#include "Surface3D.h"

Surface3D::Surface3D(float tailleX, float tailleY, std::string const vertexShader, std::string const fragmentShader,
                     std::string const fichierImage, float multi)
:m_shader(vertexShader, fragmentShader)
{
    // Vertices
    tailleX /= 2;
    tailleY /= 2;
    float vertices[] = {-tailleX, 0.0, -tailleY,   tailleX, 0.0, -tailleY,   tailleX, 0.0, tailleY,   // Triangle 1
                        -tailleX, 0.0, -tailleY,   -tailleX, 0.0, tailleY,   tailleX, 0.0, tailleY};  // Triangle 2
    for (int i(0); i<18; i++)
        m_vertices[i] = vertices[i];

    // Coordonnées de texture
    if (multi == 0.0f)
        multi = 1.0;
    float multiX, multiY;
    multiX = multiY = multi;
    if (tailleX < tailleY)
        multiX *= tailleX/tailleY;
    else if (tailleY < tailleX)
        multiY *= tailleY/tailleX;
    float coordTexture[] = {0, 0,   multiX, 0,   multiX, multiY,     // Triangle 1
                            0, 0,   0, multiY,   multiX, multiY};    // Triangle 2
    for (int i(0); i<12; i++)
        m_coordTexture[i] = coordTexture[i];

    // Texture
    m_texture.charger(fichierImage);

    // Shader
    if (!m_shader.charger())
        std::cout << "Echec du chargement des shaders de texture." << std::endl;
}

Surface3D::~Surface3D()
{

}


void Surface3D::afficher(glm::mat4 &projection, glm::mat4 &modelview)
{
    // Activation du shader
    glUseProgram(m_shader.getProgramID());
        // Envoi des vertices
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, m_vertices);
        glEnableVertexAttribArray(0);
        // Envoi des coordonnées de texture
        glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, m_coordTexture);
        glEnableVertexAttribArray(2);
        // Envoi des matrices
        glUniformMatrix4fv(glGetUniformLocation(m_shader.getProgramID(), "projection"), 1, GL_FALSE, glm::value_ptr(projection));
        glUniformMatrix4fv(glGetUniformLocation(m_shader.getProgramID(), "modelview"), 1, GL_FALSE, glm::value_ptr(modelview));
        // Verrouillage de la texture
        glBindTexture(GL_TEXTURE_2D, m_texture.getID());
        // Rendu
        glDrawArrays(GL_TRIANGLES, 0, 6);
        // Déverrouillage de la texture
        glBindTexture(GL_TEXTURE_2D, 0);
        // Désactivation des tableaux
        glDisableVertexAttribArray(2);
        glDisableVertexAttribArray(0);
    // Désactivation du shader
    glUseProgram(0);
}

