uk.co.ifs_studios.engine.shader.ShaderProgram.java Source code

Java tutorial

Introduction

Here is the source code for uk.co.ifs_studios.engine.shader.ShaderProgram.java

Source

/*
Copyright (C) 2013 IFS Studios
    
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
    
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
    
You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package uk.co.ifs_studios.engine.shader;

import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL20;

import uk.co.ifs_studios.engine.exceptions.ShaderException;
import uk.co.ifs_studios.engine.loggers.EngineLogger;

/**
 * A shader program that you can add VertexShaders and FragmentShaders to and
 * use.
 * 
 * @author BleedObsidian (Jesse Prescott)
 */
public class ShaderProgram {
    private final int id;

    /**
     * Create new ShaderProgram.
     */
    public ShaderProgram() {
        this.id = GL20.glCreateProgram();
    }

    /**
     * Add VertexShader to program.
     * 
     * @param shader
     *            - Loaded VertexShader.
     */
    public void addVertexShader(VertexShader shader) {
        GL20.glAttachShader(this.id, shader.getID());
    }

    /**
     * Add FragmentShader to program.
     * 
     * @param shader
     *            - Loaded FragmentShader.
     */
    public void addFragmentShader(FragmentShader shader) {
        GL20.glAttachShader(this.id, shader.getID());
    }

    /**
     * Create attribute.
     * 
     * @param id
     *            - Unique ID for attribute.
     * @param value
     *            - Variable name for attribute.
     */
    public void addAttribute(int id, String value) {
        GL20.glBindAttribLocation(this.id, id, value);
    }

    /**
     * Create uniform.
     * 
     * @param name
     *            - Name of variable uniform.
     * @return - Uniform ID.
     */
    public int addUniform(String name) {
        return GL20.glGetUniformLocation(this.id, name);
    }

    /**
     * Link and validate shader program.
     */
    public void link() {
        GL20.glLinkProgram(this.id);
        GL20.glValidateProgram(this.id);

        int error = GL11.glGetError();
        if (error != GL11.GL_NO_ERROR) {
            EngineLogger.error(new ShaderException("Couldn't link and validate shader program.", null));
        }
    }

    /**
     * Use program.
     */
    public void use() {
        GL20.glUseProgram(this.id);
    }

    /**
     * Set used program to null.
     */
    public void unuse() {
        GL20.glUseProgram(0);
    }
}