import {getDisconnectedVertices} from "../geometry/Figure.js";

/**
 * Programa de sombreado Alpha Mapping.
 * @author Melissa Méndez Servín.
 */
export default class AlphaMapping {

    constructor(gl, WebGL, figure, srcTexture, draw_callback, mipmap=true, filters={}){
        var vsh = `#version 300 es
            uniform mat4 u_PVM_matrix;

            in vec4 a_position;
            in vec2 a_texcoord;

            out vec2 v_texcoord;

            void main(){
                
                gl_Position =  u_PVM_matrix * a_position;
                v_texcoord = a_texcoord;
            }
            `;
        var fsh = `#version 300 es
            precision highp float;
            
            uniform sampler2D u_texture;
            uniform int u_active;
            in vec2 v_texcoord;

            out vec4 glColor;
            
            void main(){
                vec4 color = texture(u_texture, v_texcoord);
                if(color.a < 0.5 && u_active == 1)
                    discard;
                glColor = color;
            }
            `; 
        if (WebGL.programs["AM"])
            this.program = WebGL.programs["AM"];
        else
            this.program = WebGL.createProgram(gl, vsh, fsh, "AM");
            
        let vertices = (figure.byIndices) ?  figure.getVertices() : getDisconnectedVertices(figure.getVertices(), figure.getFaces());
        
        let attributes = {  position: { numComponents: 3, 
                                                    data: vertices},
                            texcoord: { numComponents: 2, 
                                                data: figure.getTexCoordinates(),
                                            normalize: true}
                            };
        if(figure.byIndices){
            let vaoAndIndices = WebGL.setVAOAndAttributes(gl, this.program, attributes, figure.getFaces());
            this.vao = vaoAndIndices.vao;
            this.indexBuffer = vaoAndIndices.indexBuffer;
            this.numIndices = figure.numIndices;
        }else{
            this.vao = WebGL.setVAOAndAttributes(gl, this.program, attributes);  
            this.numElements = attributes.position.data.length/3;
        }
        this.setUniforms = WebGL.setUniforms(gl, this.program);
        /*
        if(mipmap)
            this.texture = WebGL.loadImageTexture(gl, srcTexture, draw_callback, filters);
        else 
            this.texture = WebGL.loadImageTextureNoMipmap(gl, srcTexture, draw_callback);
*/
        this.uniforms = { u_active: 1};
    }
}