Skip to content

06. 중간점검 - 클래스 완성


목차

  • 열거형 선언하기

  • VAO

  • Buffer (BufferData)

  • ShaderProgram

  • 텍스쳐 그리는 코드 리팩토링하기

열거형 선언하기

잠깐 쉬어가는 느낌으로,

미처 다 못 만든 클래스와 열거형들을 완성하고 갑시다.

열거형을 다음과 같이 선언해 주세요.

enum class BufferAccessType : GLenum {
    ReadOnly = GL_READ_ONLY,
    WriteOnly = GL_WRITE_ONLY,
    ReadAndWrite = GL_READ_WRITE,
};


enum class TransformFeedbackCaptureMode : GLenum {
    InterleavedAttribs = GL_INTERLEAVED_ATTRIBS,
    SeparateAttribs = GL_SEPARATE_ATTRIBS
};

enum class UniformType : GLenum {
    Sampler2D = GL_SAMPLER_2D,
    Sampler2DArray = GL_SAMPLER_2D_ARRAY,
    Sampler2DRect = GL_SAMPLER_2D_RECT,
    Sampler3D = GL_SAMPLER_3D,
    SamplerCube = GL_SAMPLER_CUBE,

    Int = GL_INT,
    Float = GL_FLOAT,
    Vec2f = GL_FLOAT_VEC2,
    Vec3f = GL_FLOAT_VEC3,
    Vec4f = GL_FLOAT_VEC4,

    Mat2f = GL_FLOAT_MAT2,
    Mat3f = GL_FLOAT_MAT3,
    Mat4f = GL_FLOAT_MAT4,

    Double = GL_DOUBLE,
    Vec2d = GL_DOUBLE_VEC2,
    Vec3d = GL_DOUBLE_VEC3,
    Vec4d = GL_DOUBLE_VEC4,

    Uint = GL_UNSIGNED_INT,
    Vec2u = GL_UNSIGNED_INT_VEC2,
    Vec3u = GL_UNSIGNED_INT_VEC3,
    Vec4u = GL_UNSIGNED_INT_VEC4,

    Bool = GL_BOOL,
    Vec2b = GL_BOOL_VEC2,
    Vec3b = GL_BOOL_VEC3,
    Vec4b = GL_BOOL_VEC4,

    Mat2x3f = GL_FLOAT_MAT2x3,
    Mat2x4f = GL_FLOAT_MAT2x4,
    Mat3x2f = GL_FLOAT_MAT3x2,
    Mat3x4f = GL_FLOAT_MAT3x4,
    Mat4x2f = GL_FLOAT_MAT4x2,
    Mat4x3f = GL_FLOAT_MAT4x3,

    Mat2d = GL_DOUBLE_MAT2,
    Mat3d = GL_DOUBLE_MAT3,
    Mat4d = GL_DOUBLE_MAT4,

    Mat2x3d = GL_DOUBLE_MAT2x3,
    Mat2x4d = GL_DOUBLE_MAT2x4,
    Mat3x2d = GL_DOUBLE_MAT3x2,
    Mat3x4d = GL_DOUBLE_MAT3x4,
    Mat4x2d = GL_DOUBLE_MAT4x2,
    Mat4x3d = GL_DOUBLE_MAT4x3,

};

enum class BufferUsage : GLenum {
    StreamDraw = GL_STREAM_DRAW, // 주기적으로 업로드
    StreamRead = GL_STREAM_READ,
    StreamCopy = GL_STREAM_COPY,

    StaticDraw = GL_STATIC_DRAW, // 초기에 한번만 업로드
    StaticRead = GL_STATIC_READ,
    StaticCopy = GL_STATIC_COPY,

    DynamicDraw = GL_DYNAMIC_DRAW, // 렌더링할때마다 버퍼 내용물을 재업로드
    DynamicRead = GL_DYNAMIC_READ,
    DynamicCopy = GL_DYNAMIC_COPY
};

enum class BufferStorageFlag : GLenum {
    MapRead = GL_MAP_READ_BIT,
    MapWrite = GL_MAP_WRITE_BIT,
    MapPersistent = GL_MAP_PERSISTENT_BIT,
    MapCoherent = GL_MAP_COHERENT_BIT,
    DynamicStorage = GL_DYNAMIC_STORAGE_BIT,
    ClientStorage = GL_CLIENT_STORAGE_BIT,
};


enum class BufferMappingFlag : GLenum {
    // 이 넷중에 하나는 필수
    Read = GL_MAP_READ_BIT, // 읽기전용
    Write = GL_MAP_WRITE_BIT, // 쓰기전용
    Persistent = GL_MAP_PERSISTENT_BIT, // 
    Coherent = GL_MAP_COHERENT_BIT,

    // 이 네개는 옵션
    //      이 세개중에 하나라도 켜지면 Read는 불가
    InvalidateRange = GL_MAP_INVALIDATE_RANGE_BIT, // 기존 버퍼의 범위(glMapRange) 를 무효화
    InvalidateBuffer = GL_MAP_INVALIDATE_BUFFER_BIT, // 기존 버퍼 전체를 무효화

    // 동기화 X, 성능 우선
    /*
    *   이거 쓰고 동기화하려면,
        glFinish() -> glUnmapBuffer() 순으로 불러야함
            (또는 glMemoryBarrier(),
             또는 glClientWaitSync 이후에 unmap)
    */
    Unsynchronized = GL_MAP_UNSYNCHRONIZED_BIT,

    FlushExplicit = GL_MAP_FLUSH_EXPLICIT_BIT, // 이게 켜지면 Write는 필수
};

WrappingType, FilterType, InternalFormat, PixelFormat, DataType

5. 텍스쳐 사용하기 글에서 사용한 걸 그대로 쓰면 됩니다.

아직은 저 열거형들을 전부 알 필요가 없습니다.

우선 자주 사용되는 기능에 대한 것부터 알아가는 게 중요합니다.

VAO

VAO 래핑을 시작합시다.

저번 삼각형 그리기 코드에서,

VAO를 셋업할 때 가장 불편하고

읽기가 어려운 부분이

'정점의 속성' 을 정의하고 - 크기를 또 계산해서 - 몇 번째 바인딩 슬롯에 ...

이 부분입니다.

이를 간략화하기 위해서,

다음과 같은 구조체를 만들어 주세요.

class VertexLayout {
private:
    std::vector<std::pair<DataType, uint32_t>> m_attribs{ };
public:
    VertexLayout() = default;
    ~VertexLayout() = default;
public:
    void push_attrib(const DataType& type, const uint32_t& count) {
        m_attribs.emplace_back(type, count);
    }
public:
    const auto& get_attribs() const { return m_attribs; }
public:
    uint32_t get_vertex_size() const {
        uint32_t result = 0;
        for (const auto& attrib : m_attribs) {
            result += static_cast<uint32_t>(VertexLayout::get_data_size(attrib.first) * attrib.second);
        }
        return result;
    }
public:
    static size_t get_data_size(const DataType& type) {
        size_t result = 0;

        switch (type) {
        case (DataType::Byte): { result = sizeof(char); break; }
        case (DataType::UnsignedByte332): [[fallthrough]];
        case (DataType::UnsignedByte233Rev): [[fallthrough]];
        case (DataType::UnsignedByte): { result = sizeof(unsigned char); break; }
        case (DataType::Short): { result = sizeof(short); break; }
        case (DataType::UnsignedShort565): [[fallthrough]];
        case (DataType::UnsignedShort565Rev): [[fallthrough]];
        case (DataType::UnsignedShort4444): [[fallthrough]];
        case (DataType::UnsignedShort4444Rev): [[fallthrough]];
        case (DataType::UnsignedShort5551): [[fallthrough]];
        case (DataType::UnsignedShort1555Rev): [[fallthrough]];
        case (DataType::UnsignedShort): { result = sizeof(unsigned short); break; }
        case (DataType::Int): { result = sizeof(int); break; }
        case (DataType::UnsignedInt8888): [[fallthrough]];
        case (DataType::UnsignedInt8888Rev): [[fallthrough]];
        case (DataType::UnsignedInt101010102): [[fallthrough]];
        case (DataType::UnsignedInt): { result = sizeof(unsigned int); break; }
        case (DataType::Float): { result = sizeof(float); break; }
        case (DataType::Double): { result = sizeof(double); break; }
        default: { assert(false); break; }
        };
        return result;
    }
};

VertexLayout 구조체는 말 그대로

이 VAO에 바인딩 될 정점 버퍼가 어떻게 생겼는지를

간략하게 설명하기 위함입니다.

VertexLayout::push_attrib 메서드를 호출해서

어떤 타입의, 몇 개의 데이터가 든 속성을 쉽게 추가할 수 있습니다.

다음은 VertexArray 클래스를 구현합시다.

class VertexArray final {
private:
    GLuint m_ID = 0;
public:
    VertexArray() {
        glCreateVertexArrays(1, &m_ID);

    }
    ~VertexArray() {
        glDeleteBuffers(1, &m_ID);

    }
public:
    void bind() const {
        glBindVertexArray(m_ID);
    }

생성 / 삭제 / 바인딩을 기본적으로 만들어주시고,

정점 버퍼와 인덱스 버퍼를 바인딩할 수 있도록

bind_vertex_bufferbind_element_buffer 를 각각 만들어주세요.

public:
    void bind_vertex_buffer(const uint32_t& binding_idx, const Buffer* buffer, const uint32_t& offset, const VertexLayout& layout) const {
        auto vbo_id = buffer->get_opengl_id();
        glVertexArrayVertexBuffer(
            m_ID, binding_idx, vbo_id,
            offset, layout.get_vertex_size()
        );

        const auto& vertex_size = layout.get_vertex_size();
        const auto& attribs = layout.get_attribs();

        int attrib_index = 0;
        uint32_t offset_ptr = 0;

        for (const auto& attrib : attribs) {
            glEnableVertexArrayAttrib(m_ID, attrib_index);

            glVertexArrayAttribFormat(
                m_ID, attrib_index, attrib.second, (GLenum)(attrib.first), GL_FALSE, offset_ptr
            );

            glVertexArrayAttribBinding(
                m_ID,
                attrib_index,
                binding_idx
            );

            offset_ptr += static_cast<uint32_t>(VertexLayout::get_data_size(attrib.first)) * attrib.second;
            attrib_index++;
        }
    }
    void bind_element_buffer(const Buffer* buffer) const {
        glVertexArrayElementBuffer(m_ID, buffer->get_opengl_id());
    }

또한 divisor와 ID의 getter를 만들어주면 완성입니다.

(VAO의 divisor 개념은 인스턴싱 부분에서 다룹니다)

public:
    void set_divisor(const uint32_t& binding_idx, const uint32_t& divisor) const {
        glVertexArrayBindingDivisor(
            m_ID,
            binding_idx, divisor
        );
    }
public:
    const GLuint& get_opengl_id() const { return m_ID; }
};

Buffer

이제 버퍼를 만들 차례입니다.

저희가 정점 버퍼 / 인덱스 버퍼라고 구분을 하긴 하지만,

둘 다 똑같은 버퍼, 즉 GPU 메모리 덩어리입니다.

저희는 CPU 측의 데이터를 GPU로 보내기 위해서

BufferData라는 CPU 데이터 저장공간을 하나 만들 겁니다.

이는 일련의 데이터가 몇 바이트인지 추적하기 위함이죠.

다음과 같이 클래스를 만들어주세요.

사실 그냥 uint8_t형을 담는 std::vector를 한번 감싼 것과 같습니다.

class BufferData final {
private:
    std::vector<unsigned char> m_data{};
public:
    BufferData() = default;
    ~BufferData() = default;
    BufferData(const BufferData& other) = default;
    BufferData& operator=(const BufferData& other) = default;
public:
    BufferData(const void* data, const size_t& len) {
        assert(data != nullptr && len > 0);

        const auto* bytes = static_cast<const unsigned char*>(data);
        m_data.assign(bytes, bytes + len);
    }
public:
    void swap(std::vector<unsigned char>&& data) {
        m_data = std::move(data);
    }
private:
    void _add(const unsigned char* value, size_t count) {
        size_t old_size = m_data.size();
        m_data.resize(old_size + count);
        std::memcpy(m_data.data() + old_size, value, count);
    }
public:
    template <typename T, typename std::enable_if_t<std::is_trivially_copyable_v<T>, int> = 0>
    void add_pod(const T& value) {
        _add(reinterpret_cast<const unsigned char*>(&value), sizeof(T));
    }
    template <typename T, typename std::enable_if_t<std::is_trivially_copyable_v<T>, int> = 0>
    void add_vec(const T& v) {
        _add(reinterpret_cast<const unsigned char*>(&v), sizeof(T));
    }
public:
    void add_int32(int32_t v) { add_pod(v); }
    void add_uint32(uint32_t v) { add_pod(v); }
    void add_float(float v) { add_pod(v); }
public:
    void add_vec2i(const glm::ivec2& v) { add_vec(v); }
    void add_vec3i(const glm::ivec3& v) { add_vec(v); }
    void add_vec4i(const glm::ivec4& v) { add_vec(v); }
    void add_vec2u(const glm::uvec2& v) { add_vec(v); }
    void add_vec3u(const glm::uvec3& v) { add_vec(v); }
    void add_vec4u(const glm::uvec4& v) { add_vec(v); }
    void add_vec2(const glm::vec2& v) { add_vec(v); }
    void add_vec3(const glm::vec3& v) { add_vec(v); }
    void add_vec4(const glm::vec4& v) { add_vec(v); }
public:
    void reserve(const size_t& size) { m_data.reserve(size); }
public:
    const void* get_pointer() const { return m_data.data(); }
    size_t get_length() const { return m_data.size(); }
};

이제 저희는 BufferData 에다가 add_vec* 같은 메서드로 3차원 점을 추가해 갈 수 있는 겁니다.

그럼 Buffer를 만들어 봅시다.

생성자와 소멸자를 정의해주세요.

class Buffer final {
private:
    GLuint m_ID = 0;
public:
    Buffer() {
        glCreateBuffers(1, &m_ID);
    }
    ~Buffer() {
        glDeleteBuffers(1, &m_ID);
    }

다음은 버퍼에 데이터를 업로드 / 다운로드하는 메서드입니다.

public:
    void upload_data(const BufferData& data, const BufferUsage& usage) const {
        glNamedBufferData(m_ID,
            data.get_length(),
            data.get_pointer(),
            (GLenum)(usage)
        );
    }
    void upload_empty_data(const size_t& size, const BufferUsage& usage) const {
        glNamedBufferData(m_ID,
            size,
            nullptr,
            (GLenum)(usage)
        );
    }
    void upload_sub_data(const uint32_t& offset, const BufferData& data) const {
        glNamedBufferSubData(
            m_ID,
            offset,
            data.get_length(), data.get_pointer()
        );
    }
    void download_sub_data(const uint32_t& offset, void* dst, const size_t& size) const {
        glGetNamedBufferSubData(
            m_ID,
            offset,
            size, dst
        );
    }

upload_data 는 말 그대로 버퍼에 데이터를 업로드하고,

upload_empty_data 는 크기만 받아서 해당 바이트 크기만큼 공간을 할당만 합니다.

upload_sub_data 는 특정 오프셋을 받아서 그 오프셋부터 데이터를 씁니다.

download_sub_data로는 특정 오프셋으로부터 특정 크기까지의 데이터를 CPU로 받을 수 있습니다.

다음은 매핑 관련 메서드입니다.

OpenGL 버퍼에서의 매핑(mapping)이란, GPU에 업로드 된 데이터의 포인터를

CPU 내 메모리의 포인터로써 받아와서(=매핑 시켜서), CPU 측에서 GPU 내의 데이터를 수정할 수 있게 하는 기능입니다.

대충 map -> 버퍼의 데이터 읽기 / 수정 -> unmap 순서로 이루어집니다.

public:
    void* map(const BufferAccessType& type) const {
        return glMapNamedBuffer(m_ID,
            (GLenum)(type)
        );
    }
    void* map_range(const uint32_t& offset, const size_t& size, const BufferMappingFlag& flag) const {
        return glMapNamedBufferRange(
            m_ID, offset, size, (GLenum)(flag));
    }
    void flush_mapped_range(const uint32_t& offset, const size_t& size) const {
        glFlushMappedNamedBufferRange(
            m_ID,
            offset,
            size
        );
    }
    void unmap() const {
        glUnmapNamedBuffer(m_ID);
    }

mapmap_range 의 차이점은

전자는 버퍼의 전체에 대한 매핑을,

후자는 버퍼의 지정된 범위(오프셋, 크기)에 대한 매핑을 한다는 데 있습니다.

flush_mapped_range

map_range 로 CPU 측에서 버퍼를 매핑했을때,

BufferMappingFlag::FlushExplicit 을 플래그에 포함시켰다면

CPU로 쓰기를 수행한 후에,

수동으로 '방금 CPU쓰기가 끝났으니, GPU 버퍼의 이 영역을 갱신해주세요' 라고 요청할 때 쓰입니다.

다음은 버퍼끼리 내용물을 복사하는 메서드입니다.

public:
    void copy_from(const Buffer& src, const uint32_t& read_offset, const uint32_t& write_offset, const size_t& size) const {
        glCopyNamedBufferSubData(
            src.get_opengl_id(), m_ID,
            read_offset, write_offset, size
        );
    }
    void copy_to(const Buffer& dst, const uint32_t& read_offset, const uint32_t& write_offset, const size_t& size) const {
        glCopyNamedBufferSubData(
            m_ID, dst.get_opengl_id(),
            read_offset, write_offset, size
        );
    }

두 메서드는 그냥 src와 dst가 반전된 버전이며,

read_offsetwrite_offset 은 각각 src와 dst의 어디에서 / 어디를 읽고 쓸지 지정하는 오프셋입니다.

다음은 버퍼를 초기화하는 메서드입니다.

public:
    void clear_data(const InternalFormat& iformat, const PixelFormat& format, const DataType& data_type, const void* data /* 배열 아님. 보통 0임 */) const {
        glClearNamedBufferData(
            m_ID,
            (GLenum)(iformat),
            (GLenum)(format),
            (GLenum)(data_type), data
        );
    }
    void clear_sub_data(const InternalFormat& iformat, const uint32_t& offset, const size_t& size, const PixelFormat& format, const DataType& data_type, const void* data /* 배열 아님, 보통0 */) const {
        glClearNamedBufferSubData(
            m_ID,
            (GLenum)(iformat),
            offset, size,
            (GLenum)(format),
            (GLenum)(data_type),
            data
        );
    }

clear_data 또는 clear_sub_data 를 써서

버퍼 내의 모든 요소를 특정 값으로 초기화할 수 있습니다.

여기서 data 인자에 nullptr를 넣으면 초깃값(0) 으로 초기화되며,

포멧에 맞는 데이터를 보내면 그 값으로 초기화됩니다.

예를 들어서

  • iformat = GL_RGBA8
  • format = GL_RGBA
  • data_type = GL_UNSIGNED_BYTE

이라면, 초깃값은 다음과 같이 만들 수 있습니다.

uint8_t clear_value[4] = { 0, 0, 0, 1 };
void* ptr = (void*)(&clear_value[0]);

data_type / iformat의 바이트 수를 고려해 배열의 타입을,

iformat / format의 채널 수를 고려해 배열의 길이를 만드는 것에 주의하세요.

마지막으로 upload_storage 입니다.

public:
    void upload_storage(const BufferData& data, const BufferStorageFlag& flag) const {
        glNamedBufferStorage(
            m_ID,
            data.get_length(), data.get_pointer(),
            (GLenum)(flag)
        );
    }
    void upload_storage(const size_t& size, const BufferStorageFlag& flag) const {
        glNamedBufferStorage(
            m_ID,
            size, nullptr,
            (GLenum)(flag)
        );
    }
public:
    const GLuint& get_opengl_id() const { return m_ID; }
};

upload_storage 메서드의 경우, upload_data 와는 다르게

한번 부른 이후에는 절대 그 버퍼의 크기가 변하지 않습니다.

예를 들어 처음에 upload_storage 메서드로 버퍼의 크기를 정해 버렸다면,

그 이후에 불리는 upload_storage / upload_data 로는 버퍼의 재할당이 불가능해진다는 뜻입니다.

(upload_data 의 경우 재할당이 가능합니다.)

이는 반복적인 재할당에 의한 오버헤드를 막기 위함이며,

일단 storage로 적절히 할당해 두고

데이터를 수정할 때는 upload_data 로 재업로드 하는 것이 아닌,

map / unmap 을 사용하게 하는 디자인입니다.

이걸로 Buffer는 구현이 완료되었습니다.

ShaderProgram

원래 삼각형 그리기 코드에서

먼저 GLuint vertex_shader, fragment_shader 형태로

셰이더를 생성한 후에

GLuint program 이라는 객체에 해당 셰이더를 첨부했었죠?

ShaderProgram은 그 두 객체를 간결하게 합친 클래스입니다.

우선 멤버 함수와 생성자 / 소멸자, 또 use 메서드를 정의해줍시다.

class ShaderProgram final {
private:
    std::unordered_map<std::string, UniformType>
        m_uniform_type_map{ };
private:
    GLuint m_ID = 0;
private:
    std::unordered_map<ShaderType, GLuint, ShaderTypeHash> m_shader_map{ };
    std::unordered_map<std::string, int> m_uniform_location_map{ };
private:
private:
    // 서브루틴 기능은 OpenGL에만 있다.
    struct SubroutineInfo {
        // 타겟 uniform 서브루틴 이름 -->  해당 셰이더에서의 인덱스
        std::unordered_map<std::string, GLuint> location_map{ };
        // 특정 서브루틴 이름         -->  해당 서브루틴의 인덱스
        std::unordered_map<std::string, GLuint> index_map{ };
        // 이걸 전부 glUniformSubroutinesuiv에 전달.
        std::vector<GLuint> storage{};
    };
    mutable std::unordered_map<ShaderType, SubroutineInfo, ShaderTypeHash> m_subroutine_info_map{ };
public:
    ShaderProgram() {
        m_ID = glCreateProgram();
    }
    ~ShaderProgram() {
        for (const auto& [type, id] : m_shader_map) {
            glDetachShader(m_ID, id);
            glDeleteShader(id);
        }
        glDeleteProgram(m_ID);
    }
public:
    void use() const {
        glUseProgram(m_ID);
    }

저희가 저번에 살펴보았던

'셰이더 내에 유니폼이 어디에 있는지'

또 '이 유니폼은 무슨 타입인지' 등을 저장하는 맵들과

기본적인 프로그램 생성 / 소멸, 사용 메서드가 있습니다.

(서브루틴 기능은 제대로 아실 필요가 없습니다, 무시해주세요)

다음은 셰이더 첨부 / 프로그램 링킹 메서드입니다.

public:
    void attach_shader(const ShaderType& type, const std::string_view& src) {
        assert(m_shader_map.find(type) == m_shader_map.end());
        uint32_t id = glCreateShader((GLenum)(type));
        const auto* ptr = src.data();
        glShaderSource(id, 1, &ptr, NULL);
        glCompileShader(id);
        int success = 0;
        glGetShaderiv(id, GL_COMPILE_STATUS, &success);
        if (!success) {
            char buffer[1024] = { 0, };
            glGetShaderInfoLog(id, 1024, NULL, buffer);
            std::cout << "failed to compile shader : " << buffer << "\n";
            assert(false);
        }
        m_shader_map[type] = id;
        glAttachShader(m_ID, id);
    }
    void link() const {
        glLinkProgram(m_ID);
        int success = 0;
        glGetProgramiv(m_ID, GL_LINK_STATUS, &success);
        if (!success) {
            char buffer[1024] = { 0, };
            glGetProgramInfoLog(m_ID, 1024, NULL, &buffer[0]);
            std::cout << "failed to link program : " << buffer << "\n";
            assert(false);
        }
    }

프로그램 생성 -> 여러 셰이더 첨부 ->

프로그램 링킹 -> 프로그램 사용 / 유니폼 업로드 -> 프로그램 삭제

이런 과정을 떠올리시면 이해하기 편합니다.

다음은 트랜스폼 피드백 관련 메서드입니다.

public:
    void set_transform_feedback_varyings(const std::vector<std::string_view>& varyings, const TransformFeedbackCaptureMode& capture_mode) const {
        std::vector<const char*> strs{};
        strs.reserve(varyings.size());
        for (const auto& s : varyings) { strs.emplace_back(s.data()); }
        glTransformFeedbackVaryings(
            m_ID, static_cast<GLsizei>(strs.size()), strs.data(),
            (GLenum)(capture_mode)
        );
    }
    void get_varying(const uint32_t& index, std::string& out_name, uint32_t& out_size /* 배열이면 out_size > 1 */, UniformType& out_type) const {
     char name[64] = { 0, };
     GLsizei length = 0, size = 0;
     GLenum type = 0;

     glGetTransformFeedbackVarying(
         m_ID,
         index,
         64,
         &length,
         &size,
         &type,
         name
     );

     out_name = name;
     out_size = size;
     out_type = (UniformType)(type);
 }

트랜스폼 피드백 기능은 추후에 설명합니다.

다음은 유니폼 업로드 메서드들입니다.

public:
    void upload_uniform_bool(const std::string& name, const bool& value) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::Bool);
        glProgramUniform1i(m_ID, m_uniform_location_map.at(name), value);
    }
    void upload_uniform_int(const std::string& name, const int& value) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::Int);
        glProgramUniform1i(m_ID, m_uniform_location_map.at(name), value);
    }
    void upload_uniform_float(const std::string& name, const float& value) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::Float);
        glProgramUniform1f(m_ID, m_uniform_location_map.at(name), value);
    }
    void upload_uniform_vec2f(const std::string& name, const glm::vec2& value) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::Vec2f);
        glProgramUniform2f(m_ID, m_uniform_location_map.at(name), value.x, value.y);
    }
    void upload_uniform_vec3f(const std::string& name, const glm::vec3& value) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::Vec3f);
        glProgramUniform3f(m_ID, m_uniform_location_map.at(name), value.x, value.y, value.z);
    }
    void upload_uniform_vec4f(const std::string& name, const glm::vec4& value) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::Vec4f);
        glProgramUniform4f(m_ID, m_uniform_location_map.at(name), value.x, value.y, value.z, value.w);
    }
    void upload_uniform_mat4f(const std::string& name, const glm::mat4& value) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::Mat4f);
        glProgramUniformMatrix4fv(m_ID, m_uniform_location_map.at(name), 1, GL_FALSE, &value[0][0]);
    }
    void upload_uniform_sampler2d(const std::string& name, const int& slot) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::Sampler2D);
        glProgramUniform1i(m_ID, m_uniform_location_map.at(name), slot);
    }
    void upload_uniform_sampler2d_array(const std::string& name, const int& slot) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::Sampler2DArray);
        glProgramUniform1i(m_ID, m_uniform_location_map.at(name), slot);
    }
    void upload_uniform_sampler_cube(const std::string& name, const int& slot) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::SamplerCube);
        glProgramUniform1i(m_ID, m_uniform_location_map.at(name), slot);
    }
public:
    void upload_uniform_subroutine(const ShaderType& type, const std::string& target_name, const std::string& subroutine_fn_name) const {
        auto& info = m_subroutine_info_map.at(type);
        GLuint loc = info.location_map.at(target_name);
        GLuint index = info.index_map.at(subroutine_fn_name);
        // 기록 하고 다시 갱신해주는거임.
        info.storage.at(loc) = index;
        glUniformSubroutinesuiv(
            (GLenum)(type),
            info.storage.size(),
            info.storage.data()
        );
    }

모든 upload_uniform_* 메서드들은

현재 해당 유니폼이 이전에 등록했던 타입 정보와 일치한다고 가정합니다.

다음은 유니폼 정보를 사전에 등록하는 메서드입니다.

public:
    void register_uniform(const std::string& name, const UniformType& type) {

        assert(m_uniform_type_map.find(name) == m_uniform_type_map.end());
        m_uniform_type_map[name] = type;

        auto loc = glGetUniformLocation(m_ID, name.c_str());

        // GLSL컴파일러가 너무 똑똑해서 안쓰는건 다 없애버리기에 
        // 이걸 해놓으면 (디버깅이) 귀찮아짐
        //assert(loc != -1);
        m_uniform_location_map[name] = loc;

        if (loc == -1) { return; }

        {
            const GLchar* str = name.c_str();
            const GLchar* const arr[] = { str };

            // 주의 : 컴파일단에서 안쓰이는거 없어진 경우
            //      여기서 INVALID_INDEX뜸..
            GLuint gl_index{};
            glGetUniformIndices(m_ID, 1, arr, &gl_index);

            assert(gl_index != GL_INVALID_INDEX);

            GLint gl_type{};
            glGetActiveUniformsiv(m_ID, 1, &gl_index, GL_UNIFORM_TYPE, &gl_type);

            assert((GLenum)type == (gl_type));
        }
    }
public:
    void set_uniform_block_binding(const uint32_t& block_index, const uint32_t& binding) const {
        glUniformBlockBinding(m_ID, block_index, binding);
    }
    uint32_t get_uniform_block_index(const std::string& name) const {
        return glGetUniformBlockIndex(m_ID, name.c_str());
    }

set_uniform_block_bindingget_uniform_block_index 는 추후에

유니폼 버퍼셰이더 스토리지 버퍼 를 다룰 때 설명하겠습니다.

마지막으로 서브루틴 기능의 구현입니다.

이해하지 않고 넘어가셔도 무방합니다.

public:
    const uint32_t& get_opengl_id() const { return m_ID; }
private:
    void _register_subroutines() {

        GLenum interfaces[] = {
            GL_VERTEX_SUBROUTINE,
            GL_GEOMETRY_SUBROUTINE,
            GL_TESS_CONTROL_SUBROUTINE,
            GL_TESS_EVALUATION_SUBROUTINE,
            GL_FRAGMENT_SUBROUTINE,
            GL_COMPUTE_SUBROUTINE
        };
        ShaderType shader_stages[] = {
            ShaderType::Vertex,
            ShaderType::Geometry,
            ShaderType::TessellationControl,
            ShaderType::TessellationEvaluation,
            ShaderType::Fragment,
            ShaderType::Compute
        };

        GLint interfaces_count = std::size(interfaces);

        for (GLint i = 0; i < interfaces_count; ++i) {
            /* Get all active subroutines */
            GLenum program_interface = interfaces[i];

            // 해당 셰이더에 정의된 subroutine의 개수
            GLint num_subroutines = 0;
            glGetProgramInterfaceiv(m_ID, program_interface, GL_ACTIVE_RESOURCES, &num_subroutines);

            const GLenum properties[] = { GL_NAME_LENGTH };
            const GLint properties_size = sizeof(properties) / sizeof(properties[0]);

            // 해당 셰이더에 얼만큼 크기의 서브루틴배열을 넘겨야 하는가??
            GLint count_subroutine_locations = 0;
            glGetProgramStageiv(m_ID, (GLenum)(shader_stages[i]), GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS, &count_subroutine_locations);
            m_subroutine_info_map[shader_stages[i]]
                .storage.resize(count_subroutine_locations);

            // location_map 채우기
            std::vector<std::string> uniform_names{};
            GLint count = 0;
            glGetProgramInterfaceiv(m_ID, program_interface, GL_ACTIVE_RESOURCES, &count);
            for (GLint i = 0; i < count; ++i) {
                char name[256];
                GLsizei length = 0;
                glGetProgramResourceName(
                    m_ID,
                    program_interface,
                    i,
                    sizeof(name),
                    &length,
                    name
                );
                uniform_names.push_back(std::string(name));
            }
            for (const auto& name : uniform_names) {
                GLuint location = glGetSubroutineUniformLocation(
                    m_ID,
                    (GLenum)(shader_stages[i]),
                    name.c_str()
                );

                m_subroutine_info_map[shader_stages[i]]
                    .location_map.at(name) = location;
            }

            // index_map 채우기
            for (GLint j = 0; j < num_subroutines; ++j) {
                GLint values[properties_size];
                GLint length = 0;
                glGetProgramResourceiv(m_ID, program_interface, j, properties_size, properties, properties_size, &length, values);

                std::vector<char> name_data(values[0]);
                glGetProgramResourceName(m_ID, program_interface, j, name_data.size(), nullptr, &name_data[0]);
                std::string subroutine_name(name_data.begin(), name_data.end() - 1);

                GLuint subroutine_index = glGetSubroutineIndex(m_ID, (GLenum)(shader_stages[i]), subroutine_name.c_str());

                m_subroutine_info_map[shader_stages[i]]
                    .index_map[subroutine_name] = subroutine_index;
            }
        }
    }
};

이걸로 셰이더 프로그램이 구현되었습니다.

텍스쳐 그리는 코드 리팩토링하기

저희가 5번째 게시물에서 구현했던 텍스쳐 렌더링 코드를

위에서 구현한 클래스들로 더 간결히 바꿔 봅시다.

우선 정점 데이터와 인덱스 데이터를 준비하는 부분입니다.

BufferData 클래스를 통해 데이터를 만들어 놓습니다.

    ...
    glfwMakeContextCurrent(window);
    assert(gladLoadGL() != 0);


    // 정점 데이터를 준비합니다.
    BufferData vertices_data{}; {
        vertices_data.add_vec4({-0.5f, 0.5f, 0.0f, 1.0f});// 첫 번째 정점 (사각형의 topleft)
        vertices_data.add_vec4({0.5f, 0.5f, 1.0f, 1.0f});// 두 번째 정점 (사각형의 topright)
        vertices_data.add_vec4({0.5f, -0.5f, 1.0f, 0.0f});// 세 번째 정점 (사각형의 bottomright)
        vertices_data.add_vec4({-0.5f, -0.5f, 0.0f, 0.0f});// 네 번째 정점 (사각형의 bottomleft)
    }

    // 인덱스 데이터를 준비합니다.
    BufferData indices_data{}; {
        // 반시계방향으로!!
        indices_data.add_uint32(0);
        indices_data.add_uint32(3);
        indices_data.add_uint32(1);
        indices_data.add_uint32(1);
        indices_data.add_uint32(3);
        indices_data.add_uint32(2);
    }

다음은 VAO / VBO / EBO 의 셋업입니다.

이전과 개념은 동일하지만 더욱 간결해진 것에 주목하세요.

    ...

    VertexArray va{};
    Buffer vb{}, eb{};

    vb.upload_data(vertices_data, BufferUsage::StaticDraw);
    eb.upload_data(indices_data, BufferUsage::StaticDraw);

    VertexLayout va_layout{}; {
        va_layout.push_attrib(DataType::Float, 2);
        va_layout.push_attrib(DataType::Float, 2);
    }

    va.bind_vertex_buffer(0, &vb, 0, va_layout);
    va.bind_element_buffer(&eb);

    ShaderProgram program{};
    program.attach_shader(ShaderType::Vertex, s_vertex_shader_src);
    program.attach_shader(ShaderType::Fragment, s_fragment_shader_src);
    program.link();
    program.register_uniform("uSize", UniformType::Vec2f);
    program.register_uniform("uProj", UniformType::Mat4f);
    program.register_uniform("uView", UniformType::Mat4f);
    program.register_uniform("uWorld", UniformType::Mat4f);
    program.register_uniform("uTexture", UniformType::Sampler2D);

    ...

그리고 마지막으로 렌더링 부분을 다음과 같이 수정해주세요.

            // 화면 초기화 색상을 초록색으로 정하고, 컬러 버퍼와 깊이 버퍼를 초기화합니다.
            glClearColor(0.2f, 0.3f, 0.1f, 1.0f);
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

            // 정점 배열과 프로그램을 지정합니다.
            //     glDraw* 함수를 부르려면 이 두 코드가 꼭 필요합니다.
            va.bind();
            program.use();

            program.upload_uniform_vec2f("uSize", { 100, 100 });
            program.upload_uniform_mat4f("uProj", proj_mat.get_matrix());
            program.upload_uniform_mat4f("uView", view_mat.get_matrix());
            program.upload_uniform_mat4f("uWorld", world_mat.get_matrix());
            tex.bind_unit(0);
            program.upload_uniform_sampler2d("uTexture", 0);

            // glDrawElements 는 인덱스 버퍼를 사용한다는 가정 하에 쓰이는 렌더 콜입니다.
            // 첫번째 인자 : 프리미티브를 지정합니다. 이 경우에서는 GL_TRIANGLES, 즉 삼각형을 그립니다.
            // 두번째 인자 : 인덱스의 개수를 지정합니다. 아까 인덱스 데이터의 개수는 3개였습니다.
            // 세번째 인자 : 인덱스 데이터의 형태를 지정합니다. 아까 인덱스 데이터의 형은 uint32_t 형이었습니다.
            // 네번째 인자 : 인덱스 데이터의 오프셋을 지정합니다. 보통은 0으로 둡니다.
            glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

전보다 훨씬 깔끔해지지 않았나요?

전체 코드는 하단에 있습니다.

다음 게시글에서는 7. 3D로의 확장 을 주제로써,

Transform2D / ViewMatrix2D / ProjectionMatrix2D 를 3차원으로 확장시키고,

3차원에서의 카메라와 큐브 렌더링을 구현해보도록 하겠습니다.

전체 코드 보기

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <cassert>

#define GLM_ENABLE_EXPERIMENTAL
#include <glm/glm.hpp>
#include <glm/ext.hpp>

#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>

#include <iostream>
#include <vector>
#include <optional>
#include <array>
#include <unordered_map>

const char* s_vertex_shader_src =
R"""(// 모든 GLSL 코드는 #version [버전] [core(선택)] 이라는 전처리기로 시작합니다.
#version 460 core

// 아까 만들었던 정점 데이터가 하나하나씩 여기로 들어옵니다.
//     2차원 정점으로 만들었으니 vec2로 받아야 합니다.
layout (location = 0) in vec2 aPos; 
layout (location = 1) in vec2 aTexCoord; 

layout (location = 0) uniform vec2 uSize = vec2(64, 64);

layout (location = 1) uniform mat4 uProj;
layout (location = 2) uniform mat4 uView;
layout (location = 3) uniform mat4 uWorld;

layout (location = 0) out vec2 TexCoord;

// GLSL도 셰이더 1개당 진입점을 하나씩 가집니다.
// C++ 처럼 에러 코드를 반환하지는 않지만, 
//      버텍스 셰이더에서는 'gl_Position 이라는 내부 변수에 값을 쓰는 것' 이 핵심입니다.
//          gl_Position 은 버텍스 셰이더 내에서 읽고 쓰기가 가능한 vec4 타입의 변수이며,
//          이름 그대로 GPU에 넘겨질 정점을 뜻합니다. 왜 vec4이고 마지막에 1을 넣는지는 다다음 장을 참고해주세요.
void main() {
    // 저희는 2차원 정점, 즉 (X, Y) 데이터만 입력했기에 남은 Z축 데이터는 0으로 통일합니다.

    vec2 pos = (aPos * uSize);

    gl_Position = uProj * uView * uWorld * vec4(pos, 0, 1);
    TexCoord = aTexCoord;
}
)""";

const char* s_fragment_shader_src =
R"""(#version 460 core

// 위의 코드에서 정점을 in 으로 받은 것과 다르게, 
// 이번에는 프래그먼트 셰이더가 'RGBA 색상을 출력' 한다는 것을 표현하기 위해 
// out 을 사용합니다.
// FragColor 라는 변수에 값을 쓴다는 것은, 최종적으로 화면에 그려질 픽셀의 색상을 결정하는 것과 같습니다.
layout (location = 0) out vec4 FragColor;

layout (location = 0) in vec2 TexCoord;

layout (location = 4) uniform sampler2D uTexture;

void main() {
    FragColor = texture(uTexture, TexCoord);
}
)""";


class Transform2D final {
private:
    glm::vec2 m_position{ 0.0f, 0.0f };
    float     m_rotation{ 0.0f };
    glm::vec2 m_scale{ 1.0f, 1.0f };
private:
    glm::mat4 m_matrix{ 1.0f };
public:
    Transform2D() {
        this->_update_matrix();
    }
    Transform2D(const glm::vec2& pos, const float& rot, const glm::vec2& scl)
        : m_position(pos), m_rotation(rot), m_scale(scl) {
        this->_update_matrix();
    }
    ~Transform2D() = default;
public:
    const glm::mat4& get_matrix() const { return m_matrix; }
public:
    void set_position(const glm::vec2& value) { m_position = value; this->_update_matrix(); }
    void set_rotation(const float& value) { m_rotation = value; this->_update_matrix(); }
    void set_scale(const glm::vec2& value) { m_scale = value; this->_update_matrix(); }
public:
    const glm::vec2& get_position() const { return m_position; }
    const float& get_rotation() const { return m_rotation; }
    const glm::vec2& get_scale() const { return m_scale; }
private:
    void _update_matrix() {
        m_matrix = glm::mat4{ 1.0f };
        m_matrix = glm::translate(m_matrix, { m_position.x, -m_position.y, 0.0f });
        m_matrix = glm::rotate(m_matrix, m_rotation, { 0.0f, 0.0f, 1.0f });
        m_matrix = glm::scale(m_matrix, { m_scale.x, m_scale.y, 1.0f });
    }
};

class ViewMatrix2D final {
private:
    glm::vec2 m_position{ 0.0f, 0.0f };
    float     m_rotation{ 0.0f };
    glm::vec2 m_zoom{ 1.0f, 1.0f };
private:
    glm::mat4 m_matrix{ 1.0f };
public:
    ViewMatrix2D() { this->_update_matrix(); }
    ViewMatrix2D(const glm::vec2& pos, const float& rot, const glm::vec2& zoom)
        : m_position(pos), m_rotation(rot), m_zoom(zoom) {
        this->_update_matrix();
    }
    ~ViewMatrix2D() = default;
public:
    void set_position(const glm::vec2& value) { m_position = value; this->_update_matrix(); }
    void set_rotation(const float& value) { m_rotation = value; this->_update_matrix(); }
    void set_zoom(const glm::vec2& value) { m_zoom = value; this->_update_matrix(); }
public:
    const glm::vec2& get_position() const { return m_position; }
    const float& get_rotation() const { return m_rotation; }
    const glm::vec2& get_zoom() const { return m_zoom; }
    const glm::mat4& get_matrix() const { return m_matrix; }
private:
    void _update_matrix() {
        m_matrix = glm::mat4{ 1.0f };

        m_matrix = glm::scale(m_matrix, { m_zoom.x, m_zoom.y, 1.0f });
        m_matrix = glm::rotate(m_matrix, -m_rotation, { 0.0f, 0.0f, 1.0f });
        m_matrix = glm::translate(m_matrix, { -m_position.x, m_position.y, 0.0f });
    }
};

class ProjectionMatrix2D final {
private:
    glm::uvec2 m_frustrum_size{ 1280, 720 };
    float m_near = -1.0f;
    float m_far = 1.0f;
private:
    glm::mat4 m_matrix{ 1.0f };
public:
    ProjectionMatrix2D() {
        this->_update_matrix();
    }
    ProjectionMatrix2D(const glm::uvec2& frustrum_size, const float& proj_near, const float& proj_far)
        : m_frustrum_size(frustrum_size), m_near(proj_near), m_far(proj_far)
    {
        this->_update_matrix();
    }
    ~ProjectionMatrix2D() = default;
public:
    void set_frustrum_size(const glm::uvec2& value) { m_frustrum_size = value; this->_update_matrix(); }
    void set_near(const float& value) { m_near = value; this->_update_matrix(); }
    void set_far(const float& value) { m_far = value; this->_update_matrix(); }
public:
    const glm::uvec2& get_frustrum_size() const { return m_frustrum_size; }
    const float& get_near() const { return m_near; }
    const float& get_far() const { return m_far; }
public:
    const glm::mat4& get_matrix() const { return m_matrix; }
private:
    void _update_matrix() {
        const float fwidth = static_cast<float>(m_frustrum_size.x);
        const float fheight = static_cast<float>(m_frustrum_size.y);

        //m_matrix = {
        //    2.0f / fwidth, 0.0f,           0.0f,                      0.0f,
        //    0.0f,          2.0f / fheight, 0.0f,                      0.0f,
        //    0.0f,          0.0f,           -2.0f / (m_far - m_near),  0.0f,
        //    0.0f,          0.0f,           -(m_far + m_near) / (m_far - m_near), 1.0f
        //};


        //m_matrix = {
        //    2.0f / fwidth,  0.0f,           0.0f,                     0.0f, //  -(right+left)/(right-left)
        //    0.0f,           2.0f / fheight, 0.0f,                     0.0f, //  -(top+bottom)/(top-bottom)
        //    0.0f,           0.0f,           -2.0f / (m_far - m_near), -(m_far + m_near) / (m_far - m_near),
        //    0.0f,           0.0f,           0.0f,                     1.0f
        //};

        //m_matrix = glm::ortho(-640.0f, 640.0f, -360.0f, 360.0f, -1.0f, 1.0f);
        float width_half = (fwidth / 2.0f);
        float height_half = (fheight / 2.0f);
        m_matrix = glm::ortho(-width_half, width_half, -height_half, height_half, m_near, m_far);
    }
};


class BufferData final {
private:
    std::vector<unsigned char> m_data{};
public:
    BufferData() = default;
    ~BufferData() = default;
    BufferData(const BufferData& other) = default;
    BufferData& operator=(const BufferData& other) = default;
public:
    BufferData(const void* data, const size_t& len) {
        assert(data != nullptr && len > 0);

        const auto* bytes = static_cast<const unsigned char*>(data);
        m_data.assign(bytes, bytes + len);
    }
public:
    void swap(std::vector<unsigned char>&& data) {
        m_data = std::move(data);
    }
private:
    void _add(const unsigned char* value, size_t count) {
        size_t old_size = m_data.size();
        m_data.resize(old_size + count);
        std::memcpy(m_data.data() + old_size, value, count);
    }
public:
    template <typename T, typename std::enable_if_t<std::is_trivially_copyable_v<T>, int> = 0>
    void add_pod(const T& value) {
        _add(reinterpret_cast<const unsigned char*>(&value), sizeof(T));
    }
    template <typename T, typename std::enable_if_t<std::is_trivially_copyable_v<T>, int> = 0>
    void add_vec(const T& v) {
        _add(reinterpret_cast<const unsigned char*>(&v), sizeof(T));
    }
public:
    void add_int32(int32_t v) { add_pod(v); }
    void add_uint32(uint32_t v) { add_pod(v); }
    void add_float(float v) { add_pod(v); }
public:
    void add_vec2i(const glm::ivec2& v) { add_vec(v); }
    void add_vec3i(const glm::ivec3& v) { add_vec(v); }
    void add_vec4i(const glm::ivec4& v) { add_vec(v); }
    void add_vec2u(const glm::uvec2& v) { add_vec(v); }
    void add_vec3u(const glm::uvec3& v) { add_vec(v); }
    void add_vec4u(const glm::uvec4& v) { add_vec(v); }
    void add_vec2(const glm::vec2& v) { add_vec(v); }
    void add_vec3(const glm::vec3& v) { add_vec(v); }
    void add_vec4(const glm::vec4& v) { add_vec(v); }
public:
    void reserve(const size_t& size) { m_data.reserve(size); }
public:
    const void* get_pointer() const { return m_data.data(); }
    size_t get_length() const { return m_data.size(); }
};

enum class BufferAccessType : GLenum {
    ReadOnly = GL_READ_ONLY,
    WriteOnly = GL_WRITE_ONLY,
    ReadAndWrite = GL_READ_WRITE,
};


enum class TransformFeedbackCaptureMode : GLenum {
    InterleavedAttribs = GL_INTERLEAVED_ATTRIBS,
    SeparateAttribs = GL_SEPARATE_ATTRIBS
};

enum class UniformType : GLenum {
    Sampler2D = GL_SAMPLER_2D,
    Sampler2DArray = GL_SAMPLER_2D_ARRAY,
    Sampler2DRect = GL_SAMPLER_2D_RECT,
    Sampler3D = GL_SAMPLER_3D,
    SamplerCube = GL_SAMPLER_CUBE,

    Int = GL_INT,
    Float = GL_FLOAT,
    Vec2f = GL_FLOAT_VEC2,
    Vec3f = GL_FLOAT_VEC3,
    Vec4f = GL_FLOAT_VEC4,

    Mat2f = GL_FLOAT_MAT2,
    Mat3f = GL_FLOAT_MAT3,
    Mat4f = GL_FLOAT_MAT4,

    Double = GL_DOUBLE,
    Vec2d = GL_DOUBLE_VEC2,
    Vec3d = GL_DOUBLE_VEC3,
    Vec4d = GL_DOUBLE_VEC4,

    Uint = GL_UNSIGNED_INT,
    Vec2u = GL_UNSIGNED_INT_VEC2,
    Vec3u = GL_UNSIGNED_INT_VEC3,
    Vec4u = GL_UNSIGNED_INT_VEC4,

    Bool = GL_BOOL,
    Vec2b = GL_BOOL_VEC2,
    Vec3b = GL_BOOL_VEC3,
    Vec4b = GL_BOOL_VEC4,

    Mat2x3f = GL_FLOAT_MAT2x3,
    Mat2x4f = GL_FLOAT_MAT2x4,
    Mat3x2f = GL_FLOAT_MAT3x2,
    Mat3x4f = GL_FLOAT_MAT3x4,
    Mat4x2f = GL_FLOAT_MAT4x2,
    Mat4x3f = GL_FLOAT_MAT4x3,

    Mat2d = GL_DOUBLE_MAT2,
    Mat3d = GL_DOUBLE_MAT3,
    Mat4d = GL_DOUBLE_MAT4,

    Mat2x3d = GL_DOUBLE_MAT2x3,
    Mat2x4d = GL_DOUBLE_MAT2x4,
    Mat3x2d = GL_DOUBLE_MAT3x2,
    Mat3x4d = GL_DOUBLE_MAT3x4,
    Mat4x2d = GL_DOUBLE_MAT4x2,
    Mat4x3d = GL_DOUBLE_MAT4x3,

};

enum class BufferUsage : GLenum {
    StreamDraw = GL_STREAM_DRAW, // 주기적으로 업로드
    StreamRead = GL_STREAM_READ,
    StreamCopy = GL_STREAM_COPY,

    StaticDraw = GL_STATIC_DRAW, // 초기에 한번만 업로드
    StaticRead = GL_STATIC_READ,
    StaticCopy = GL_STATIC_COPY,

    DynamicDraw = GL_DYNAMIC_DRAW, // 렌더링할때마다 버퍼 내용물을 재업로드
    DynamicRead = GL_DYNAMIC_READ,
    DynamicCopy = GL_DYNAMIC_COPY
};

enum class BufferStorageFlag : GLenum {
    MapRead = GL_MAP_READ_BIT,
    MapWrite = GL_MAP_WRITE_BIT,
    MapPersistent = GL_MAP_PERSISTENT_BIT,
    MapCoherent = GL_MAP_COHERENT_BIT,
    DynamicStorage = GL_DYNAMIC_STORAGE_BIT,
    ClientStorage = GL_CLIENT_STORAGE_BIT,
};


enum class BufferMappingFlag : GLenum {
    // 이 넷중에 하나는 필수
    Read = GL_MAP_READ_BIT, // 읽기전용
    Write = GL_MAP_WRITE_BIT, // 쓰기전용
    Persistent = GL_MAP_PERSISTENT_BIT, // 
    Coherent = GL_MAP_COHERENT_BIT,

    // 이 네개는 옵션
    //      이 세개중에 하나라도 켜지면 Read는 불가
    InvalidateRange = GL_MAP_INVALIDATE_RANGE_BIT, // 기존 버퍼의 범위(glMapRange) 를 무효화
    InvalidateBuffer = GL_MAP_INVALIDATE_BUFFER_BIT, // 기존 버퍼 전체를 무효화

    // 동기화 X, 성능 우선
    /*
    *   이거 쓰고 동기화하려면,
        glFinish() -> glUnmapBuffer() 순으로 불러야함
            (또는 glMemoryBarrier(),
             또는 glClientWaitSync 이후에 unmap)
    */
    Unsynchronized = GL_MAP_UNSYNCHRONIZED_BIT,

    FlushExplicit = GL_MAP_FLUSH_EXPLICIT_BIT, // 이게 켜지면 Write는 필수
};


enum class WrappingType : GLenum {
    ClampToEdge = GL_CLAMP_TO_EDGE,
    ClampToBorder = GL_CLAMP_TO_BORDER,
    Repeat = GL_REPEAT,
    MirroredRepeat = GL_MIRRORED_REPEAT
};

enum class FilterType : GLenum {
    Nearest = GL_NEAREST,
    Linear = GL_LINEAR,
    NearestMipmapNearest = GL_NEAREST_MIPMAP_NEAREST,
    LinearMipmapNearest = GL_LINEAR_MIPMAP_NEAREST,
    NearestMipmapLinear = GL_NEAREST_MIPMAP_LINEAR,
    LinearMipmapLinear = GL_LINEAR_MIPMAP_LINEAR
};

enum class InternalFormat : GLenum {
    CompressedRed = GL_COMPRESSED_RED,
    CompressedRedRGTC1 = GL_COMPRESSED_RED_RGTC1,
    CompressedRG = GL_COMPRESSED_RG,
    CompressedRGB = GL_COMPRESSED_RGB,
    CompressedRGBA = GL_COMPRESSED_RGBA,
    CompressedRGRGTC2 = GL_COMPRESSED_RG_RGTC2,
    CompressedSignedRedRGTC1 = GL_COMPRESSED_SIGNED_RED_RGTC1,
    CompressedSignedRGRGTC2 = GL_COMPRESSED_SIGNED_RG_RGTC2,
    CompressedSRGB = GL_COMPRESSED_SRGB,
    DepthStencil = GL_DEPTH_STENCIL,
    Depth24Stencil8 = GL_DEPTH24_STENCIL8,
    Depth32FStencil8 = GL_DEPTH32F_STENCIL8,
    DepthComponent = GL_DEPTH_COMPONENT,
    DepthComponent16 = GL_DEPTH_COMPONENT16,
    DepthComponent24 = GL_DEPTH_COMPONENT24,
    DepthComponent32F = GL_DEPTH_COMPONENT32F,
    R16F = GL_R16F,
    R16I = GL_R16I,
    R16SNorm = GL_R16_SNORM,
    R16UI = GL_R16UI,
    R32F = GL_R32F,
    R32I = GL_R32I,
    R32UI = GL_R32UI,
    R3G3B2 = GL_R3_G3_B2,
    R8 = GL_R8,
    R8I = GL_R8I,
    R8SNorm = GL_R8_SNORM,
    R8UI = GL_R8UI,
    Red = GL_RED,
    RG = GL_RG,
    RG16 = GL_RG16,
    RG16F = GL_RG16F,
    RG16SNorm = GL_RG16_SNORM,
    RG32F = GL_RG32F,
    RG32I = GL_RG32I,
    RG32UI = GL_RG32UI,
    RG8 = GL_RG8,
    RG8I = GL_RG8I,
    RG8SNorm = GL_RG8_SNORM,
    RG8UI = GL_RG8UI,
    RGB = GL_RGB,
    RGB10 = GL_RGB10,
    RGB10A2 = GL_RGB10_A2,
    RGB12 = GL_RGB12,
    RGB16 = GL_RGB16,
    RGB16F = GL_RGB16F,
    RGB16I = GL_RGB16I,
    RGB16UI = GL_RGB16UI,
    RGB32F = GL_RGB32F,
    RGB32I = GL_RGB32I,
    RGB32UI = GL_RGB32UI,
    RGB4 = GL_RGB4,
    RGB5 = GL_RGB5,
    RGB5A1 = GL_RGB5_A1,
    RGB8 = GL_RGB8,
    RGB8I = GL_RGB8I,
    RGB8UI = GL_RGB8UI,
    RGB9E5 = GL_RGB9_E5,
    RGBA = GL_RGBA,
    RGBA12 = GL_RGBA12,
    RGBA16 = GL_RGBA16,
    RGBA16F = GL_RGBA16F,
    RGBA16I = GL_RGBA16I,
    RGBA16UI = GL_RGBA16UI,
    RGBA2 = GL_RGBA2,
    RGBA32F = GL_RGBA32F,
    RGBA32I = GL_RGBA32I,
    RGBA32UI = GL_RGBA32UI,
    RGBA4 = GL_RGBA4,
    RGBA8 = GL_RGBA8,
    RGBA8UI = GL_RGBA8UI,
    SRGB8 = GL_SRGB8,
    SRGB8A8 = GL_SRGB8_ALPHA8,
    SRGBA = GL_SRGB_ALPHA,

    R11FG11FB10F = GL_R11F_G11F_B10F,
};

enum class PixelFormat : GLenum {
    Red = GL_RED,
    Green = GL_GREEN,
    Blue = GL_BLUE,
    Alpha = GL_ALPHA,
    RGB = GL_RGB,
    RGBA = GL_RGBA,
    BGR = GL_BGR,
    BGRA = GL_BGRA,
    RG = GL_RG,
    RedInteger = GL_RED_INTEGER,
    RGInteger = GL_RG_INTEGER,
    RGBInteger = GL_RGB_INTEGER,
    BGRInteger = GL_BGR_INTEGER,
    RGBAInteger = GL_RGBA_INTEGER,
    BGRAInteger = GL_BGRA_INTEGER,
    StencilIndex = GL_STENCIL_INDEX,
    DepthComponent = GL_DEPTH_COMPONENT,
    DepthStencil = GL_DEPTH_STENCIL
};

enum class DataType : GLenum {
    Byte = GL_BYTE,
    UnsignedByte = GL_UNSIGNED_BYTE,
    Short = GL_SHORT,
    UnsignedShort = GL_UNSIGNED_SHORT,
    Int = GL_INT,
    UnsignedInt = GL_UNSIGNED_INT,
    Float = GL_FLOAT,
    Double = GL_DOUBLE,

    UnsignedByte332 = GL_UNSIGNED_BYTE_3_3_2,
    UnsignedByte233Rev = GL_UNSIGNED_BYTE_2_3_3_REV,
    UnsignedShort565 = GL_UNSIGNED_SHORT_5_6_5,
    UnsignedShort565Rev = GL_UNSIGNED_SHORT_5_6_5_REV,
    UnsignedShort4444 = GL_UNSIGNED_SHORT_4_4_4_4,
    UnsignedShort4444Rev = GL_UNSIGNED_SHORT_4_4_4_4_REV,
    UnsignedShort5551 = GL_UNSIGNED_SHORT_5_5_5_1,
    UnsignedShort1555Rev = GL_UNSIGNED_SHORT_1_5_5_5_REV,
    UnsignedInt8888 = GL_UNSIGNED_INT_8_8_8_8,
    UnsignedInt8888Rev = GL_UNSIGNED_INT_8_8_8_8_REV,
    UnsignedInt101010102 = GL_UNSIGNED_INT_10_10_10_2
};

class VertexLayout {
private:
    std::vector<std::pair<DataType, uint32_t>> m_attribs{ };
public:
    VertexLayout() = default;
    ~VertexLayout() = default;
public:
    void push_attrib(const DataType& type, const uint32_t& count) {
        m_attribs.emplace_back(type, count);
    }
public:
    const auto& get_attribs() const { return m_attribs; }
public:
    uint32_t get_vertex_size() const {
        uint32_t result = 0;
        for (const auto& attrib : m_attribs) {
            result += static_cast<uint32_t>(VertexLayout::get_data_size(attrib.first) * attrib.second);
        }
        return result;
    }
public:
    static size_t get_data_size(const DataType& type) {
        size_t result = 0;

        switch (type) {
        case (DataType::Byte): { result = sizeof(char); break; }
        case (DataType::UnsignedByte332): [[fallthrough]];
        case (DataType::UnsignedByte233Rev): [[fallthrough]];
        case (DataType::UnsignedByte): { result = sizeof(unsigned char); break; }
        case (DataType::Short): { result = sizeof(short); break; }
        case (DataType::UnsignedShort565): [[fallthrough]];
        case (DataType::UnsignedShort565Rev): [[fallthrough]];
        case (DataType::UnsignedShort4444): [[fallthrough]];
        case (DataType::UnsignedShort4444Rev): [[fallthrough]];
        case (DataType::UnsignedShort5551): [[fallthrough]];
        case (DataType::UnsignedShort1555Rev): [[fallthrough]];
        case (DataType::UnsignedShort): { result = sizeof(unsigned short); break; }
        case (DataType::Int): { result = sizeof(int); break; }
        case (DataType::UnsignedInt8888): [[fallthrough]];
        case (DataType::UnsignedInt8888Rev): [[fallthrough]];
        case (DataType::UnsignedInt101010102): [[fallthrough]];
        case (DataType::UnsignedInt): { result = sizeof(unsigned int); break; }
        case (DataType::Float): { result = sizeof(float); break; }
        case (DataType::Double): { result = sizeof(double); break; }
        default: { assert(false); break; }
        };
        return result;
    }
};

enum class ShaderType : uint32_t {
    Vertex = GL_VERTEX_SHADER,
    TessellationControl = GL_TESS_CONTROL_SHADER,
    TessellationEvaluation = GL_TESS_EVALUATION_SHADER,
    Geometry = GL_GEOMETRY_SHADER,
    Fragment = GL_FRAGMENT_SHADER,
    Compute = GL_COMPUTE_SHADER,
};

struct ShaderTypeHash {
    template <typename T>
    std::size_t operator()(T t) const {
        return static_cast<std::size_t>(t);
    }
};

class Buffer final {
private:
    GLuint m_ID = 0;
public:
    Buffer() {
        glCreateBuffers(1, &m_ID);
    }
    ~Buffer() {
        glDeleteBuffers(1, &m_ID);
    }
public:
    void upload_data(const BufferData& data, const BufferUsage& usage) const {
        glNamedBufferData(m_ID,
            data.get_length(),
            data.get_pointer(),
            (GLenum)(usage)
        );
    }
    void upload_empty_data(const size_t& size, const BufferUsage& usage) const {
        glNamedBufferData(m_ID,
            size,
            nullptr,
            (GLenum)(usage)
        );
    }
    void upload_sub_data(const uint32_t& offset, const BufferData& data) const {
        glNamedBufferSubData(
            m_ID,
            offset,
            data.get_length(), data.get_pointer()
        );
    }
    void download_sub_data(const uint32_t& offset, void* dst, const size_t& size) const {
        glGetNamedBufferSubData(
            m_ID,
            offset,
            size, dst
        );
    }
public:
    void* map(const BufferAccessType& type) const {
        return glMapNamedBuffer(m_ID,
            (GLenum)(type)
        );
    }
    void* map_range(const uint32_t& offset, const size_t& size, const BufferMappingFlag& flag) const {
        return glMapNamedBufferRange(
            m_ID, offset, size, (GLenum)(flag));
    }
    void flush_mapped_range(const uint32_t& offset, const size_t& size) const {
        glFlushMappedNamedBufferRange(
            m_ID,
            offset,
            size
        );
    }
    void unmap() const {
        glUnmapNamedBuffer(m_ID);
    }
public:
    void copy_from(const Buffer& src, const uint32_t& read_offset, const uint32_t& write_offset, const size_t& size) const {
        glCopyNamedBufferSubData(
            src.get_opengl_id(), m_ID,
            read_offset, write_offset, size
        );
    }
    void copy_to(const Buffer& dst, const uint32_t& read_offset, const uint32_t& write_offset, const size_t& size) const {
        glCopyNamedBufferSubData(
            m_ID, dst.get_opengl_id(),
            read_offset, write_offset, size
        );
    }
public:
    void clear_data(const InternalFormat& iformat, const PixelFormat& format, const DataType& data_type, const void* data /* 배열 아님. 보통 0임 */) const {
        glClearNamedBufferData(
            m_ID,
            (GLenum)(iformat),
            (GLenum)(format),
            (GLenum)(data_type), data
        );
    }
    void clear_sub_data(const InternalFormat& iformat, const uint32_t& offset, const size_t& size, const PixelFormat& format, const DataType& data_type, const void* data /* 배열 아님, 보통0 */) const {
        glClearNamedBufferSubData(
            m_ID,
            (GLenum)(iformat),
            offset, size,
            (GLenum)(format),
            (GLenum)(data_type),
            data
        );
    }
public:
    void upload_storage(const BufferData& data, const BufferStorageFlag& flag) const {
        glNamedBufferStorage(
            m_ID,
            data.get_length(), data.get_pointer(),
            (GLenum)(flag)
        );
    }
    void upload_storage(const size_t& size, const BufferStorageFlag& flag) const {
        glNamedBufferStorage(
            m_ID,
            size, nullptr,
            (GLenum)(flag)
        );
    }
public:
    const GLuint& get_opengl_id() const { return m_ID; }
};

class VertexArray final {
private:
    GLuint m_ID = 0;
public:
    VertexArray() {
        glCreateVertexArrays(1, &m_ID);

    }
    ~VertexArray() {
        glDeleteBuffers(1, &m_ID);

    }
public:
    void bind() const {
        glBindVertexArray(m_ID);

    }
public:
    void bind_vertex_buffer(const uint32_t& binding_idx, const Buffer* buffer, const uint32_t& offset, const VertexLayout& layout) const {
        auto vbo_id = buffer->get_opengl_id();
        glVertexArrayVertexBuffer(
            m_ID, binding_idx, vbo_id,
            offset, layout.get_vertex_size()
        );

        const auto& vertex_size = layout.get_vertex_size();
        const auto& attribs = layout.get_attribs();

        int attrib_index = 0;
        uint32_t offset_ptr = 0;

        for (const auto& attrib : attribs) {
            glEnableVertexArrayAttrib(m_ID, attrib_index);

            glVertexArrayAttribFormat(
                m_ID, attrib_index, attrib.second, (GLenum)(attrib.first), GL_FALSE, offset_ptr
            );

            glVertexArrayAttribBinding(
                m_ID,
                attrib_index,
                binding_idx
            );

            offset_ptr += static_cast<uint32_t>(VertexLayout::get_data_size(attrib.first)) * attrib.second;
            attrib_index++;
        }
    }
    void bind_element_buffer(const Buffer* buffer) const {
        glVertexArrayElementBuffer(m_ID, buffer->get_opengl_id());
    }
public:
    void set_divisor(const uint32_t& binding_idx, const uint32_t& divisor) const {
        glVertexArrayBindingDivisor(
            m_ID,
            binding_idx, divisor
        );
    }
public:
    const GLuint& get_opengl_id() const { return m_ID; }
};


class ShaderProgram final {
private:
    std::unordered_map<std::string, UniformType>
        m_uniform_type_map{ };
private:
    GLuint m_ID = 0;
private:
    std::unordered_map<ShaderType, GLuint, ShaderTypeHash> m_shader_map{ };
    std::unordered_map<std::string, int> m_uniform_location_map{ };
private:
private:
    // 서브루틴 기능은 OpenGL에만 있다.
    struct SubroutineInfo {
        // 타겟 uniform 서브루틴 이름 -->  해당 셰이더에서의 인덱스
        std::unordered_map<std::string, GLuint> location_map{ };
        // 특정 서브루틴 이름         -->  해당 서브루틴의 인덱스
        std::unordered_map<std::string, GLuint> index_map{ };
        // 이걸 전부 glUniformSubroutinesuiv에 전달.
        std::vector<GLuint> storage{};
    };
    mutable std::unordered_map<ShaderType, SubroutineInfo, ShaderTypeHash> m_subroutine_info_map{ };
public:
    ShaderProgram() {
        m_ID = glCreateProgram();
    }
    ~ShaderProgram() {
        for (const auto& [type, id] : m_shader_map) {
            glDetachShader(m_ID, id);
            glDeleteShader(id);
        }
        glDeleteProgram(m_ID);
    }
public:
    void use() const {
        glUseProgram(m_ID);
    }
public:
    void attach_shader(const ShaderType& type, const std::string_view& src) {
        assert(m_shader_map.find(type) == m_shader_map.end());
        uint32_t id = glCreateShader((GLenum)(type));
        const auto* ptr = src.data();
        glShaderSource(id, 1, &ptr, NULL);
        glCompileShader(id);
        int success = 0;
        glGetShaderiv(id, GL_COMPILE_STATUS, &success);
        if (!success) {
            char buffer[1024] = { 0, };
            glGetShaderInfoLog(id, 1024, NULL, buffer);
            std::cout << "failed to compile shader : " << buffer << "\n";
            assert(false);
        }
        m_shader_map[type] = id;
        glAttachShader(m_ID, id);
    }
    void link() const {
        glLinkProgram(m_ID);
        int success = 0;
        glGetProgramiv(m_ID, GL_LINK_STATUS, &success);
        if (!success) {
            char buffer[1024] = { 0, };
            glGetProgramInfoLog(m_ID, 1024, NULL, &buffer[0]);
            std::cout << "failed to link program : " << buffer << "\n";
            assert(false);
        }
    }
public:
    void set_transform_feedback_varyings(const std::vector<std::string_view>& varyings, const TransformFeedbackCaptureMode& capture_mode) const {
        std::vector<const char*> strs{};
        strs.reserve(varyings.size());
        for (const auto& s : varyings) { strs.emplace_back(s.data()); }
        glTransformFeedbackVaryings(
            m_ID, static_cast<GLsizei>(strs.size()), strs.data(),
            (GLenum)(capture_mode)
        );
    }
    void get_varying(const uint32_t& index, std::string& out_name, uint32_t& out_size /* 배열이면 out_size > 1 */, UniformType& out_type) const {
        char name[64] = { 0, };
        GLsizei length = 0, size = 0;
        GLenum type = 0;

        glGetTransformFeedbackVarying(
            m_ID,
            index,
            64,
            &length,
            &size,
            &type,
            name
        );

        out_name = name;
        out_size = size;
        out_type = (UniformType)(type);
    }
public:
    void upload_uniform_bool(const std::string& name, const bool& value) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::Bool);
        glProgramUniform1i(m_ID, m_uniform_location_map.at(name), value);
    }
    void upload_uniform_int(const std::string& name, const int& value) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::Int);
        glProgramUniform1i(m_ID, m_uniform_location_map.at(name), value);
    }
    void upload_uniform_float(const std::string& name, const float& value) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::Float);
        glProgramUniform1f(m_ID, m_uniform_location_map.at(name), value);
    }
    void upload_uniform_vec2f(const std::string& name, const glm::vec2& value) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::Vec2f);
        glProgramUniform2f(m_ID, m_uniform_location_map.at(name), value.x, value.y);
    }
    void upload_uniform_vec3f(const std::string& name, const glm::vec3& value) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::Vec3f);
        glProgramUniform3f(m_ID, m_uniform_location_map.at(name), value.x, value.y, value.z);
    }
    void upload_uniform_vec4f(const std::string& name, const glm::vec4& value) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::Vec4f);
        glProgramUniform4f(m_ID, m_uniform_location_map.at(name), value.x, value.y, value.z, value.w);
    }
    void upload_uniform_mat4f(const std::string& name, const glm::mat4& value) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::Mat4f);
        glProgramUniformMatrix4fv(m_ID, m_uniform_location_map.at(name), 1, GL_FALSE, &value[0][0]);
    }
    void upload_uniform_sampler2d(const std::string& name, const int& slot) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::Sampler2D);
        glProgramUniform1i(m_ID, m_uniform_location_map.at(name), slot);
    }
    void upload_uniform_sampler2d_array(const std::string& name, const int& slot) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::Sampler2DArray);
        glProgramUniform1i(m_ID, m_uniform_location_map.at(name), slot);
    }
    void upload_uniform_sampler_cube(const std::string& name, const int& slot) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::SamplerCube);
        glProgramUniform1i(m_ID, m_uniform_location_map.at(name), slot);
    }
public:
    void upload_uniform_subroutine(const ShaderType& type, const std::string& target_name, const std::string& subroutine_fn_name) const {
        auto& info = m_subroutine_info_map.at(type);
        GLuint loc = info.location_map.at(target_name);
        GLuint index = info.index_map.at(subroutine_fn_name);
        // 기록 하고? 다시 갱신해주는거임.
        info.storage.at(loc) = index;
        glUniformSubroutinesuiv(
            (GLenum)(type),
            info.storage.size(),
            info.storage.data()
        );
    }
public:
    void register_uniform(const std::string& name, const UniformType& type) {

        assert(m_uniform_type_map.find(name) == m_uniform_type_map.end());
        m_uniform_type_map[name] = type;

        auto loc = glGetUniformLocation(m_ID, name.c_str());

        // GLSL컴파일러가 너무 똑똑해서 안쓰는건 다 없애버리기에 
        // 이걸 해놓으면 (디버깅이) 귀찮아짐
        //assert(loc != -1);
        m_uniform_location_map[name] = loc;

        if (loc == -1) { return; }

        {
            const GLchar* str = name.c_str();
            const GLchar* const arr[] = { str };

            // 주의 : 컴파일단에서 안쓰이는거 없어진 경우
            //      여기서 INVALID_INDEX뜸..
            GLuint gl_index{};
            glGetUniformIndices(m_ID, 1, arr, &gl_index);

            assert(gl_index != GL_INVALID_INDEX);

            GLint gl_type{};
            glGetActiveUniformsiv(m_ID, 1, &gl_index, GL_UNIFORM_TYPE, &gl_type);

            assert((GLenum)type == (gl_type));
        }
    }
public:
    void set_uniform_block_binding(const uint32_t& block_index, const uint32_t& binding) const {
        glUniformBlockBinding(m_ID, block_index, binding);
    }
    uint32_t get_uniform_block_index(const std::string& name) const {
        return glGetUniformBlockIndex(m_ID, name.c_str());
    }
public:
    const uint32_t& get_opengl_id() const { return m_ID; }
private:
    void _register_subroutines() {

        GLenum interfaces[] = {
            GL_VERTEX_SUBROUTINE,
            GL_GEOMETRY_SUBROUTINE,
            GL_TESS_CONTROL_SUBROUTINE,
            GL_TESS_EVALUATION_SUBROUTINE,
            GL_FRAGMENT_SUBROUTINE,
            GL_COMPUTE_SUBROUTINE
        };
        ShaderType shader_stages[] = {
            ShaderType::Vertex,
            ShaderType::Geometry,
            ShaderType::TessellationControl,
            ShaderType::TessellationEvaluation,
            ShaderType::Fragment,
            ShaderType::Compute
        };

        GLint interfaces_count = std::size(interfaces);

        for (GLint i = 0; i < interfaces_count; ++i) {
            /* Get all active subroutines */
            GLenum program_interface = interfaces[i];

            // 해당 셰이더에 정의된 subroutine의 개수
            GLint num_subroutines = 0;
            glGetProgramInterfaceiv(m_ID, program_interface, GL_ACTIVE_RESOURCES, &num_subroutines);

            const GLenum properties[] = { GL_NAME_LENGTH };
            const GLint properties_size = sizeof(properties) / sizeof(properties[0]);

            // 해당 셰이더에 얼만큼 크기의 서브루틴배열을 넘겨야 하는가??
            GLint count_subroutine_locations = 0;
            glGetProgramStageiv(m_ID, (GLenum)(shader_stages[i]), GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS, &count_subroutine_locations);
            m_subroutine_info_map[shader_stages[i]]
                .storage.resize(count_subroutine_locations);

            // location_map 채우기
            std::vector<std::string> uniform_names{};
            GLint count = 0;
            glGetProgramInterfaceiv(m_ID, program_interface, GL_ACTIVE_RESOURCES, &count);
            for (GLint i = 0; i < count; ++i) {
                char name[256];
                GLsizei length = 0;
                glGetProgramResourceName(
                    m_ID,
                    program_interface,
                    i,
                    sizeof(name),
                    &length,
                    name
                );
                uniform_names.push_back(std::string(name));
            }
            for (const auto& name : uniform_names) {
                GLuint location = glGetSubroutineUniformLocation(
                    m_ID,
                    (GLenum)(shader_stages[i]),
                    name.c_str()
                );

                m_subroutine_info_map[shader_stages[i]]
                    .location_map.at(name) = location;
            }

            // index_map 채우기
            for (GLint j = 0; j < num_subroutines; ++j) {
                GLint values[properties_size];
                GLint length = 0;
                glGetProgramResourceiv(m_ID, program_interface, j, properties_size, properties, properties_size, &length, values);

                std::vector<char> name_data(values[0]);
                glGetProgramResourceName(m_ID, program_interface, j, name_data.size(), nullptr, &name_data[0]);
                std::string subroutine_name(name_data.begin(), name_data.end() - 1);

                GLuint subroutine_index = glGetSubroutineIndex(m_ID, (GLenum)(shader_stages[i]), subroutine_name.c_str());

                m_subroutine_info_map[shader_stages[i]]
                    .index_map[subroutine_name] = subroutine_index;
            }
        }
    }
};

struct TextureDesc {
    FilterType MagFilter = FilterType::Linear;
    FilterType MinFilter = FilterType::Linear;
    WrappingType WrappingS = WrappingType::Repeat;
    WrappingType WrappingT = WrappingType::Repeat;
    WrappingType WrappingR = WrappingType::Repeat;
    InternalFormat FormatInternal = InternalFormat::RGBA8;
    PixelFormat FormatPixel = PixelFormat::RGBA;
    DataType FormatData = DataType::UnsignedByte;
    bool     MipmapGeneration = false;
    // 해당 텍스쳐의 밉맵을 몇 개나 생성할 건지.
    std::optional<int>   MipmapLevel = std::nullopt;
};


class Texture2D final {
private:
    mutable glm::uvec2 m_size{};
private:
    mutable TextureDesc m_desc{};
private:
    GLuint m_ID = 0;
public:
    Texture2D() {
        glCreateTextures(GL_TEXTURE_2D, 1, &m_ID);
    }
    ~Texture2D() {
        glDeleteTextures(1, &m_ID);
    }
public:
    void initialize_empty(const glm::uvec2& size, const TextureDesc& desc) const {
        m_size = size;
        m_desc = desc;

        // 밉맵 최대 레벨이 1이면 밉맵X, 기본 1개만 사용
        int mip_level_count = 1;
        if (desc.MipmapGeneration == true) {
            if (desc.MipmapLevel.has_value()) {
                mip_level_count = desc.MipmapLevel.value();
            }
            else {
                mip_level_count = 1 + static_cast<int>(std::floor(std::log2(std::max(size.x, size.y))));
            }
        }
        glTextureStorage2D(m_ID, mip_level_count,
            (GLenum)desc.FormatInternal,
            static_cast<int>(size.x), static_cast<int>(size.y)
        );

        glTextureParameteri(this->m_ID, GL_TEXTURE_MIN_FILTER, (GLenum)desc.MinFilter);
        glTextureParameteri(this->m_ID, GL_TEXTURE_MAG_FILTER, (GLenum)desc.MagFilter);
        glTextureParameteri(this->m_ID, GL_TEXTURE_WRAP_S, (GLenum)desc.WrappingS);
        glTextureParameteri(this->m_ID, GL_TEXTURE_WRAP_T, (GLenum)desc.WrappingT);

        glClearTexImage(m_ID, 0,
            (GLenum)desc.FormatPixel,
            (GLenum)desc.FormatData,
            nullptr
        );

        // 앞에서 0으로 mipmap레벨 0을 초기화했으므로
        //      이 명령은 유효하다
        if (desc.MipmapGeneration == true) {
            glGenerateTextureMipmap(m_ID);
        }
    }
    void initialize_by_bytes(const glm::uvec2& size, const void* data, const TextureDesc& desc) const {
        m_size = size;

        // 밉맵 최대 레벨이 1이면 밉맵X, 기본 1개만 사용
        int mip_level_count = 1;

        if (desc.MipmapGeneration == true) {
            if (desc.MipmapLevel.has_value()) {
                mip_level_count = desc.MipmapLevel.value();
            }
            else {
                mip_level_count = 1 + static_cast<int>(std::floor(std::log2(std::max(size.x, size.y))));
            }
        }

        glTextureStorage2D(m_ID, mip_level_count,
            (GLenum)desc.FormatInternal,
            static_cast<int>(size.x), static_cast<int>(size.y)
        );

        glTextureParameteri(m_ID, GL_TEXTURE_MIN_FILTER, (GLenum)desc.MinFilter);
        glTextureParameteri(m_ID, GL_TEXTURE_MAG_FILTER, (GLenum)desc.MagFilter);
        glTextureParameteri(m_ID, GL_TEXTURE_WRAP_S, (GLenum)desc.WrappingS);
        glTextureParameteri(m_ID, GL_TEXTURE_WRAP_T, (GLenum)desc.WrappingT);

        // 그냥 여기서 레벨 0만 초기화하고,
        //      glGenerateTextureMipmap()  불러주면 자동으로 채워짐.
        glTextureSubImage2D(
            m_ID,
            0, // 레벨 0만 초기화
            0, 0, // 오프셋
            static_cast<int>(size.x),
            static_cast<int>(size.y),
            (GLenum)desc.FormatPixel,
            (GLenum)desc.FormatData,
            data
        );

        if (desc.MipmapGeneration == true) {
            glGenerateTextureMipmap(m_ID);
        }
    }
public:
    void upload_sub_image(const glm::ivec2& offset, const glm::uvec2& mipmap_size, const int& mip_lvl, const void* ptr) const {

        // 이미 init이 되어 있다고 가정
        //      -> texStorage 이미 끝남....
        glTextureSubImage2D(
            m_ID,
            mip_lvl, // 타겟팅하는 밉맵 레벨
            offset.x, offset.y, // 오프셋
            static_cast<int>(mipmap_size.x), // 해당 밉맵 크기
            static_cast<int>(mipmap_size.y), // 해당 밉맵 크기
            (GLenum)m_desc.FormatPixel,
            (GLenum)m_desc.FormatData,
            ptr
        );
    }
public:
    void bind_unit(const uint32_t& slot) const {
        glBindTextureUnit(slot, m_ID);
    }
public:
    const GLuint& get_opengl_id() const { return m_ID; }
};


int main() {
    glfwInit();

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    GLFWwindow* window = glfwCreateWindow(1280, 720, "Texture + class wrapper ", nullptr, nullptr);

    glfwMakeContextCurrent(window);
    assert(gladLoadGL() != 0);

    // 정점 데이터를 준비합니다.
    BufferData vertices_data{}; {
        vertices_data.add_vec4({-0.5f, 0.5f, 0.0f, 1.0f});// 첫 번째 정점 (사각형의 topleft)
        vertices_data.add_vec4({0.5f, 0.5f, 1.0f, 1.0f});// 두 번째 정점 (사각형의 topright)
        vertices_data.add_vec4({0.5f, -0.5f, 1.0f, 0.0f});// 세 번째 정점 (사각형의 bottomright)
        vertices_data.add_vec4({-0.5f, -0.5f, 0.0f, 0.0f});// 네 번째 정점 (사각형의 bottomleft)
    }

    // 인덱스 데이터를 준비합니다.
    BufferData indices_data{}; {
        // 반시계방향으로!!
        indices_data.add_uint32(0);
        indices_data.add_uint32(3);
        indices_data.add_uint32(1);
        indices_data.add_uint32(1);
        indices_data.add_uint32(3);
        indices_data.add_uint32(2);
    }

    VertexArray va{};
    Buffer vb{}, eb{};

    vb.upload_data(vertices_data, BufferUsage::StaticDraw);
    eb.upload_data(indices_data, BufferUsage::StaticDraw);

    VertexLayout va_layout{}; {
        va_layout.push_attrib(DataType::Float, 2);
        va_layout.push_attrib(DataType::Float, 2);
    }

    va.bind_vertex_buffer(0, &vb, 0, va_layout);
    va.bind_element_buffer(&eb);

    ShaderProgram program{};
    program.attach_shader(ShaderType::Vertex, s_vertex_shader_src);
    program.attach_shader(ShaderType::Fragment, s_fragment_shader_src);
    program.link();
    program.register_uniform("uSize", UniformType::Vec2f);
    program.register_uniform("uProj", UniformType::Mat4f);
    program.register_uniform("uView", UniformType::Mat4f);
    program.register_uniform("uWorld", UniformType::Mat4f);
    program.register_uniform("uTexture", UniformType::Sampler2D);

    Texture2D tex{};
    {
        TextureDesc desc{ };
        int w{}, h{}, c{};
        stbi_set_flip_vertically_on_load(true);
        auto* data = stbi_load("image.png", &w, &h, &c, 0);
        assert(data != nullptr);
        assert(c == 4);

        tex.initialize_by_bytes({ w, h }, data, desc);

        stbi_image_free(data);
    }

    ProjectionMatrix2D proj_mat{ {1280, 720}, -1.0f, 1.0f };

    ViewMatrix2D view_mat{};
    view_mat.set_position({ 640, 360 });

    Transform2D world_mat{};
    world_mat.set_position({ 640, 360 });

    while (glfwWindowShouldClose(window) == false) {
        glfwPollEvents();
        {
            float speed = 2.0f;
            if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) {
                world_mat.set_position(world_mat.get_position() - glm::vec2(speed, 0.0f));
            }
            if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) {
                world_mat.set_position(world_mat.get_position() + glm::vec2(speed, 0.0f));
            }
            if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) {
                world_mat.set_position(world_mat.get_position() - glm::vec2(0.0f, speed));
            }
            if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) {
                world_mat.set_position(world_mat.get_position() + glm::vec2(0.0f, speed));
            }
            if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS) {
                world_mat.set_rotation(world_mat.get_rotation() + 0.01f);
            }
            if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS) {
                world_mat.set_rotation(world_mat.get_rotation() - 0.01f);
            }
            if (glfwGetKey(window, GLFW_KEY_COMMA) == GLFW_PRESS) {
                world_mat.set_scale(world_mat.get_scale() - glm::vec2(0.01f));
            }
            if (glfwGetKey(window, GLFW_KEY_PERIOD) == GLFW_PRESS) {
                world_mat.set_scale(world_mat.get_scale() + glm::vec2(0.01f));
            }
        }
        {
            // 화면 초기화 색상을 초록색으로 정하고, 컬러 버퍼와 깊이 버퍼를 초기화합니다.
            glClearColor(0.2f, 0.3f, 0.1f, 1.0f);
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

            // 정점 배열과 프로그램을 지정합니다.
            //     glDraw* 함수를 부르려면 이 두 코드가 꼭 필요합니다.
            va.bind();
            program.use();

            program.upload_uniform_vec2f("uSize", { 100, 100 });
            program.upload_uniform_mat4f("uProj", proj_mat.get_matrix());
            program.upload_uniform_mat4f("uView", view_mat.get_matrix());
            program.upload_uniform_mat4f("uWorld", world_mat.get_matrix());
            tex.bind_unit(0);
            program.upload_uniform_sampler2d("uTexture", 0);

            // glDrawElements 는 인덱스 버퍼를 사용한다는 가정 하에 쓰이는 렌더 콜입니다.
            // 첫번째 인자 : 프리미티브를 지정합니다. 이 경우에서는 GL_TRIANGLES, 즉 삼각형을 그립니다.
            // 두번째 인자 : 인덱스의 개수를 지정합니다. 아까 인덱스 데이터의 개수는 3개였습니다.
            // 세번째 인자 : 인덱스 데이터의 형태를 지정합니다. 아까 인덱스 데이터의 형은 uint32_t 형이었습니다.
            // 네번째 인자 : 인덱스 데이터의 오프셋을 지정합니다. 보통은 0으로 둡니다.
            glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
        }
        glfwSwapBuffers(window);
    }

    glfwDestroyWindow(window);

    glfwTerminate();
}