private void activate() {
    if (_active == 0) {
      try {
        _oldContext = ContextManager.getCurrentContext();
        _pbuffer.makeCurrent();

        ContextManager.switchContext(_pbuffer);

        ContextManager.getCurrentContext().clearEnforcedStates();
        ContextManager.getCurrentContext().enforceStates(_enforcedStates);

        if (_bgColorDirty) {
          GL11.glClearColor(
              _backgroundColor.getRed(),
              _backgroundColor.getGreen(),
              _backgroundColor.getBlue(),
              _backgroundColor.getAlpha());
          _bgColorDirty = false;
        }
      } catch (final LWJGLException e) {
        logger.logp(Level.SEVERE, this.getClass().toString(), "activate()", "Exception", e);
        throw new Ardor3dException();
      }
    }
    _active++;
  }
 // XXX: Need another look at this to make it generic?
 private void giveBackContext() throws LWJGLException {
   if (Display.isCreated()) {
     Display.makeCurrent();
     ContextManager.switchContext(_oldContext.getContextKey());
   } else if (_oldContext.getContextKey() instanceof AWTGLCanvas) {
     ((AWTGLCanvas) _oldContext.getContextKey()).makeCurrent();
     ContextManager.switchContext(_oldContext.getContextKey());
   }
 }
  private void initPbuffer() {

    try {
      if (_pbuffer != null) {
        giveBackContext();
        ContextManager.removeContext(_pbuffer);
      }
      final PixelFormat format =
          new PixelFormat(
                  _settings.getAlphaBits(), _settings.getDepthBits(), _settings.getStencilBits())
              .withSamples(_settings.getSamples())
              .withBitsPerPixel(_settings.getColorDepth())
              .withStereo(_settings.isStereo());
      _pbuffer = new Pbuffer(_width, _height, format, _texture, null);
      final Object contextKey = _pbuffer;
      try {
        _pbuffer.makeCurrent();
      } catch (final LWJGLException e) {
        throw new RuntimeException(e);
      }

      final LwjglContextCapabilities caps =
          new LwjglContextCapabilities(GLContext.getCapabilities());
      ContextManager.addContext(
          contextKey, new RenderContext(contextKey, caps, ContextManager.getCurrentContext()));

    } catch (final Exception e) {
      logger.logp(Level.SEVERE, this.getClass().toString(), "initPbuffer()", "Exception", e);

      if (_texture != null && _useDirectRender) {
        logger.warning(
            "Your card claims to support Render to Texture but fails to enact it.  Updating your driver might solve this problem.");
        logger.warning("Attempting to fall back to Copy Texture.");
        _texture = null;
        _useDirectRender = false;
        initPbuffer();
        return;
      }

      logger.log(Level.WARNING, "Failed to create Pbuffer.", e);
      return;
    }

    try {
      activate();

      _width = _pbuffer.getWidth();
      _height = _pbuffer.getHeight();

      deactivate();
    } catch (final Exception e) {
      logger.log(Level.WARNING, "Failed to initialize created Pbuffer.", e);
      return;
    }
  }
 public void setMultipleTargets(final boolean force) {
   if (force) {
     logger.fine("Copy Texture Pbuffer used!");
     _useDirectRender = false;
     _texture = null;
     if (_pbuffer != null) {
       try {
         giveBackContext();
       } catch (final LWJGLException ex) {
       }
       ContextManager.removeContext(_pbuffer);
     }
   } else {
     if ((Pbuffer.getCapabilities() & Pbuffer.RENDER_TEXTURE_SUPPORTED) != 0) {
       logger.fine("Render to Texture Pbuffer supported!");
       if (_texture == null) {
         logger.fine("No RenderTexture used in init, falling back to Copy Texture PBuffer.");
         _useDirectRender = false;
       } else {
         _useDirectRender = true;
       }
     } else {
       logger.fine("Copy Texture Pbuffer supported!");
       _texture = null;
     }
   }
 }
  public static void apply(final JoglRenderer renderer, final GLSLShaderObjectsState state) {
    final GL gl = GLU.getCurrentGL();
    final RenderContext context = ContextManager.getCurrentContext();
    final ContextCapabilities caps = context.getCapabilities();

    if (caps.isGLSLSupported()) {
      // Ask for the current state record
      final ShaderObjectsStateRecord record =
          (ShaderObjectsStateRecord) context.getStateRecord(StateType.GLSLShader);
      context.setCurrentState(StateType.GLSLShader, state);

      if (state.isEnabled()) {
        if (state._needSendShader) {
          sendToGL(state);
        }

        if (state._shaderDataLogic != null) {
          state._shaderDataLogic.applyData(state, state._mesh, renderer);
        }
      }

      if (!record.isValid() || record.getReference() != state || state.needsRefresh()) {
        record.setReference(state);
        if (state.isEnabled()) {
          if (state._programID != -1) {
            gl.glUseProgramObjectARB(state._programID);

            final List<ShaderVariable> attribs = state.getShaderAttributes();
            for (int i = attribs.size(); --i >= 0; ) {
              final ShaderVariable shaderVariable = attribs.get(i);
              if (shaderVariable.needsRefresh) {
                JoglShaderUtil.updateAttributeLocation(shaderVariable, state._programID);
                shaderVariable.needsRefresh = false;
              }
              JoglShaderUtil.updateShaderAttribute(shaderVariable);
            }

            final List<ShaderVariable> uniforms = state.getShaderUniforms();
            for (int i = uniforms.size(); --i >= 0; ) {
              final ShaderVariable shaderVariable = uniforms.get(i);
              if (shaderVariable.needsRefresh) {
                JoglShaderUtil.updateUniformLocation(shaderVariable, state._programID);
                JoglShaderUtil.updateShaderUniform(shaderVariable);
                shaderVariable.needsRefresh = false;
              }
            }
          }
        } else {
          gl.glUseProgramObjectARB(0);
        }
      }

      if (!record.isValid()) {
        record.validate();
      }
    }
  }
  private static void checkLinkError(final int programId) {
    final GL gl = GLContext.getCurrentGL();

    final JoglRenderContext context = (JoglRenderContext) ContextManager.getCurrentContext();
    final IntBuffer compiled = context.getDirectNioBuffersSet().getSingleIntBuffer();
    compiled.clear();
    if (gl.isGL2()) {
      gl.getGL2().glGetObjectParameterivARB(programId, GL2ES2.GL_LINK_STATUS, compiled);
    } else {
      if (gl.isGL2ES2()) {
        gl.getGL2ES2().glGetProgramiv(programId, GL2ES2.GL_LINK_STATUS, compiled);
      }
    }
    if (compiled.get(0) == GL.GL_FALSE) {
      if (gl.isGL2()) {
        gl.getGL2().glGetObjectParameterivARB(programId, GL2ES2.GL_INFO_LOG_LENGTH, compiled);
      } else {
        if (gl.isGL2ES2()) {
          gl.getGL2ES2().glGetProgramiv(programId, GL2ES2.GL_INFO_LOG_LENGTH, compiled);
        }
      }
      final int length = compiled.get(0);
      String out = null;
      if (length > 0) {
        final ByteBuffer infoLogBuf = context.getDirectNioBuffersSet().getInfoLogBuffer();
        final ByteBuffer infoLog;
        if (length <= infoLogBuf.capacity()) {
          infoLog = infoLogBuf;
          infoLogBuf.rewind().limit(length);
        } else {
          infoLog = BufferUtils.createByteBuffer(length);
        }
        if (gl.isGL2()) {
          gl.getGL2().glGetInfoLogARB(programId, infoLog.limit(), compiled, infoLog);
        } else {
          if (gl.isGL2ES2()) {
            gl.getGL2ES2().glGetProgramInfoLog(programId, infoLog.limit(), compiled, infoLog);
          }
        }

        final byte[] infoBytes = new byte[length];
        infoLog.get(infoBytes);
        out = new String(infoBytes);
      }

      logger.severe(out);

      // throw new Ardor3dException("Error linking GLSL shader: " + out);
    }
  }
  /**
   * <code>setupTexture</code> initializes a new Texture object for use with TextureRenderer.
   * Generates a valid gl texture id for this texture and inits the data type for the texture.
   */
  public void setupTexture(final Texture tex) {
    if (tex.getType() != Type.TwoDimensional) {
      throw new IllegalArgumentException("Unsupported type: " + tex.getType());
    }
    final RenderContext context = ContextManager.getCurrentContext();
    final TextureStateRecord record =
        (TextureStateRecord) context.getStateRecord(RenderState.StateType.Texture);

    // check if we are already setup... if so, throw error.
    if (tex.getTextureKey() == null) {
      tex.setTextureKey(TextureKey.getRTTKey(tex.getMinificationFilter()));
    } else if (tex.getTextureIdForContext(context.getGlContextRep()) != 0) {
      throw new Ardor3dException("Texture is already setup and has id.");
    }

    // Create the texture
    final IntBuffer ibuf = BufferUtils.createIntBuffer(1);
    GL11.glGenTextures(ibuf);
    final int textureId = ibuf.get(0);
    tex.setTextureIdForContext(context.getGlContextRep(), textureId);

    LwjglTextureStateUtil.doTextureBind(tex, 0, true);

    // Initialize our texture with some default data.
    final int internalFormat = LwjglTextureUtil.getGLInternalFormat(tex.getTextureStoreFormat());
    final int dataFormat =
        LwjglTextureUtil.getGLPixelFormatFromStoreFormat(tex.getTextureStoreFormat());
    final int pixelDataType =
        LwjglTextureUtil.getGLPixelDataType(tex.getRenderedTexturePixelDataType());

    GL11.glTexImage2D(
        GL11.GL_TEXTURE_2D,
        0,
        internalFormat,
        _width,
        _height,
        0,
        dataFormat,
        pixelDataType,
        (ByteBuffer) null);

    // Setup filtering and wrap
    final TextureRecord texRecord = record.getTextureRecord(textureId, tex.getType());
    LwjglTextureStateUtil.applyFilter(tex, texRecord, 0, record, context.getCapabilities());
    LwjglTextureStateUtil.applyWrap(tex, texRecord, 0, record, context.getCapabilities());

    logger.fine("setup pbuffer tex" + textureId + ": " + _width + "," + _height);
  }
  /**
   * Check for program errors. If an error is detected, program exits.
   *
   * @param compilerState the compiler state for a given shader
   * @param id shader's id
   */
  private static void checkProgramError(
      final int compilerState, final int id, final String shaderName) {
    final GL gl = GLContext.getCurrentGL();

    if (compilerState == GL.GL_FALSE) {
      final JoglRenderContext context = (JoglRenderContext) ContextManager.getCurrentContext();
      final IntBuffer iVal = context.getDirectNioBuffersSet().getSingleIntBuffer();
      iVal.clear();
      if (gl.isGL2()) {
        gl.getGL2().glGetObjectParameterivARB(id, GL2.GL_OBJECT_INFO_LOG_LENGTH_ARB, iVal);
      } else {
        if (gl.isGL2ES2()) {
          gl.getGL2ES2().glGetProgramiv(id, GL2ES2.GL_INFO_LOG_LENGTH, iVal);
        }
      }
      final int length = iVal.get(0);
      String out = null;

      if (length > 0) {
        final ByteBuffer infoLogBuf = context.getDirectNioBuffersSet().getInfoLogBuffer();
        final ByteBuffer infoLog;
        if (length <= infoLogBuf.capacity()) {
          infoLog = infoLogBuf;
          infoLogBuf.rewind().limit(length);
        } else {
          infoLog = BufferUtils.createByteBuffer(length);
        }
        if (gl.isGL2()) {
          gl.getGL2().glGetInfoLogARB(id, infoLog.limit(), iVal, infoLog);
        } else {
          if (gl.isGL2ES2()) {
            gl.getGL2ES2().glGetProgramInfoLog(id, infoLog.limit(), iVal, infoLog);
          }
        }

        final byte[] infoBytes = new byte[length];
        infoLog.get(infoBytes);
        out = new String(infoBytes);
      }

      logger.severe(out);

      final String nameString = shaderName.equals("") ? "" : " [ " + shaderName + " ]";
      throw new Ardor3dException("Error compiling GLSL shader " + nameString + ": " + out);
    }
  }
  public static void apply(final LwjglRenderer renderer, final ShadingState state) {
    // ask for the current state record
    final RenderContext context = ContextManager.getCurrentContext();
    final ShadingStateRecord record =
        (ShadingStateRecord) context.getStateRecord(StateType.Shading);
    context.setCurrentState(StateType.Shading, state);

    // If not enabled, we'll use smooth
    final int toApply = state.isEnabled() ? getGLShade(state.getShadingMode()) : GL11.GL_SMOOTH;
    // only apply if we're different. Update record to reflect any changes.
    if (!record.isValid() || toApply != record.lastShade) {
      GL11.glShadeModel(toApply);
      record.lastShade = toApply;
    }

    if (!record.isValid()) {
      record.validate();
    }
  }
Пример #10
0
  public static void apply(final JoglRenderer renderer, final ColorMaskState state) {
    final GL gl = GLU.getCurrentGL();

    // ask for the current state record
    final RenderContext context = ContextManager.getCurrentContext();
    final ColorMaskStateRecord record =
        (ColorMaskStateRecord) context.getStateRecord(StateType.ColorMask);
    context.setCurrentState(StateType.ColorMask, state);

    if (state.isEnabled()) {
      if (!record.isValid()
          || !record.is(state.getRed(), state.getGreen(), state.getBlue(), state.getAlpha())) {
        gl.glColorMask(state.getRed(), state.getGreen(), state.getBlue(), state.getAlpha());
        record.set(state.getRed(), state.getGreen(), state.getBlue(), state.getAlpha());
      }
    } else if (!record.isValid() || !record.is(true, true, true, true)) {
      gl.glColorMask(true, true, true, true);
      record.set(true, true, true, true);
    }

    if (!record.isValid()) {
      record.validate();
    }
  }
  protected static void sendToGL(
      final GLSLShaderObjectsState state, final ContextCapabilities caps) {
    final GL gl = GLContext.getCurrentGL();

    if (state.getVertexShader() == null && state.getFragmentShader() == null) {
      logger.warning("Could not find shader resources!" + "(both inputbuffers are null)");
      state._needSendShader = false;
      return;
    }

    if (state._programID == -1) {
      if (gl.isGL2()) {
        state._programID = gl.getGL2().glCreateProgramObjectARB();
      } else {
        if (gl.isGL2ES2()) {
          state._programID = gl.getGL2ES2().glCreateProgram();
        }
      }
    }

    if (state.getVertexShader() != null) {
      if (state._vertexShaderID != -1) {
        removeVertShader(state);
      }
      if (gl.isGL2()) {
        state._vertexShaderID = gl.getGL2().glCreateShaderObjectARB(GL2ES2.GL_VERTEX_SHADER);
      } else {
        if (gl.isGL2ES2()) {
          state._vertexShaderID = gl.getGL2ES2().glCreateShader(GL2ES2.GL_VERTEX_SHADER);
        }
      }

      // Create the sources
      final byte array[] = new byte[state.getVertexShader().limit()];
      state.getVertexShader().rewind();
      state.getVertexShader().get(array);
      if (gl.isGL2()) {
        gl.getGL2()
            .glShaderSourceARB(
                state._vertexShaderID,
                1,
                new String[] {new String(array)},
                new int[] {array.length},
                0);
      } else {
        if (gl.isGL2ES2()) {
          gl.getGL2ES2()
              .glShaderSource(
                  state._vertexShaderID,
                  1,
                  new String[] {new String(array)},
                  new int[] {array.length},
                  0);
        }
      }

      // Compile the vertex shader
      final JoglRenderContext context = (JoglRenderContext) ContextManager.getCurrentContext();
      final IntBuffer compiled = context.getDirectNioBuffersSet().getSingleIntBuffer();
      compiled.clear();
      if (gl.isGL2()) {
        gl.getGL2().glCompileShaderARB(state._vertexShaderID);
        gl.getGL2()
            .glGetObjectParameterivARB(
                state._vertexShaderID, GL2.GL_OBJECT_COMPILE_STATUS_ARB, compiled);
      } else {
        if (gl.isGL2ES2()) {
          gl.getGL2ES2().glCompileShader(state._vertexShaderID);
          gl.getGL2ES2().glGetShaderiv(state._vertexShaderID, GL2ES2.GL_COMPILE_STATUS, compiled);
        }
      }
      checkProgramError(compiled.get(0), state._vertexShaderID, state._vertexShaderName);

      // Attach the program
      if (gl.isGL2()) {
        gl.getGL2().glAttachObjectARB(state._programID, state._vertexShaderID);
      } else {
        if (gl.isGL2ES2()) {
          gl.getGL2ES2().glAttachShader(state._programID, state._vertexShaderID);
        }
      }
    } else if (state._vertexShaderID != -1) {
      removeVertShader(state);
      state._vertexShaderID = -1;
    }

    if (state.getFragmentShader() != null) {
      if (state._fragmentShaderID != -1) {
        removeFragShader(state);
      }

      if (gl.isGL2()) {
        state._fragmentShaderID = gl.getGL2().glCreateShaderObjectARB(GL2ES2.GL_FRAGMENT_SHADER);
      } else {
        if (gl.isGL2ES2()) {
          state._fragmentShaderID = gl.getGL2ES2().glCreateShader(GL2ES2.GL_FRAGMENT_SHADER);
        }
      }

      // Create the sources
      final byte array[] = new byte[state.getFragmentShader().limit()];
      state.getFragmentShader().rewind();
      state.getFragmentShader().get(array);
      if (gl.isGL2()) {
        gl.getGL2()
            .glShaderSourceARB(
                state._fragmentShaderID,
                1,
                new String[] {new String(array)},
                new int[] {array.length},
                0);
      } else {
        if (gl.isGL2ES2()) {
          gl.getGL2ES2()
              .glShaderSource(
                  state._fragmentShaderID,
                  1,
                  new String[] {new String(array)},
                  new int[] {array.length},
                  0);
        }
      }

      // Compile the fragment shader
      final JoglRenderContext context = (JoglRenderContext) ContextManager.getCurrentContext();
      final IntBuffer compiled = context.getDirectNioBuffersSet().getSingleIntBuffer();
      compiled.clear();
      if (gl.isGL2()) {
        gl.getGL2().glCompileShaderARB(state._fragmentShaderID);
        gl.getGL2()
            .glGetObjectParameterivARB(
                state._fragmentShaderID, GL2.GL_OBJECT_COMPILE_STATUS_ARB, compiled);
      } else {
        if (gl.isGL2ES2()) {
          gl.getGL2ES2().glCompileShader(state._fragmentShaderID);
          gl.getGL2ES2().glGetShaderiv(state._fragmentShaderID, GL2ES2.GL_COMPILE_STATUS, compiled);
        }
      }
      checkProgramError(compiled.get(0), state._fragmentShaderID, state._vertexShaderName);

      // Attach the program
      if (gl.isGL2()) {
        gl.getGL2().glAttachObjectARB(state._programID, state._fragmentShaderID);
      } else {
        if (gl.isGL2ES2()) {
          gl.getGL2ES2().glAttachShader(state._programID, state._fragmentShaderID);
        }
      }
    } else if (state._fragmentShaderID != -1) {
      removeFragShader(state);
      state._fragmentShaderID = -1;
    }

    if (caps.isGeometryShader4Supported()) {
      if (state.getGeometryShader() != null) {
        if (state._geometryShaderID != -1) {
          removeGeomShader(state);
        }

        if (gl.isGL2()) {
          state._geometryShaderID = gl.getGL2().glCreateShaderObjectARB(GL3.GL_GEOMETRY_SHADER);
        } else {
          if (gl.isGL2ES2()) {
            state._geometryShaderID = gl.getGL2ES2().glCreateShader(GL3.GL_GEOMETRY_SHADER);
          }
        }

        // Create the sources
        final byte array[] = new byte[state.getGeometryShader().limit()];
        state.getGeometryShader().rewind();
        state.getGeometryShader().get(array);
        if (gl.isGL2()) {
          gl.getGL2()
              .glShaderSourceARB(
                  state._geometryShaderID,
                  1,
                  new String[] {new String(array)},
                  new int[] {array.length},
                  0);
        } else {
          if (gl.isGL2ES2()) {
            gl.getGL2ES2()
                .glShaderSource(
                    state._geometryShaderID,
                    1,
                    new String[] {new String(array)},
                    new int[] {array.length},
                    0);
          }
        }

        // Compile the geometry shader
        final JoglRenderContext context = (JoglRenderContext) ContextManager.getCurrentContext();
        final IntBuffer compiled = context.getDirectNioBuffersSet().getSingleIntBuffer();
        compiled.clear();
        if (gl.isGL2()) {
          gl.getGL2().glCompileShaderARB(state._geometryShaderID);
          gl.getGL2()
              .glGetObjectParameterivARB(
                  state._geometryShaderID, GL2.GL_OBJECT_COMPILE_STATUS_ARB, compiled);
        } else {
          if (gl.isGL2ES2()) {
            gl.getGL2ES2().glCompileShader(state._geometryShaderID);
            gl.getGL2ES2()
                .glGetShaderiv(state._geometryShaderID, GL2ES2.GL_COMPILE_STATUS, compiled);
          }
        }
        checkProgramError(compiled.get(0), state._geometryShaderID, state._geometryShaderName);

        // Attach the program
        if (gl.isGL2()) {
          gl.getGL2().glAttachObjectARB(state._programID, state._geometryShaderID);
        } else {
          if (gl.isGL2ES2()) {
            gl.getGL2ES2().glAttachShader(state._programID, state._geometryShaderID);
          }
        }
      } else if (state._geometryShaderID != -1) {
        removeGeomShader(state);
        state._geometryShaderID = -1;
      }
    }

    if (caps.isTessellationShadersSupported()) {
      if (state.getTessellationControlShader() != null) {
        if (state._tessellationControlShaderID != -1) {
          removeTessControlShader(state);
        }

        if (gl.isGL2()) {
          state._tessellationControlShaderID =
              gl.getGL2().glCreateShaderObjectARB(GL4.GL_TESS_CONTROL_SHADER);
        } else {
          if (gl.isGL2ES2()) {
            state._tessellationControlShaderID =
                gl.getGL2ES2().glCreateShader(GL4.GL_TESS_CONTROL_SHADER);
          }
        }

        // Create the sources
        final byte array[] = new byte[state.getTessellationControlShader().limit()];
        state.getTessellationControlShader().rewind();
        state.getTessellationControlShader().get(array);
        if (gl.isGL2()) {
          gl.getGL2()
              .glShaderSourceARB(
                  state._tessellationControlShaderID,
                  1,
                  new String[] {new String(array)},
                  new int[] {array.length},
                  0);
        } else {
          if (gl.isGL2ES2()) {
            gl.getGL2ES2()
                .glShaderSource(
                    state._tessellationControlShaderID,
                    1,
                    new String[] {new String(array)},
                    new int[] {array.length},
                    0);
          }
        }

        // Compile the tessellation control shader
        final JoglRenderContext context = (JoglRenderContext) ContextManager.getCurrentContext();
        final IntBuffer compiled = context.getDirectNioBuffersSet().getSingleIntBuffer();
        compiled.clear();
        if (gl.isGL2()) {
          gl.getGL2().glCompileShaderARB(state._tessellationControlShaderID);
          gl.getGL2()
              .glGetObjectParameterivARB(
                  state._tessellationControlShaderID, GL2.GL_OBJECT_COMPILE_STATUS_ARB, compiled);
        } else {
          if (gl.isGL2ES2()) {
            gl.getGL2ES2().glCompileShader(state._tessellationControlShaderID);
            gl.getGL2ES2()
                .glGetShaderiv(
                    state._tessellationControlShaderID, GL2ES2.GL_COMPILE_STATUS, compiled);
          }
        }
        checkProgramError(
            compiled.get(0),
            state._tessellationControlShaderID,
            state._tessellationControlShaderName);

        // Attach the program
        if (gl.isGL2()) {
          gl.getGL2().glAttachObjectARB(state._programID, state._tessellationControlShaderID);
        } else {
          if (gl.isGL2ES2()) {
            gl.getGL2ES2().glAttachShader(state._programID, state._tessellationControlShaderID);
          }
        }
      } else if (state._tessellationControlShaderID != -1) {
        removeTessControlShader(state);
        state._tessellationControlShaderID = -1;
      }
      if (state.getTessellationEvaluationShader() != null) {
        if (state._tessellationEvaluationShaderID != -1) {
          removeTessEvalShader(state);
        }

        if (gl.isGL2()) {
          state._tessellationEvaluationShaderID =
              gl.getGL2().glCreateShaderObjectARB(GL4.GL_TESS_CONTROL_SHADER);
        } else {
          if (gl.isGL2ES2()) {
            state._tessellationEvaluationShaderID =
                gl.getGL2ES2().glCreateShader(GL4.GL_TESS_CONTROL_SHADER);
          }
        }

        // Create the sources
        final byte array[] = new byte[state.getTessellationEvaluationShader().limit()];
        state.getTessellationEvaluationShader().rewind();
        state.getTessellationEvaluationShader().get(array);
        if (gl.isGL2()) {
          gl.getGL2()
              .glShaderSourceARB(
                  state._tessellationEvaluationShaderID,
                  1,
                  new String[] {new String(array)},
                  new int[] {array.length},
                  0);
        } else {
          if (gl.isGL2ES2()) {
            gl.getGL2ES2()
                .glShaderSource(
                    state._tessellationEvaluationShaderID,
                    1,
                    new String[] {new String(array)},
                    new int[] {array.length},
                    0);
          }
        }

        // Compile the tessellation control shader
        final JoglRenderContext context = (JoglRenderContext) ContextManager.getCurrentContext();
        final IntBuffer compiled = context.getDirectNioBuffersSet().getSingleIntBuffer();
        compiled.clear();
        if (gl.isGL2()) {
          gl.getGL2().glCompileShaderARB(state._tessellationEvaluationShaderID);
          gl.getGL2()
              .glGetObjectParameterivARB(
                  state._tessellationEvaluationShaderID,
                  GL2.GL_OBJECT_COMPILE_STATUS_ARB,
                  compiled);
        } else {
          if (gl.isGL2ES2()) {
            gl.getGL2ES2().glCompileShader(state._tessellationEvaluationShaderID);
            gl.getGL2ES2()
                .glGetShaderiv(
                    state._tessellationEvaluationShaderID, GL2ES2.GL_COMPILE_STATUS, compiled);
          }
        }
        checkProgramError(
            compiled.get(0),
            state._tessellationEvaluationShaderID,
            state._tessellationEvaluationShaderName);

        // Attach the program
        if (gl.isGL2()) {
          gl.getGL2().glAttachObjectARB(state._programID, state._tessellationEvaluationShaderID);
        } else {
          if (gl.isGL2ES2()) {
            gl.getGL2ES2().glAttachShader(state._programID, state._tessellationEvaluationShaderID);
          }
        }
      } else if (state._tessellationEvaluationShaderID != -1) {
        removeTessEvalShader(state);
        state._tessellationEvaluationShaderID = -1;
      }
    }

    if (gl.isGL2()) {
      gl.getGL2().glLinkProgramARB(state._programID);
    } else {
      if (gl.isGL2ES2()) {
        gl.getGL2ES2().glLinkProgram(state._programID);
      }
    }
    checkLinkError(state._programID);
    state.setNeedsRefresh(true);
    state._needSendShader = false;
  }
  public static void apply(final JoglRenderer renderer, final VertexProgramState state) {
    final GL gl = GLU.getCurrentGL();
    final RenderContext context = ContextManager.getCurrentContext();
    final ContextCapabilities caps = context.getCapabilities();

    if (caps.isVertexProgramSupported()) {
      // ask for the current state record
      final VertexProgramStateRecord record =
          (VertexProgramStateRecord) context.getStateRecord(StateType.VertexProgram);
      context.setCurrentState(StateType.VertexProgram, state);

      if (!record.isValid() || record.getReference() != state) {
        record.setReference(state);
        if (state.isEnabled()) {
          // Vertex program not yet loaded
          if (state._getProgramID() == -1) {
            if (state.getProgramAsBuffer() != null) {
              final int id = create(state.getProgramAsBuffer());
              state._setProgramID(id);
            } else {
              return;
            }
          }

          gl.glEnable(GL.GL_VERTEX_PROGRAM_ARB);
          gl.glBindProgramARB(GL.GL_VERTEX_PROGRAM_ARB, state._getProgramID());

          // load environmental parameters...
          for (int i = 0; i < VertexProgramState._getEnvParameters().length; i++) {
            if (VertexProgramState._getEnvParameters()[i] != null) {
              gl.glProgramEnvParameter4fARB(
                  GL.GL_VERTEX_PROGRAM_ARB,
                  i,
                  VertexProgramState._getEnvParameters()[i][0],
                  VertexProgramState._getEnvParameters()[i][1],
                  VertexProgramState._getEnvParameters()[i][2],
                  VertexProgramState._getEnvParameters()[i][3]);
            }
          }

          // load local parameters...
          if (state.isUsingParameters()) {
            // no parameters are used
            for (int i = 0; i < state._getParameters().length; i++) {
              if (state._getParameters()[i] != null) {
                gl.glProgramLocalParameter4fARB(
                    GL.GL_VERTEX_PROGRAM_ARB,
                    i,
                    state._getParameters()[i][0],
                    state._getParameters()[i][1],
                    state._getParameters()[i][2],
                    state._getParameters()[i][3]);
              }
            }
          }

        } else {
          gl.glDisable(GL.GL_VERTEX_PROGRAM_ARB);
        }
      }

      if (!record.isValid()) {
        record.validate();
      }
    }
  }
Пример #13
0
  /**
   * Initialize texture renderers. Load water textures. Create shaders.
   *
   * @param r
   */
  private void initialize(final Renderer r) {
    if (cam == null || initialized) {
      return;
    }
    initialized = true;

    final ContextCapabilities caps = ContextManager.getCurrentContext().getCapabilities();

    if (useRefraction && useProjectedShader && caps.getNumberOfFragmentTextureUnits() < 6
        || useRefraction && caps.getNumberOfFragmentTextureUnits() < 5) {
      useRefraction = false;
      logger.info("Not enough textureunits, falling back to non refraction water");
    }

    if (!caps.isGLSLSupported()) {
      supported = false;
    }
    if (!(caps.isPbufferSupported() || caps.isFBOSupported())) {
      supported = false;
    }

    if (isSupported()) {
      tRenderer =
          TextureRendererFactory.INSTANCE.createTextureRenderer( //
              cam.getWidth() / renderScale, // width
              cam.getHeight() / renderScale, // height
              8, // Depth bits... TODO: Make configurable?
              0, // Samples... TODO: Make configurable?
              r,
              caps);

      // blurSampleDistance = 1f / ((float) cam.getHeight() / renderScale);

      tRenderer.setMultipleTargets(true);
      tRenderer.setBackgroundColor(new ColorRGBA(0.0f, 0.0f, 0.0f, 1.0f));
      tRenderer
          .getCamera()
          .setFrustum(
              cam.getFrustumNear(),
              cam.getFrustumFar(),
              cam.getFrustumLeft(),
              cam.getFrustumRight(),
              cam.getFrustumTop(),
              cam.getFrustumBottom());

      textureState = new TextureState();
      textureState.setEnabled(true);

      setupTextures();

      fullScreenQuad = new Quad("FullScreenQuad", cam.getWidth() / 4, cam.getHeight() / 4);
      fullScreenQuad.setTranslation(cam.getWidth() / 2, cam.getHeight() / 2, 0);
      fullScreenQuad.getSceneHints().setRenderBucketType(RenderBucketType.Ortho);
      fullScreenQuad.getSceneHints().setCullHint(CullHint.Never);
      fullScreenQuad.getSceneHints().setTextureCombineMode(TextureCombineMode.Replace);
      fullScreenQuad.getSceneHints().setLightCombineMode(LightCombineMode.Off);
      final TextureState ts = new TextureState();
      ts.setTexture(textureReflect);
      fullScreenQuad.setRenderState(ts);
      fullScreenQuad.setRenderState(blurShaderVertical);
      fullScreenQuad.updateWorldRenderStates(false);
    }

    if (!isSupported()) {
      createFallbackData();
    } else {
      noFog = new FogState();
      noFog.setEnabled(false);
    }

    getSceneHints().setCullHint(CullHint.Never);

    setWaterEffectOnSpatial(this);
  }
 public void cleanup() {
   ContextManager.removeContext(_pbuffer);
   _pbuffer.destroy();
 }
Пример #15
0
  @Override
  public void render(final Renderer renderer) {
    // Grab our render context - used to enforce renderstates
    final RenderContext context = ContextManager.getCurrentContext();

    // go through our bucket contents
    Spatial spatial;
    for (int i = 0; i < _currentListSize; i++) {
      spatial = _currentList[i];

      // make sure we have a real spatial
      if (spatial == null) {
        continue;
      }

      // we only care about altering the Mesh... perhaps could be altered later to some interface
      // shared by Mesh
      // and other leaf nodes.
      if (spatial instanceof Mesh) {

        // get our transparency rendering type.
        final TransparencyType renderType = spatial.getSceneHints().getTransparencyType();

        // check for one of the two pass types...
        if (renderType != TransparencyType.OnePass) {

          // get handle to Mesh
          final Mesh mesh = (Mesh) spatial;

          // check if we have a Cull state set or enforced. If one is explicitly set and is not
          // Face.None,
          // we'll not do two-pass transparency.
          RenderState setState =
              context.hasEnforcedStates() ? context.getEnforcedState(StateType.Cull) : null;
          if (setState == null) {
            setState = mesh.getWorldRenderState(RenderState.StateType.Cull);
          }

          // Do the described check.
          if (setState == null || ((CullState) setState).getCullFace() == Face.None) {

            // pull any currently enforced cull or zstate. We'll put them back afterwards
            final RenderState oldCullState = context.getEnforcedState(StateType.Cull);
            final RenderState oldZState = context.getEnforcedState(StateType.ZBuffer);

            // enforce our cull and zstate. The zstate is setup to respect depth, but not write to
            // it.
            context.enforceState(_tranparentCull);
            context.enforceState(_transparentZBuff);

            // first render back-facing tris only
            _tranparentCull.setCullFace(CullState.Face.Front);
            mesh.draw(renderer);

            // revert z state
            context.clearEnforcedState(StateType.ZBuffer);
            if (oldZState != null) {
              context.enforceState(oldZState);
            }

            // render front-facing tris
            _tranparentCull.setCullFace(CullState.Face.Back);
            mesh.draw(renderer);

            // revert cull state
            if (oldCullState != null) {
              context.enforceState(oldCullState);
            } else {
              context.clearEnforcedState(StateType.Cull);
            }
            continue;
          }
        }
      }

      // go ahead and draw as usual
      spatial.draw(renderer);
    }
  }