#include "pch.h"

#include "TextShader.h"

#include "../ShaderProgram.h" 

static const std::string TEXT_VERTEX_SHADER_CODE = R"""(
#version 330 core
layout(location = 0) in vec2 aPosition;
layout(location = 1) in vec2 aTexCoord;

uniform mat3 uProjectionMatrix;

out vec2 vTexCoord;

void main() {
    vec3 p = uProjectionMatrix * vec3(aPosition, 1.0);
    gl_Position = vec4(p.xy, 0.0, 1.0);
    vTexCoord = aTexCoord;
}
)""";

static const std::string TEXT_FRAGMENT_SHADER_CODE = R"""(
#version 330 core
in vec2 vTexCoord;
out vec4 FragColor;

uniform sampler2D uTexture;
uniform vec4 uColor;

void main() {
    // 使用 .r 通道读取单通道纹理 (用于字体位图)
    float alpha = texture(uTexture, vTexCoord).r;
    FragColor = vec4(uColor.rgb, uColor.a * alpha);
}
)""";

class TextShader::TextVertexShader : public Shader {
public:
    virtual ~TextVertexShader() = default;
    std::string getShaderCode() const override { return TEXT_VERTEX_SHADER_CODE; }
    std::string getShaderName() const override { return "TextVertexShader"; }
};
class TextShader::TextFragmentShader : public Shader {
public:
    virtual ~TextFragmentShader() = default;
    std::string getShaderCode() const override { return TEXT_FRAGMENT_SHADER_CODE; }
    std::string getShaderName() const override { return "TextFragmentShader"; }
};
const TextShader::TextVertexShader TextShader::s_vertexShader;
const TextShader::TextFragmentShader TextShader::s_fragmentShader;
TextShader::TextShader()
    : m_color(1.0f, 1.0f, 1.0f, 1.0f)
{}

const Shader& TextShader::getVertexShader() const
{
    return s_vertexShader;
}

const Shader& TextShader::getFragmentShader() const
{
    return s_fragmentShader;
}

void TextShader::setColor(const glm::vec4& color)
{
    this->m_color = color;
}

void TextShader::setDefaultUniforms(ShaderProgram* program)
{
    if (!program) return;
    program->use();
    program->setUniform4f("uColor", m_color.r, m_color.g, m_color.b, m_color.a);
    program->setUniform1i("uTexture", 0);
    program->stop();
}