Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (539)
Games in Android Showcase (133)
games submitted by our members
Games in WIP (603)
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: Riven (posted 2014-06-23 12:15:38, viewed 65 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   368   369   370   371   372   373   374   375   376   377   378   379   380   381   382   383   384   385   386   387   388   389   390   391   392   393   394   395   396   397   398   399   400   401   402   403   404   405   406   407   408   409   410   411   412   413   414   415   416   417   418   419   420   421   422   423   424   425   426   427   428   429   430   431   432   433   434   435   436   437   438   439   440   441   442   443   444   445   446   447   448   449   450   451  
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;

import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.ContextAttribs;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GLContext;
import org.lwjgl.opengl.PixelFormat;

import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL12.*;
import static org.lwjgl.opengl.GL13.*;
import static org.lwjgl.opengl.GL14.*;
import static org.lwjgl.opengl.GL15.*;
import static org.lwjgl.opengl.GL20.*;
import static org.lwjgl.opengl.GL21.*;
import static org.lwjgl.opengl.GL30.*;
import static org.lwjgl.opengl.GL31.*;
import static org.lwjgl.opengl.GL32.*;
import static org.lwjgl.opengl.GL33.*;
import static org.lwjgl.opengl.GL40.*;
import static org.lwjgl.opengl.GL41.*;
import static org.lwjgl.opengl.GL42.*;
import static org.lwjgl.opengl.GL43.*;
import static org.lwjgl.opengl.GL44.*;

public class DrawIndirect {

   public static void main(String[] args) throws Exception {
      int wWindow = 800;
      int hWindow = 600;

      ContextAttribs contextAttributes = new ContextAttribs(3, 3)//
            .withForwardCompatible(false)//
            .withProfileCore(true)//
            .withDebug(false);

      Display.setDisplayMode(new DisplayMode(wWindow, hWindow));
      Display.setTitle("DrawIndirect");

      for(int samples = 8; samples >= 0; samples--) {
         int alpha = 8;
         int depth = 8;
         int stencil = 8;

         PixelFormat pixelFormat = new PixelFormat(alpha, depth, stencil, samples);
         try {
            System.out.println("samples=" + samples);
            Display.create(pixelFormat, contextAttributes);
            break;
         }
         catch (LWJGLException exc) {
            continue;
         }
      }

      System.out.println(glGetString(GL_RENDERER));
      System.out.println(glGetString(GL_VERSION));

      int drawStrategy;
      if(GLContext.getCapabilities().GL_ARB_multi_draw_indirect) {
         // glMultiDrawElementsIndirect
         drawStrategy = 4;
      }
      else if(GLContext.getCapabilities().GL_ARB_base_instance) {
         // glDrawElementsInstancedBaseVertexBaseInstance
         drawStrategy = 3;
      }
      else {
         throw new IllegalStateException();
      }
      drawStrategy = 4;
      System.out.println("drawStrategy=" + drawStrategy);

      int baseInstance = 0; // does NOT affect gl_InstanceID, just the offset for instanced vertex-attrs
      int baseVertex = 0;
      int firstIndex = 0;

      final int[] circleEdges = { 7, 5, 3 };
      final int[] circleInstances = { 4, 11, 5 };
      final int drawCount = circleEdges.length;

      final int bufferAccessFlags = GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT;

      final int vertexBufferStride = (3 + 4) << 2;
      final int idInstanceDrawStride = (1 + 1 + 1 + 1) << 2;

      int vertexBufId;
      int indicesBufId;
      int multiDrawCommandBufId;
      int idInstanceDrawBufId;
      MultiDrawCommand drawCmd;
      {
         // calculate the space we need to hold all data

         int vertexBufferSizeof = 0;
         int indexBufferSizeof = 0;
         int commandStructSizeof = 0;
         int idInstanceDrawSizeof = 0;

         for(int d = 0; d < drawCount; d++) {
            vertexBufferSizeof += (1 + circleEdges[d] * 2) * vertexBufferStride;
            indexBufferSizeof += (circleEdges[d] * 3) << 1;
            commandStructSizeof += MultiDrawCommand.strideBytes;
            idInstanceDrawSizeof += circleInstances[d] * idInstanceDrawStride;
         }

         // create the VBOs and map them as persistent buffers

         vertexBufId = glGenBuffers();
         glBindBuffer(GL_ARRAY_BUFFER, vertexBufId);
         glBufferStorage(GL_ARRAY_BUFFER, vertexBufferSizeof, bufferAccessFlags);
         FloatBuffer vertexBuffer = glMapBufferRange(GL_ARRAY_BUFFER, 0, vertexBufferSizeof, bufferAccessFlags, null).asFloatBuffer();

         indicesBufId = glGenBuffers();
         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesBufId);
         glBufferStorage(GL_ELEMENT_ARRAY_BUFFER, indexBufferSizeof, bufferAccessFlags);
         ShortBuffer indexBuffer = glMapBufferRange(GL_ELEMENT_ARRAY_BUFFER, 0, indexBufferSizeof, bufferAccessFlags, null).asShortBuffer();

         multiDrawCommandBufId = glGenBuffers();
         glBindBuffer(GL_DRAW_INDIRECT_BUFFER, multiDrawCommandBufId);
         glBufferStorage(GL_DRAW_INDIRECT_BUFFER, commandStructSizeof, bufferAccessFlags);
         IntBuffer multiDrawCommandBuffer = glMapBufferRange(GL_DRAW_INDIRECT_BUFFER, 0, commandStructSizeof, bufferAccessFlags, null).asIntBuffer();

         idInstanceDrawBufId = glGenBuffers();
         glBindBuffer(GL_ARRAY_BUFFER, idInstanceDrawBufId);
         glBufferStorage(GL_ARRAY_BUFFER, idInstanceDrawSizeof, bufferAccessFlags);
         FloatBuffer idInstanceDrawBuffer = glMapBufferRange(GL_ARRAY_BUFFER, 0, idInstanceDrawSizeof, bufferAccessFlags, null).asFloatBuffer();

         // 

         drawCmd = new MultiDrawCommand(multiDrawCommandBuffer);
         int indexOffset = 0;

         for(int drawID = 0; drawID < drawCount; drawID++) {

            int triangleCount = circleEdges[drawID];

            // draw a circle using N triangles

            int vertexCount;
            {
               float ox = -0.66f;

               int vbPos1 = vertexBuffer.position();
               vertexBuffer.put(0 + ox).put(0).put(0.0f); // vertex
               vertexBuffer.put(1).put(1).put(0).put(0.8f); // color

               for(int i = 0; i < triangleCount; i++) {
                  final float scale = 1.0f / 16;
                  float x1 = (float) Math.cos((float) (i + 0) / triangleCount * Math.PI * 2.0) * scale;
                  float y1 = (float) Math.sin((float) (i + 0) / triangleCount * Math.PI * 2.0) * scale;
                  float x2 = (float) Math.cos((float) (i + 1) / triangleCount * Math.PI * 2.0) * scale;
                  float y2 = (float) Math.sin((float) (i + 1) / triangleCount * Math.PI * 2.0) * scale;

                  vertexBuffer.put(x1 + ox).put(y1).put(0.0f); // vertex
                  vertexBuffer.put(1).put(0).put(0).put(0.8f); // color

                  vertexBuffer.put(x2 + ox).put(y2).put(0.0f); // vertex
                  vertexBuffer.put(0).put(1).put(0).put(0.8f); // color
               }
               int vbPos2 = vertexBuffer.position();
               vertexCount = ((vbPos2 - vbPos1) << 2) / vertexBufferStride;
            }

            int indexCount;
            {
               int ibPos1 = indexBuffer.position();
               for(int i = 0; i < triangleCount; i++) {
                  indexBuffer.put((short) (indexOffset + 0));
                  indexBuffer.put((short) (indexOffset + 1 + i * 2 + 0));
                  indexBuffer.put((short) (indexOffset + 1 + i * 2 + 1));
               }
               int ibPos2 = indexBuffer.position();
               indexCount = (ibPos2 - ibPos1);

               if(drawStrategy == 2)
                  indexOffset += vertexCount;
            }

            int instanceCount = circleInstances[drawID];
            {
               for(int instanceID = 0; instanceID < instanceCount; instanceID++)
                  idInstanceDrawBuffer.put(instanceID).put(instanceCount).put(drawID).put(drawCount);
            }

            drawCmd.indicesCount(indexCount);
            drawCmd.instanceCount(instanceCount);
            drawCmd.firstIndex(firstIndex);
            drawCmd.baseVertex(baseVertex);
            drawCmd.baseInstance(baseInstance);

            baseVertex += vertexCount;
            baseInstance += drawCmd.instanceCount();

            drawCmd.advanceStructView();
         }

         if(vertexBuffer.hasRemaining())
            throw new IllegalStateException();
         if(indexBuffer.hasRemaining())
            throw new IllegalStateException();
         if(multiDrawCommandBuffer.hasRemaining())
            throw new IllegalStateException();
         if(idInstanceDrawBuffer.hasRemaining())
            throw new IllegalStateException();
      }
      glBindBuffer(GL_ARRAY_BUFFER, 0);
      glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
      glBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0);
      glBindBuffer(GL_ARRAY_BUFFER, 0);

      // create program from shaders

      int vertexShader;
      {
         vertexShader = glCreateShader(GL_VERTEX_SHADER);
         glShaderSource(vertexShader, OpenGL.readFileAsString("shaders/indirect.vert"));
         glCompileShader(vertexShader);
         int compileStatus = glGetShaderi(vertexShader, GL_COMPILE_STATUS);
         if(compileStatus == GL_FALSE) {
            throw new IllegalStateException(glGetShaderInfoLog(vertexShader, 64 * 1024));
         }
      }

      int fragmentShader;
      {
         fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
         glShaderSource(fragmentShader, OpenGL.readFileAsString("shaders/indirect.frag"));
         glCompileShader(fragmentShader);
         int compileStatus = glGetShaderi(fragmentShader, GL_COMPILE_STATUS);
         if(compileStatus == GL_FALSE) {
            throw new IllegalStateException(glGetShaderInfoLog(fragmentShader, 64 * 1024));
         }
      }

      int program = glCreateProgram();
      glAttachShader(program, vertexShader);
      glAttachShader(program, fragmentShader);

      {
         glLinkProgram(program);
         int linkStatus = glGetProgrami(program, GL_LINK_STATUS);
         if(linkStatus == GL_FALSE) {
            throw new IllegalStateException(glGetProgramInfoLog(program, 64 * 1024));
         }
      }
      {
         glValidateProgram(program);
         if(glGetProgrami(program, GL_VALIDATE_STATUS) == GL_FALSE) {
            throw new IllegalStateException(glGetProgramInfoLog(program, 64 * 1024));
         }
      }

      {
         System.out.println("vert.position  @ " + glGetAttribLocation(program, "position"));
         System.out.println("vert.color     @ " + glGetAttribLocation(program, "color"));
         System.out.println("vert.instance_draw  @ " + glGetAttribLocation(program, "instance_draw"));
         System.out.println("frag.drawcolor @ " + glGetFragDataLocation(program, "drawcolor"));
      }

      glUseProgram(program);

      System.out.println(glGetError());

      // create and configure VAO

      int vaoId = glGenVertexArrays();
      glBindVertexArray(vaoId);
      glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesBufId);
      glBindBuffer(GL_DRAW_INDIRECT_BUFFER, multiDrawCommandBufId);

      {
         long vertexBufferOffset = 0;
         {
            int attrIndex = glGetAttribLocation(program, "position");
            int numComponents = 3;
            int type = GL_FLOAT;
            boolean doNormalize = false;

            glBindBuffer(GL_ARRAY_BUFFER, vertexBufId);
            glVertexAttribPointer(attrIndex, numComponents, type, doNormalize, vertexBufferStride, vertexBufferOffset);
            glBindBuffer(GL_ARRAY_BUFFER, 0);

            glEnableVertexAttribArray(attrIndex);

            vertexBufferOffset += numComponents << 2;
         }
         {
            int attrIndex = glGetAttribLocation(program, "color");
            int numComponents = 4;
            int type = GL_FLOAT;
            boolean doNormalize = false;

            glBindBuffer(GL_ARRAY_BUFFER, vertexBufId);
            glVertexAttribPointer(attrIndex, numComponents, type, doNormalize, vertexBufferStride, vertexBufferOffset);
            glBindBuffer(GL_ARRAY_BUFFER, 0);

            glEnableVertexAttribArray(attrIndex);

            vertexBufferOffset += numComponents << 2;
         }
         if(vertexBufferOffset != vertexBufferStride)
            throw new IllegalStateException();
      }
      {
         long idInstanceDrawOffset = 0;
         {
            int attrIndex = glGetAttribLocation(program, "instance_draw");
            int numComponents = 4;
            int type = GL_FLOAT;
            boolean doNormalize = false;

            glBindBuffer(GL_ARRAY_BUFFER, idInstanceDrawBufId);
            glVertexAttribPointer(attrIndex, numComponents, type, doNormalize, idInstanceDrawStride, idInstanceDrawOffset);
            glVertexAttribDivisor(attrIndex, 1); // advance one attribute every 1 instance(s)
            glBindBuffer(GL_ARRAY_BUFFER, 0);

            glEnableVertexAttribArray(attrIndex);

            idInstanceDrawOffset += numComponents << 2;
         }
         if(idInstanceDrawOffset != idInstanceDrawStride)
            throw new IllegalStateException();
      }

      glBindVertexArray(0);

      System.out.println(glGetError());

      glEnable(GL_BLEND);
      //glBlendFunc(GL_ONE, GL_ONE);
      glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

      glViewport(0, 0, wWindow, hWindow);
      glClearColor(0, 0, 0, 1);

      long lastSec = System.currentTimeMillis();
      int frameCounter = 0;

      while (!Display.isCloseRequested()) {

         glClear(GL_COLOR_BUFFER_BIT);

         glBindVertexArray(vaoId);

         switch (drawStrategy) {

         case 3: // OpenGL 4.2
            drawCmd.resetStructView();
            for(int d = 0; d < drawCount; d++) {
               glDrawElementsInstancedBaseVertexBaseInstance(GL_TRIANGLES, //
                     drawCmd.indicesCount(), GL_UNSIGNED_SHORT, 0L + (drawCmd.firstIndex() << 1), //
                     drawCmd.instanceCount(), drawCmd.baseVertex(), drawCmd.baseInstance());

               drawCmd.advanceStructView();
            }
            break;

         case 4: // OpenGL 4.3
            glMultiDrawElementsIndirect(GL_TRIANGLES, GL_UNSIGNED_SHORT, 0L, drawCount, MultiDrawCommand.strideBytes);
            break;
         }
         glBindVertexArray(0);

         // swap
         //Display.sync(60);
         Display.update();

         frameCounter++;
         if(System.currentTimeMillis() - lastSec >= 1000) {
            System.out.println("fps: " + frameCounter);
            lastSec += 1000;
            frameCounter = 0;
         }
      }

      Display.destroy();
   }

   private static class MultiDrawCommand {
      public static final int strideWords = 5;
      public static final int strideBytes = strideWords << 2;

      private final IntBuffer backing;

      public MultiDrawCommand(IntBuffer backing) {
         this.backing = backing;
      }

      public void resetStructView() {
         backing.position(0);
      }

      public void advanceStructView() {
         backing.position(backing.position() + strideWords);
      }

      //

      public int indicesCount() {
         return backing.get(backing.position() + 0);
      }

      public void indicesCount(int count) {
         backing.put(backing.position() + 0, count);
      }

      //

      public int instanceCount() {
         return backing.get(backing.position() + 1);
      }

      public void instanceCount(int instanceCount) {
         backing.put(backing.position() + 1, instanceCount);
      }

      //

      public int firstIndex() {
         return backing.get(backing.position() + 2);
      }

      public void firstIndex(int firstIndex) {
         backing.put(backing.position() + 2, firstIndex);
      }

      //

      public int baseVertex() {
         return backing.get(backing.position() + 3);
      }

      public void baseVertex(int baseVertex) {
         backing.put(backing.position() + 3, baseVertex);
      }

      //

      public int baseInstance() {
         return backing.get(backing.position() + 4);
      }

      public void baseInstance(int baseInstance) {
         backing.put(backing.position() + 4, baseInstance);
      }
   }
}


1   2   3   4   5   6   7   8   9   10   11   12   13   14   15   16   17   18   19   20   21   22   23  
#version 330 core
layout(location = 0) in vec3 position;
layout(location = 1) in vec4 color;
layout(location = 2) in vec4 instance_draw;


out vec3 fragposition;
out vec4 fragcolor;

void main()
{
   float instanceID    = instance_draw.x;
   float instanceCount = instance_draw.y;
   float drawID        = instance_draw.z;
   float drawCount     = instance_draw.w;
   
   vec3 pos = vec3(position) + vec3(instanceID, drawID, 0.0) * 0.125;
   
   fragcolor = vec4(color.r, color.g, instanceID / (instanceCount-1.0), color.a);
    fragposition = pos;
    
    gl_Position = vec4(pos, 1.0);
}


1   2   3   4   5   6   7   8   9   10   11  
#version 330 core

in vec3 fragposition;
in vec4 fragcolor;

layout(location = 0) out vec4 drawcolor;

void main()
{
   drawcolor = fragcolor;
}





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.

rwatson462 (37 views)
2014-12-15 09:26:44

Mr.CodeIt (31 views)
2014-12-14 19:50:38

BurntPizza (62 views)
2014-12-09 22:41:13

BurntPizza (99 views)
2014-12-08 04:46:31

JscottyBieshaar (60 views)
2014-12-05 12:39:02

SHC (74 views)
2014-12-03 16:27:13

CopyableCougar4 (77 views)
2014-11-29 21:32:03

toopeicgaming1999 (138 views)
2014-11-26 15:22:04

toopeicgaming1999 (127 views)
2014-11-26 15:20:36

toopeicgaming1999 (38 views)
2014-11-26 15:20:08
Resources for WIP games
by kpars
2014-12-18 10:26:14

Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50
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!