Example #1
0
  /**
   * Constructor that creates a Vertex Buffer Object with the specified GLSL attributes. (typically
   * location, texture coordinates, normals, etc.)
   *
   * @param gl The global openGL instance.
   * @param attribs One or more attributes that represent this VBO, @see GLSLAttrib
   */
  public VBO(GL3 gl, GLSLAttrib... attribs) {
    this.attribs = attribs;

    // Generate a new internal OpenGL VBO pointer
    this.vboPointer = Buffers.newDirectIntBuffer(1);
    gl.glGenVertexArrays(1, this.vboPointer);
    gl.glBindVertexArray(this.vboPointer.get(0));

    // Generate a new internal OpenGL Array Buffer pointer
    this.bufferPointer = Buffers.newDirectIntBuffer(1);
    gl.glGenBuffers(1, this.bufferPointer);
    gl.glBindBuffer(GL3.GL_ARRAY_BUFFER, this.bufferPointer.get(0));

    // Allocate enough memory
    int size = 0;
    for (final GLSLAttrib attrib : attribs) {
      size += attrib.buffer.capacity() * Buffers.SIZEOF_FLOAT;
    }

    gl.glBufferData(GL3.GL_ARRAY_BUFFER, size, (Buffer) null, GL3.GL_STATIC_DRAW);

    // Copy the GLSL Attribute data into the internal OpenGL buffer
    int nextStart = 0;
    for (final GLSLAttrib attrib : attribs) {
      gl.glBufferSubData(
          GL3.GL_ARRAY_BUFFER,
          nextStart,
          attrib.buffer.capacity() * Buffers.SIZEOF_FLOAT,
          attrib.buffer);
      nextStart += attrib.buffer.capacity() * Buffers.SIZEOF_FLOAT;
    }
  }
 public static long EGLConfigId2EGLConfig(long display, int configID) {
   final IntBuffer attrs =
       Buffers.newDirectIntBuffer(new int[] {EGL.EGL_CONFIG_ID, configID, EGL.EGL_NONE});
   final PointerBuffer configs = PointerBuffer.allocateDirect(1);
   final IntBuffer numConfigs = Buffers.newDirectIntBuffer(1);
   if (!EGL.eglChooseConfig(display, attrs, configs, 1, numConfigs)) {
     return 0;
   }
   if (numConfigs.get(0) == 0) {
     return 0;
   }
   return configs.get(0);
 }
Example #3
0
 private static List<GLCapabilitiesImmutable> getAvailableEGLConfigs(
     EGLGraphicsDevice eglDisplay, GLCapabilitiesImmutable caps) {
   final IntBuffer numConfigs = Buffers.newDirectIntBuffer(1);
   if (!EGL.eglGetConfigs(eglDisplay.getHandle(), null, 0, numConfigs)) {
     throw new GLException(
         "EGLDrawableFactory.getAvailableEGLConfigs: Get maxConfigs (eglGetConfigs) call failed, error "
             + EGLContext.toHexString(EGL.eglGetError()));
   }
   if (0 < numConfigs.get(0)) {
     final PointerBuffer configs = PointerBuffer.allocateDirect(numConfigs.get(0));
     final IntBuffer attrs = EGLGraphicsConfiguration.GLCapabilities2AttribList(caps);
     final int winattrmask = GLGraphicsConfigurationUtil.getExclusiveWinAttributeBits(caps);
     if (EGL.eglChooseConfig(
             eglDisplay.getHandle(), attrs, configs, configs.capacity(), numConfigs)
         && numConfigs.get(0) > 0) {
       return EGLGraphicsConfigurationFactory.eglConfigs2GLCaps(
           eglDisplay,
           caps.getGLProfile(),
           configs,
           numConfigs.get(0),
           winattrmask,
           false /* forceTransparentFlag */);
     }
   }
   return new ArrayList<GLCapabilitiesImmutable>(0);
 }
Example #4
0
  public static void shaderSource(final GL _gl, final int shader, final CharSequence[] source) {
    final GL2ES2 gl = _gl.getGL2ES2();
    if (!isShaderCompilerAvailable(_gl)) {
      throw new GLException("No compiler is available");
    }

    final int count = (null != source) ? source.length : 0;
    if (count == 0) {
      throw new GLException("No sources specified");
    }

    final IntBuffer lengths = Buffers.newDirectIntBuffer(count);
    for (int i = 0; i < count; i++) {
      lengths.put(i, source[i].length());
    }
    if (source instanceof String[]) {
      // rare case ..
      gl.glShaderSource(shader, count, (String[]) source, lengths);
    } else {
      final String[] tmp = new String[source.length];
      for (int i = source.length - 1; i >= 0; i--) {
        final CharSequence csq = source[i];
        if (csq instanceof String) {
          // if ShaderCode.create(.. mutableStringBuilder == false )
          tmp[i] = (String) csq;
        } else {
          // if ShaderCode.create(.. mutableStringBuilder == true )
          tmp[i] = source[i].toString();
        }
      }
      gl.glShaderSource(shader, count, tmp, lengths);
    }
  }
Example #5
0
  /**
   * Initialization method for any shader. Compiles and checks code.
   *
   * @param gl The global openGL instance.
   * @throws CompilationFailedException If the compilation of the GLSL code generated any errors.
   */
  public void init(GL3 gl) throws CompilationFailedException {
    try {
      // First, give the source to OpenGL and compile
      gl.glShaderSource(getShaderPointer(), 1, source, (int[]) null, 0);
      gl.glCompileShader(getShaderPointer());

      // Receive compilation status
      IntBuffer buf = Buffers.newDirectIntBuffer(1);
      gl.glGetShaderiv(getShaderPointer(), GL3.GL_COMPILE_STATUS, buf);
      int status = buf.get(0);

      // Check the status
      if (status == GL3.GL_FALSE) {
        // Prepare for additional information
        gl.glGetShaderiv(getShaderPointer(), GL3.GL_INFO_LOG_LENGTH, buf);
        int logLength = buf.get(0);
        byte[] reason = new byte[logLength];

        // Get additional information
        gl.glGetShaderInfoLog(getShaderPointer(), logLength, null, 0, reason, 0);

        throw new CompilationFailedException(
            "Compilation of " + filename + " failed, " + new String(reason));
      }
    } catch (UninitializedException e) {
      logger.error(e.getMessage());
    }
  }
  protected static X11ExternalGLXContext create(GLDrawableFactory factory, GLProfile glp) {
    long ctx = GLX.glXGetCurrentContext();
    if (ctx == 0) {
      throw new GLException("Error: current context null");
    }
    long display = GLX.glXGetCurrentDisplay();
    if (display == 0) {
      throw new GLException("Error: current display null");
    }
    long drawable = GLX.glXGetCurrentDrawable();
    if (drawable == 0) {
      throw new GLException(
          "Error: attempted to make an external GLDrawable without a drawable/context current");
    }
    IntBuffer val = Buffers.newDirectIntBuffer(1);

    int w, h;
    GLX.glXQueryDrawable(display, drawable, GLX.GLX_WIDTH, val);
    w = val.get(0);
    GLX.glXQueryDrawable(display, drawable, GLX.GLX_HEIGHT, val);
    h = val.get(0);

    GLX.glXQueryContext(display, ctx, GLX.GLX_SCREEN, val);
    X11GraphicsScreen x11Screen =
        (X11GraphicsScreen) X11GraphicsScreen.createScreenDevice(display, val.get(0), false);

    GLX.glXQueryContext(display, ctx, GLX.GLX_FBCONFIG_ID, val);
    X11GLXGraphicsConfiguration cfg = null;
    // sometimes glXQueryContext on an external context gives us a framebuffer config ID
    // of 0, which doesn't work in a subsequent call to glXChooseFBConfig; if this happens,
    // create and use a default config (this has been observed when running on CentOS 5.5 inside
    // of VMWare Server 2.0 with the Mesa 6.5.1 drivers)
    if (VisualIDHolder.VID_UNDEFINED == val.get(0)
        || !X11GLXGraphicsConfiguration.GLXFBConfigIDValid(
            display, x11Screen.getIndex(), val.get(0))) {
      GLCapabilities glcapsDefault = new GLCapabilities(GLProfile.getDefault());
      cfg =
          X11GLXGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(
              glcapsDefault, glcapsDefault, null, x11Screen, VisualIDHolder.VID_UNDEFINED);
      if (DEBUG) {
        System.err.println(
            "X11ExternalGLXContext invalid FBCONFIG_ID "
                + val.get(0)
                + ", using default cfg: "
                + cfg);
      }
    } else {
      cfg = X11GLXGraphicsConfiguration.create(glp, x11Screen, val.get(0));
    }

    final WrappedSurface ns = new WrappedSurface(cfg, drawable, w, h, true);
    return new X11ExternalGLXContext(new Drawable(factory, ns), ctx);
  }
Example #7
0
  public void updateVisibleOctant(GL2 gl) {
    if (leavesCount > 0) {
      // Limits
      refreshLimits();

      // Switch to OpenGL2 select mode
      int capacity = 1 * 4 * leavesCount; // Each object take in maximium : 4 * name stack depth
      IntBuffer hitsBuffer = Buffers.newDirectIntBuffer(capacity);
      gl.glSelectBuffer(hitsBuffer.capacity(), hitsBuffer);
      gl.glRenderMode(GL2.GL_SELECT);
      gl.glInitNames();
      gl.glPushName(0);
      gl.glDisable(GL2.GL_CULL_FACE); // Disable flags
      // Draw the nodes cube in the select buffer
      for (Octant n : leaves) {
        if (n != null) {
          gl.glLoadName(n.leafId);
          n.displayOctant(gl);
          n.visible = false;
        }
      }
      visibleLeaves = 0;
      int nbRecords = gl.glRenderMode(GL2.GL_RENDER);
      if (vizController.getVizModel().isCulling()) {
        gl.glEnable(GL2.GL_CULL_FACE);
        gl.glCullFace(GL2.GL_BACK);
      }

      // Get the hits and add the nodes' objects to the array
      int depth = Integer.MAX_VALUE;
      int minDepth = -1;
      for (int i = 0; i < nbRecords; i++) {
        int hit = hitsBuffer.get(i * 4 + 3); // -1 Because of the glPushName(0)
        int minZ = hitsBuffer.get(i * 4 + 1);
        if (minZ < depth) {
          depth = minZ;
          minDepth = hit;
        }

        Octant nodeHit = leaves[hit];
        nodeHit.visible = true;
        visibleLeaves++;
      }
      if (minDepth != -1) {
        Octant closestOctant = leaves[minDepth];
        Vec3f pos =
            new Vec3f(closestOctant.getPosX(), closestOctant.getPosY(), closestOctant.getPosZ());
        limits.setClosestPoint(pos);
      }
    }
  }
Example #8
0
  public void writeSamples(byte[] data, int offset, int length) {
    if (length < 0) throw new IllegalArgumentException("length cannot be < 0.");

    if (sourceID == -1) {
      sourceID = audio.obtainSource(true);
      if (sourceID == -1) return;
      if (buffers == null) {
        buffers = Buffers.newDirectIntBuffer(bufferCount);
        audio.getAL().alGenBuffers(buffers.limit(), buffers);
        if (audio.getAL().alGetError() != ALConstants.AL_NO_ERROR)
          throw new GdxRuntimeException("Unabe to allocate audio buffers.");
      }
      audio.getAL().alSourcei(sourceID, ALConstants.AL_LOOPING, ALConstants.AL_FALSE);
      audio.getAL().alSourcef(sourceID, ALConstants.AL_GAIN, volume);
      // Fill initial buffers.
      int queuedBuffers = 0;
      for (int i = 0; i < bufferCount; i++) {
        int bufferID = buffers.get(i);
        int written = Math.min(bufferSize, length);
        tempBuffer.clear();
        tempBuffer.put(data, offset, written).flip();
        audio
            .getAL()
            .alBufferData(bufferID, format, tempBuffer, tempBuffer.remaining(), sampleRate);
        ib.put(0, bufferID).rewind();
        audio.getAL().alSourceQueueBuffers(sourceID, ib.limit(), ib);
        length -= written;
        offset += written;
        queuedBuffers++;
      }
      // Queue rest of buffers, empty.
      tempBuffer.clear().flip();
      for (int i = queuedBuffers; i < bufferCount; i++) {
        int bufferID = buffers.get(i);
        audio
            .getAL()
            .alBufferData(bufferID, format, tempBuffer, tempBuffer.remaining(), sampleRate);
        audio.getAL().alSourceQueueBuffers(sourceID, ib.limit(), ib);
      }
      audio.getAL().alSourcePlay(sourceID);
      isPlaying = true;
    }

    while (length > 0) {
      int written = fillBuffer(data, offset, length);
      length -= written;
      offset += written;
    }
  }
  protected static IntBuffer generateTriStripIndices(int width, int height, boolean wrapWidth) {
    int w = width - 1;
    if (!wrapWidth) {
      width--;
    }
    height--;
    int indexCount = 2 * width * height + 4 * width - 2;
    IntBuffer buffer = Buffers.newDirectIntBuffer(indexCount);
    int k = 0;
    for (int i = 0; i < width; i++) {
      buffer.put(k);
      if (i > 0) {
        buffer.put(++k);
        buffer.put(k);
      }

      if (i % 2 == 0) // even
      {
        buffer.put(++k);
        for (int j = 0; j < height; j++) {
          k += w;
          buffer.put(k);
          buffer.put(++k);
        }
      } else
      // odd
      {
        buffer.put(--k);
        for (int j = 0; j < height; j++) {
          k -= w;
          buffer.put(k);
          buffer.put(--k);
        }
      }
    }

    if (wrapWidth) {
      boolean even = width % 2 == 0;
      int fixLast = 2 * height + 3 - (even ? 0 : 1);
      for (int i = indexCount - fixLast + 1; i < indexCount; i += 2) {
        buffer.put(i, buffer.get(i) - width);
      }
      if (even) {
        buffer.put(fixLast, buffer.get(fixLast) - width);
      }
    }

    return buffer;
  }
  static int EGLConfigDrawableTypeBits(final EGLGraphicsDevice device, final long config) {
    int val = 0;

    final IntBuffer stype = Buffers.newDirectIntBuffer(1);
    if (!EGL.eglGetConfigAttrib(device.getHandle(), config, EGL.EGL_SURFACE_TYPE, stype)) {
      throw new GLException("Could not determine EGL_SURFACE_TYPE");
    }

    final int _stype = stype.get(0);
    if (0 != (_stype & EGL.EGL_WINDOW_BIT)) {
      val |= GLGraphicsConfigurationUtil.WINDOW_BIT;
    }
    if (0 != (_stype & EGL.EGL_PIXMAP_BIT)) {
      val |= GLGraphicsConfigurationUtil.BITMAP_BIT;
    }
    if (0 != (_stype & EGL.EGL_PBUFFER_BIT)) {
      val |= GLGraphicsConfigurationUtil.PBUFFER_BIT | GLGraphicsConfigurationUtil.FBO_BIT;
    }
    return val;
  }
  public static IntBuffer CreatePBufferSurfaceAttribList(int width, int height, int texFormat) {
    IntBuffer attrs = Buffers.newDirectIntBuffer(16);
    int idx = 0;

    attrs.put(idx++, EGL.EGL_WIDTH);
    attrs.put(idx++, width);

    attrs.put(idx++, EGL.EGL_HEIGHT);
    attrs.put(idx++, height);

    attrs.put(idx++, EGL.EGL_TEXTURE_FORMAT);
    attrs.put(idx++, texFormat);

    attrs.put(idx++, EGL.EGL_TEXTURE_TARGET);
    attrs.put(idx++, EGL.EGL_NO_TEXTURE == texFormat ? EGL.EGL_NO_TEXTURE : EGL.EGL_TEXTURE_2D);

    attrs.put(idx++, EGL.EGL_NONE);

    return attrs;
  }
  public static boolean isEGLConfigValid(long display, long config) {
    if (0 == config) {
      return false;
    }
    final IntBuffer val = Buffers.newDirectIntBuffer(1);

    // get the configID
    if (!EGL.eglGetConfigAttrib(display, config, EGL.EGL_CONFIG_ID, val)) {
      final int eglErr = EGL.eglGetError();
      if (DEBUG) {
        System.err.println(
            dbgCfgFailIntro
                + "EGL_CONFIG_ID"
                + dbgCfgFailForConfig
                + toHexString(config)
                + dbgCfgFailError
                + toHexString(eglErr));
      }
      return false;
    }
    return true;
  }
  public static IntBuffer GLCapabilities2AttribList(GLCapabilitiesImmutable caps) {
    final IntBuffer attrs = Buffers.newDirectIntBuffer(32);
    int idx = 0;

    attrs.put(idx++, EGL.EGL_SURFACE_TYPE);
    final int surfaceType;
    if (caps.isOnscreen()) {
      surfaceType = EGL.EGL_WINDOW_BIT;
    } else if (caps.isFBO()) {
      surfaceType = EGL.EGL_PBUFFER_BIT; // native replacement!
    } else if (caps.isPBuffer()) {
      surfaceType = EGL.EGL_PBUFFER_BIT;
    } else if (caps.isBitmap()) {
      surfaceType = EGL.EGL_PIXMAP_BIT;
    } else {
      throw new GLException("no surface type set in caps: " + caps);
    }
    attrs.put(idx++, surfaceType);

    attrs.put(idx++, EGL.EGL_RED_SIZE);
    attrs.put(idx++, caps.getRedBits());

    attrs.put(idx++, EGL.EGL_GREEN_SIZE);
    attrs.put(idx++, caps.getGreenBits());

    attrs.put(idx++, EGL.EGL_BLUE_SIZE);
    attrs.put(idx++, caps.getBlueBits());

    if (caps.getAlphaBits() > 0) {
      attrs.put(idx++, EGL.EGL_ALPHA_SIZE);
      attrs.put(idx++, caps.getAlphaBits());
    }

    if (caps.getStencilBits() > 0) {
      attrs.put(idx++, EGL.EGL_STENCIL_SIZE);
      attrs.put(idx++, caps.getStencilBits());
    }

    attrs.put(idx++, EGL.EGL_DEPTH_SIZE);
    attrs.put(idx++, caps.getDepthBits());

    if (caps.getSampleBuffers()) {
      if (caps.getSampleExtension().equals(GLGraphicsConfigurationUtil.NV_coverage_sample)) {
        attrs.put(idx++, EGLExt.EGL_COVERAGE_BUFFERS_NV);
        attrs.put(idx++, 1);
        attrs.put(idx++, EGLExt.EGL_COVERAGE_SAMPLES_NV);
        attrs.put(idx++, caps.getNumSamples());
      } else {
        // try default ..
        attrs.put(idx++, EGL.EGL_SAMPLE_BUFFERS);
        attrs.put(idx++, 1);
        attrs.put(idx++, EGL.EGL_SAMPLES);
        attrs.put(idx++, caps.getNumSamples());
      }
    }

    attrs.put(idx++, EGL.EGL_TRANSPARENT_TYPE);
    attrs.put(idx++, caps.isBackgroundOpaque() ? EGL.EGL_NONE : EGL.EGL_TRANSPARENT_TYPE);

    // 22

    if (!caps.isBackgroundOpaque()) {
      attrs.put(idx++, EGL.EGL_TRANSPARENT_RED_VALUE);
      attrs.put(
          idx++,
          caps.getTransparentRedValue() >= 0 ? caps.getTransparentRedValue() : EGL.EGL_DONT_CARE);

      attrs.put(idx++, EGL.EGL_TRANSPARENT_GREEN_VALUE);
      attrs.put(
          idx++,
          caps.getTransparentGreenValue() >= 0
              ? caps.getTransparentGreenValue()
              : EGL.EGL_DONT_CARE);

      attrs.put(idx++, EGL.EGL_TRANSPARENT_BLUE_VALUE);
      attrs.put(
          idx++,
          caps.getTransparentBlueValue() >= 0 ? caps.getTransparentBlueValue() : EGL.EGL_DONT_CARE);

      /**
       * Not define in EGL attrs.put(idx++, EGL.EGL_TRANSPARENT_ALPHA_VALUE; attrs.put(idx++,
       * caps.getTransparentAlphaValue()>=0?caps.getTransparentAlphaValue():EGL.EGL_DONT_CARE;
       */
    }

    // 28
    attrs.put(idx++, EGL.EGL_RENDERABLE_TYPE);
    if (caps.getGLProfile().usesNativeGLES1()) {
      attrs.put(idx++, EGL.EGL_OPENGL_ES_BIT);
    } else if (caps.getGLProfile().usesNativeGLES2()) {
      attrs.put(idx++, EGL.EGL_OPENGL_ES2_BIT);
    } else if (caps.getGLProfile().usesNativeGLES3()) {
      if (GLRendererQuirks.existStickyDeviceQuirk(
          GLDrawableFactory.getEGLFactory().getDefaultDevice(),
          GLRendererQuirks.GLES3ViaEGLES2Config)) {
        attrs.put(idx++, EGL.EGL_OPENGL_ES2_BIT);
      } else {
        attrs.put(idx++, EGLExt.EGL_OPENGL_ES3_BIT_KHR);
      }
    } else {
      attrs.put(idx++, EGL.EGL_OPENGL_BIT);
    }

    // 30

    attrs.put(idx++, EGL.EGL_NONE);

    return attrs;
  }
Example #14
0
  public void updateSelectedOctant(GL2 gl, GLU glu, float[] mousePosition, float[] pickRectangle) {
    if (visibleLeaves > 0) {
      // Start Picking mode
      int capacity = 1 * 4 * visibleLeaves; // Each object take in maximium : 4 * name stack depth
      IntBuffer hitsBuffer = Buffers.newDirectIntBuffer(capacity);

      gl.glSelectBuffer(hitsBuffer.capacity(), hitsBuffer);
      gl.glRenderMode(GL2.GL_SELECT);
      gl.glDisable(GL2.GL_CULL_FACE); // Disable flags

      gl.glInitNames();
      gl.glPushName(0);

      gl.glMatrixMode(GL2.GL_PROJECTION);
      gl.glPushMatrix();
      gl.glLoadIdentity();

      glu.gluPickMatrix(
          mousePosition[0],
          mousePosition[1],
          pickRectangle[0],
          pickRectangle[1],
          drawable.getViewport());
      gl.glMultMatrixf(drawable.getProjectionMatrix());

      gl.glMatrixMode(GL2.GL_MODELVIEW);

      // Draw the nodes' cube int the select buffer
      List<Octant> visibleLeaves = new ArrayList<Octant>();
      for (Octant n : leaves) {
        if (n != null && n.visible) {
          int i = visibleLeaves.size() + 1;
          visibleLeaves.add(n);
          gl.glLoadName(i);
          n.displayOctant(gl);
        }
      }

      // Restoring the original projection matrix
      gl.glMatrixMode(GL2.GL_PROJECTION);
      gl.glPopMatrix();
      gl.glMatrixMode(GL2.GL_MODELVIEW);
      gl.glFlush();

      // Returning to normal rendering mode
      int nbRecords = gl.glRenderMode(GL2.GL_RENDER);
      if (vizController.getVizModel().isCulling()) {
        gl.glEnable(GL2.GL_CULL_FACE);
        gl.glCullFace(GL2.GL_BACK);
      }

      // Clean previous selection
      selectedLeaves.clear();

      // Get the hits and put the node under selection in the selectionArray
      for (int i = 0; i < nbRecords; i++) {
        int hit = hitsBuffer.get(i * 4 + 3) - 1; // -1 Because of the glPushName(0)

        Octant nodeHit = visibleLeaves.get(hit);
        selectedLeaves.add(nodeHit);
      }
    }
  }
Example #15
0
  @Override
  protected boolean createImpl(GLContextImpl shareWith) throws GLException {
    final EGLGraphicsConfiguration config =
        (EGLGraphicsConfiguration) drawable.getNativeSurface().getGraphicsConfiguration();
    final long eglDisplay = config.getScreen().getDevice().getHandle();
    final GLProfile glProfile = drawable.getGLProfile();
    final long eglConfig = config.getNativeConfig();
    long shareWithHandle = EGL.EGL_NO_CONTEXT;

    if (0 == eglDisplay) {
      throw new GLException(
          "Error: attempted to create an OpenGL context without a display connection");
    }
    if (0 == eglConfig) {
      throw new GLException(
          "Error: attempted to create an OpenGL context without a graphics configuration");
    }

    try {
      // might be unavailable on EGL < 1.2
      if (!EGL.eglBindAPI(EGL.EGL_OPENGL_ES_API)) {
        throw new GLException(
            "Catched: eglBindAPI to ES failed , error 0x" + Integer.toHexString(EGL.eglGetError()));
      }
    } catch (GLException glex) {
      if (DEBUG) {
        glex.printStackTrace();
      }
    }

    if (shareWith != null) {
      shareWithHandle = shareWith.getHandle();
      if (shareWithHandle == 0) {
        throw new GLException("GLContextShareSet returned an invalid OpenGL context");
      }
    }

    final IntBuffer contextAttrsNIO;
    {
      final int[] contextAttrs = new int[] {EGL.EGL_CONTEXT_CLIENT_VERSION, -1, EGL.EGL_NONE};
      if (glProfile.usesNativeGLES2()) {
        contextAttrs[1] = 2;
      } else if (glProfile.usesNativeGLES1()) {
        contextAttrs[1] = 1;
      } else {
        throw new GLException("Error creating OpenGL context - invalid GLProfile: " + glProfile);
      }
      contextAttrsNIO = Buffers.newDirectIntBuffer(contextAttrs);
    }
    contextHandle = EGL.eglCreateContext(eglDisplay, eglConfig, shareWithHandle, contextAttrsNIO);
    if (contextHandle == 0) {
      throw new GLException(
          "Error creating OpenGL context: eglDisplay "
              + toHexString(eglDisplay)
              + ", eglConfig "
              + config
              + ", "
              + glProfile
              + ", shareWith "
              + toHexString(shareWithHandle)
              + ", error "
              + toHexString(EGL.eglGetError()));
    }
    if (DEBUG) {
      System.err.println(
          getThreadName()
              + ": Created OpenGL context 0x"
              + Long.toHexString(contextHandle)
              + ",\n\twrite surface 0x"
              + Long.toHexString(drawable.getHandle())
              + ",\n\tread  surface 0x"
              + Long.toHexString(drawableRead.getHandle())
              + ",\n\t"
              + this
              + ",\n\tsharing with 0x"
              + Long.toHexString(shareWithHandle));
    }
    if (!EGL.eglMakeCurrent(
        eglDisplay, drawable.getHandle(), drawableRead.getHandle(), contextHandle)) {
      throw new GLException(
          "Error making context "
              + toHexString(contextHandle)
              + " current: error code "
              + toHexString(EGL.eglGetError()));
    }
    setGLFunctionAvailability(true, glProfile.usesNativeGLES2() ? 2 : 1, 0, CTX_PROFILE_ES);
    return true;
  }
Example #16
0
  private void drawCube() {
    float[] vertices =
        new float[] {
          0.500000f,
          0.500000f,
          0.500000f,
          -0.500000f,
          0.500000f,
          0.500000f,
          0.500000f,
          -0.500000f,
          0.500000f,
          -0.500000f,
          -0.500000f,
          0.500000f,
          0.500000f,
          0.500000f,
          -0.500000f,
          -0.500000f,
          0.500000f,
          -0.500000f,
          0.500000f,
          -0.500000f,
          -0.500000f,
          -0.500000f,
          -0.500000f,
          -0.500000f
        };

    int[] indices =
        new int[] {
          0, 1, 2, 3, 2, 1, 0, 2, 4, 6, 4, 2, 0, 4, 1, 5, 1, 4, 7, 5, 6, 4, 6, 5, 7, 6, 3, 2, 3, 6,
          7, 3, 5, 1, 5, 3
        };

    float[] normals =
        new float[] {
          0.577350f,
          0.577350f,
          0.577350f,
          -0.333333f,
          0.666667f,
          0.666667f,
          0.666667f,
          -0.333333f,
          0.666667f,
          -0.666667f,
          -0.666667f,
          0.333333f,
          0.666667f,
          0.666667f,
          -0.333333f,
          -0.666667f,
          0.333333f,
          -0.666667f,
          0.333333f,
          -0.666667f,
          -0.666667f,
          -0.577350f,
          -0.577350f,
          -0.577350f
        };

    float[] colors =
        new float[] {
          0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
          1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f
        };

    gl.glEnableClientState(GL2.GL_VERTEX_ARRAY);
    gl.glEnableClientState(GL2.GL_NORMAL_ARRAY);
    gl.glEnableClientState(GL2.GL_COLOR_ARRAY);

    FloatBuffer pointsFloatBuffer = Buffers.newDirectFloatBuffer(vertices);
    IntBuffer indicesIntBuffer = Buffers.newDirectIntBuffer(indices);
    FloatBuffer colorsFloatBuffer = Buffers.newDirectFloatBuffer(colors);
    FloatBuffer normalsFloatBuffer = Buffers.newDirectFloatBuffer(normals);

    gl.glMaterialfv(GL.GL_FRONT, GL2.GL_AMBIENT_AND_DIFFUSE, whiteMaterial);

    gl.glVertexPointer(3, GL.GL_FLOAT, 0, pointsFloatBuffer);
    gl.glNormalPointer(GL.GL_FLOAT, normals.length, normalsFloatBuffer);
    gl.glColorPointer(3, GL.GL_FLOAT, 0, colorsFloatBuffer);
    //		//gl.glPolygonMode (GL2.GL_FRONT, GL2.GL_FILL);
    //		gl.glPolygonMode (GL2.GL_BACK, GL2.GL_LINE);
    gl.glDrawElements(GL.GL_TRIANGLES, indices.length, GL.GL_UNSIGNED_INT, indicesIntBuffer);

    gl.glDisableClientState(GL2.GL_COLOR_ARRAY);
    gl.glDisableClientState(GL2.GL_NORMAL_ARRAY);
    gl.glDisableClientState(GL2.GL_VERTEX_ARRAY);
  }
  /**
   * @param defaultQuirks GLRendererQuirks of the EGLDrawableFactory's defaultDevice
   * @param device
   * @param glp desired GLProfile, may be null
   * @param config
   * @param winattrmask
   * @param forceTransparentFlag
   * @return
   */
  public static EGLGLCapabilities EGLConfig2Capabilities(
      GLRendererQuirks defaultQuirks,
      EGLGraphicsDevice device,
      GLProfile glp,
      long config,
      int winattrmask,
      boolean forceTransparentFlag) {
    final long display = device.getHandle();
    final int cfgID;
    final int rType;
    final int visualID;

    final int _attributes[] = {
      EGL.EGL_CONFIG_ID, // 0
      EGL.EGL_RENDERABLE_TYPE,
      EGL.EGL_NATIVE_VISUAL_ID,
      EGL.EGL_CONFIG_CAVEAT,
      EGL.EGL_RED_SIZE, // 4
      EGL.EGL_GREEN_SIZE,
      EGL.EGL_BLUE_SIZE,
      EGL.EGL_ALPHA_SIZE, // 7
      EGL.EGL_STENCIL_SIZE, // 8
      EGL.EGL_DEPTH_SIZE,
      EGL.EGL_TRANSPARENT_TYPE, // 10
      EGL.EGL_TRANSPARENT_RED_VALUE,
      EGL.EGL_TRANSPARENT_GREEN_VALUE,
      EGL.EGL_TRANSPARENT_BLUE_VALUE,
      EGL.EGL_SAMPLES, // 14
      EGLExt.EGL_COVERAGE_BUFFERS_NV, // 15
      EGLExt.EGL_COVERAGE_SAMPLES_NV
    };
    final IntBuffer attributes = Buffers.newDirectIntBuffer(_attributes);
    final IntBuffer values = Buffers.newDirectIntBuffer(attributes.remaining());
    EGL.eglGetConfigAttributes(display, config, attributes, values);

    // get the configID
    if (EGL.EGL_CONFIG_ID != attributes.get(0)) {
      if (DEBUG) {
        // FIXME: this happens on a ATI PC Emulation ..
        System.err.println(
            dbgCfgFailIntro
                + "ConfigID"
                + dbgCfgFailForConfig
                + toHexString(config)
                + dbgCfgFailError
                + toHexString(EGL.eglGetError()));
      }
      return null;
    }
    cfgID = values.get(0);

    if (EGL.EGL_RENDERABLE_TYPE != attributes.get(1)) {
      if (DEBUG) {
        System.err.println(
            dbgCfgFailIntro
                + "EGL_RENDERABLE_TYPE"
                + dbgCfgFailForConfig
                + toHexString(config)
                + dbgCfgFailError
                + toHexString(EGL.eglGetError()));
      }
      return null;
    }
    {
      final int rTypeOrig = values.get(1);
      if (defaultQuirks.exist(GLRendererQuirks.GLES3ViaEGLES2Config)
          && 0 != (EGL.EGL_OPENGL_ES2_BIT & rTypeOrig)) {
        rType = rTypeOrig | EGLExt.EGL_OPENGL_ES3_BIT_KHR;
      } else {
        rType = rTypeOrig;
      }
    }

    if (EGL.EGL_NATIVE_VISUAL_ID == attributes.get(2)) {
      visualID = values.get(2);
    } else {
      if (DEBUG) {
        System.err.println(
            dbgCfgFailIntro
                + "EGL_NATIVE_VISUAL_ID"
                + dbgCfgFailForConfig
                + toHexString(config)
                + dbgCfgFailError
                + toHexString(EGL.eglGetError()));
      }
      visualID = VisualIDHolder.VID_UNDEFINED;
    }

    EGLGLCapabilities caps = null;
    try {
      if (null == glp) {
        glp = EGLGLCapabilities.getCompatible(device, rType);
      }
      if (!EGLGLCapabilities.isCompatible(glp, rType)) {
        if (DEBUG) {
          System.err.println(
              "config "
                  + toHexString(config)
                  + ": Requested GLProfile "
                  + glp
                  + " with quirks "
                  + defaultQuirks
                  + " not compatible with EGL-RenderableType["
                  + EGLGLCapabilities.renderableTypeToString(null, rType)
                  + "]");
        }
        return null;
      }
      caps = new EGLGLCapabilities(config, cfgID, visualID, glp, rType);
    } catch (GLException gle) {
      if (DEBUG) {
        System.err.println("config " + toHexString(config) + ": " + gle);
      }
      return null;
    }

    if (EGL.EGL_CONFIG_CAVEAT == attributes.get(3)) {
      if (EGL.EGL_SLOW_CONFIG == values.get(3)) {
        caps.setHardwareAccelerated(false);
      }
    } else if (DEBUG) {
      System.err.println(
          dbgCfgFailIntro
              + "EGL_CONFIG_CAVEAT"
              + dbgCfgFailForConfig
              + toHexString(config)
              + dbgCfgFailError
              + toHexString(EGL.eglGetError()));
    }
    // ALPHA shall be set at last - due to it's auto setting by the above (!opaque / samples)
    if (EGL.EGL_RED_SIZE == attributes.get(4)) {
      caps.setRedBits(values.get(4));
    } else if (DEBUG) {
      System.err.println(
          dbgCfgFailIntro
              + "EGL_RED_SIZE"
              + dbgCfgFailForConfig
              + toHexString(config)
              + dbgCfgFailError
              + toHexString(EGL.eglGetError()));
    }
    if (EGL.EGL_GREEN_SIZE == attributes.get(5)) {
      caps.setGreenBits(values.get(5));
    } else if (DEBUG) {
      System.err.println(
          dbgCfgFailIntro
              + "EGL_GREEN_SIZE"
              + dbgCfgFailForConfig
              + toHexString(config)
              + dbgCfgFailError
              + toHexString(EGL.eglGetError()));
    }
    if (EGL.EGL_BLUE_SIZE == attributes.get(6)) {
      caps.setBlueBits(values.get(6));
    } else if (DEBUG) {
      System.err.println(
          dbgCfgFailIntro
              + "EGL_BLUE_SIZE"
              + dbgCfgFailForConfig
              + toHexString(config)
              + dbgCfgFailError
              + toHexString(EGL.eglGetError()));
    }
    if (EGL.EGL_ALPHA_SIZE == attributes.get(7)) {
      caps.setAlphaBits(values.get(7));
    } else if (DEBUG) {
      System.err.println(
          dbgCfgFailIntro
              + "EGL_ALPHA_SIZE"
              + dbgCfgFailForConfig
              + toHexString(config)
              + dbgCfgFailError
              + toHexString(EGL.eglGetError()));
    }
    if (EGL.EGL_STENCIL_SIZE == attributes.get(8)) {
      caps.setStencilBits(values.get(8));
    } else if (DEBUG) {
      System.err.println(
          dbgCfgFailIntro
              + "EGL_STENCIL_SIZE"
              + dbgCfgFailForConfig
              + toHexString(config)
              + dbgCfgFailError
              + toHexString(EGL.eglGetError()));
    }
    if (EGL.EGL_DEPTH_SIZE == attributes.get(9)) {
      caps.setDepthBits(values.get(9));
    } else if (DEBUG) {
      System.err.println(
          dbgCfgFailIntro
              + "EGL_DEPTH_SIZE"
              + dbgCfgFailForConfig
              + toHexString(config)
              + dbgCfgFailError
              + toHexString(EGL.eglGetError()));
    }
    if (forceTransparentFlag) {
      caps.setBackgroundOpaque(false);
    } else if (EGL.EGL_TRANSPARENT_TYPE == attributes.get(10)) {
      caps.setBackgroundOpaque(values.get(10) != EGL.EGL_TRANSPARENT_RGB);
    } else if (DEBUG) {
      System.err.println(
          dbgCfgFailIntro
              + "EGL_TRANSPARENT_TYPE"
              + dbgCfgFailForConfig
              + toHexString(config)
              + dbgCfgFailError
              + toHexString(EGL.eglGetError()));
    }
    if (!caps.isBackgroundOpaque()) {
      if (EGL.EGL_TRANSPARENT_RED_VALUE == attributes.get(11)) {
        final int v = values.get(11);
        caps.setTransparentRedValue(EGL.EGL_DONT_CARE == v ? -1 : v);
      } else if (DEBUG) {
        System.err.println(
            dbgCfgFailIntro
                + "EGL_TRANSPARENT_RED_VALUE"
                + dbgCfgFailForConfig
                + toHexString(config)
                + dbgCfgFailError
                + toHexString(EGL.eglGetError()));
      }
      if (EGL.EGL_TRANSPARENT_GREEN_VALUE == attributes.get(12)) {
        final int v = values.get(12);
        caps.setTransparentGreenValue(EGL.EGL_DONT_CARE == v ? -1 : v);
      } else if (DEBUG) {
        System.err.println(
            dbgCfgFailIntro
                + "EGL_TRANSPARENT_GREEN_VALUE"
                + dbgCfgFailForConfig
                + toHexString(config)
                + dbgCfgFailError
                + toHexString(EGL.eglGetError()));
      }
      if (EGL.EGL_TRANSPARENT_BLUE_VALUE == attributes.get(13)) {
        final int v = values.get(13);
        caps.setTransparentBlueValue(EGL.EGL_DONT_CARE == v ? -1 : v);
      } else if (DEBUG) {
        System.err.println(
            dbgCfgFailIntro
                + "EGL_TRANSPARENT_BLUE_VALUE"
                + dbgCfgFailForConfig
                + toHexString(config)
                + dbgCfgFailError
                + toHexString(EGL.eglGetError()));
      }
      /**
       * Not defined in EGL if( EGL.EGL_TRANSPARENT_ALPHA_VALUE == attributes.get(??) ) { final int
       * v = values.get(??); caps.setTransparentAlphaValue(EGL.EGL_DONT_CARE==v?-1:v); } else
       * if(DEBUG) {
       * System.err.println(dbgStr01+"EGL_TRANSPARENT_ALPHA_VALUE"+dbgStr02+toHexString(config)+dbgEGLCfgFailError+toHexString(EGL.eglGetError()));
       * }
       */
    }
    if (EGL.EGL_SAMPLES == attributes.get(14)) {
      final int numSamples = values.get(14);
      caps.setSampleBuffers(numSamples > 0 ? true : false);
      caps.setNumSamples(numSamples);
    } else if (DEBUG) {
      System.err.println(
          dbgCfgFailIntro
              + "EGL_SAMPLES"
              + dbgCfgFailForConfig
              + toHexString(config)
              + dbgCfgFailError
              + toHexString(EGL.eglGetError()));
    }
    if (!caps.getSampleBuffers()) {
      // try NV_coverage_sample extension
      if (EGLExt.EGL_COVERAGE_BUFFERS_NV == attributes.get(15)) {
        final boolean enabled = values.get(15) > 0;
        if (enabled && EGLExt.EGL_COVERAGE_SAMPLES_NV == attributes.get(16)) {
          caps.setSampleExtension(GLGraphicsConfigurationUtil.NV_coverage_sample);
          caps.setSampleBuffers(true);
          caps.setNumSamples(values.get(16));
        } else if (DEBUG) {
          System.err.println(
              dbgCfgFailIntro
                  + "EGL_COVERAGE_SAMPLES_NV"
                  + dbgCfgFailForConfig
                  + toHexString(config)
                  + dbgCfgFailError
                  + toHexString(EGL.eglGetError()));
        }
      }
      /**
       * else if(DEBUG) { // Not required - vendor extension - don't be verbose!
       * System.err.println(dbgCfgFailIntro+"EGL_COVERAGE_BUFFERS_NV"+dbgCfgFailForConfig+toHexString(config)+dbgCfgFailError+toHexString(EGL.eglGetError()));
       * }
       */
    }

    // Since the passed GLProfile may be null,
    // we use EGL_RENDERABLE_TYPE derived profile as created in the EGLGLCapabilities constructor.
    final int availableTypeBits = EGLConfigDrawableTypeBits(device, config);
    final int drawableTypeBits = winattrmask & availableTypeBits;

    if (0 == drawableTypeBits) {
      return null;
    }

    return (EGLGLCapabilities)
        GLGraphicsConfigurationUtil.fixWinAttribBitsAndHwAccel(device, drawableTypeBits, caps);
  }