Skip to content

07. 3D로의 확장


목차

  • 3차원으로 확장하기
  • Transform3D 구현
  • ViewMatrix3D 구현 (오일러각)
  • ProjectionMatrix3D 구현
  • 뎁스 테스트와 백페이스 컬링
  • 회전하는 3D 큐브 그리기 (정점/인덱스, drawElement수정)

3차원으로 확장하기

지금까지 저희는 2차원 좌표 내에서 도형을 그렸습니다.

그런데, 혹시 정점 셰이더에서 gl_Position 을 쓸 때에

2차원 점인 vec2 aPosvec4(aPos, 0, 1) 로 늘려서 곱했던 것이 기억나시나요?

2차원의 정점일 때, Z축을 0으로 고정시켜 XY 평면 위의 점이란 것을 표현한 것입니다.

여기서 aPosvec3 형, 즉 3차원 점으로 바꾸고

적절한 뷰 행렬과 투영 행렬, 정점 데이터를 제공해 주면

도형을 그대로 3차원으로 그릴 수 있습니다.

축을 하나 늘리기 위해서는:

  • Transform2D -> Transform3D
  • ViewMatrix2D -> ViewMatrix3D
  • ProjectionMatrix2D -> ProjectionMatrix3D

이렇게 이전에 만들었던 WVP 시리즈를

3차원으로 확장시켜야 합니다.

그러면 우선 저 세 클래스를 새로 구현해 봅시다.

Transform3D 구현

저희가 전에 만들었던 Transform2D의 경우,

위치 / 스케일 값이 glm::vec2 형으로 2차원 벡터이며,

회전 값이 float 형으로 스칼라, 즉 Z축 하나에 대한 회전으로 표현했습니다.

3차원에서는, 위치, 스케일 값이 glm::vec3 형으로 3차원 벡터이며

회전 값 또한 (X, Y, Z) 3개의 축을 사용합니다.

glm::vec3 형으로, 각 속성은

  • 피치(Pitch) : X축에서의 회전
  • 요(Yaw) : Y축에서의 회전
  • 롤(Roll) : Z축에서의 회전

을 뜻하게 됩니다.

(물론 Transform2D 에서와 마찬가지로, 각 시스템은 라디안을 사용합니다.)

이렇게 3개의 실수로 3차원의 각을 표현하는 방식을

오일러 각 이라고 합니다.

Warning

일단 지금 시점에서는 3차원 회전을 표현하기 위해서
오일러 각을 사용합니다.
오일러 각은 3차원 벡터가 그대로
3개의 축에 매핑되어 매우 직관적이라는 장점이 있지만,
짐벌 락 이라는 심각한 결함이 있습니다.
이를 간단히 설명하면,
3개의 축 중 2개가 완전히 겹치게 되면서,
1개의 축의 의미가 상실되는 현상입니다.
물론 평범한 FPS 카메라처럼
Z축을 쓰지 않는다면 간단한 회전에는 문제가 없지만,
오일러각 만으로는 회전값 보간에 제약이 있습니다.
추후에는 사원수(Quaternion) 라는 각 표현 시스템을 소개하겠습니다.

먼저 클래스 멤버입니다.

class Transform3D final {
private:
    glm::vec3 m_position{ 0.0f, 0.0f, 0.0f };
private:
    glm::vec3 m_rotation{ 0.0f, 0.0f, 0.0f}; // 라디안입니다
private:
    glm::vec3 m_scale{ 1.0f, 1.0f, 1.0f };
private:
    glm::mat4 m_matrix{ 1.0f };

속성의 이름 자체에는 변화가 없습니다.

3차원에 맞추어 타입만 변했단 것에 주의하세요.

다음은 생성자 / 소멸자와 기본적인 setter / getter입니다.

public:
    Transform3D() {
        this->_update_matrix();
    }
    Transform3D(const glm::vec3& pos, const glm::vec3& rot, const glm::vec3& scl) 
        : m_position(pos), m_rotation(rot), m_scale(scl)
    {
        _update_matrix();
    }
    ~Transform3D() = default;
public:
    void set_position(const glm::vec3& value) { m_position = value; _update_matrix(); }
    void set_rotation(const glm::vec3& value) { m_rotation = value; _update_matrix(); }
    void set_scale(const glm::vec3& value) { m_scale = value; _update_matrix(); }
public:
    const glm::mat4& get_matrix() const { return m_matrix; }
    const glm::vec3& get_position() const { return m_position; }
    const glm::vec3& get_rotation() const { return m_rotation; }
    const glm::vec3& get_scale() const { return m_scale; }

마지막으로 _update_matrix 입니다.

private:
    void _update_matrix() {
        auto scaling = glm::scale(glm::mat4{ 1.0f }, m_scale);
        auto rotation =
            glm::rotate(glm::mat4(1.0f), m_rotation.y, { 0.0f, 1.0f, 0.0f });
        rotation = glm::rotate(rotation, m_rotation.z, { 0.0f, 0.0f, 1.0f });
        rotation = glm::rotate(rotation, m_rotation.x, { 1.0f, 0.0f, 0.0f });
        auto translation = glm::translate(glm::mat4{ 1.0f }, m_position);
        m_matrix = translation * rotation * scaling;
    }
};

주의할 점은, translationscaling

Transform2D와 동일한 함수를 사용하지만 3차원 벡터를 그대로 넘긴다는 것과

rotation 을 계산할 때

Y축 (0, 1, 0) -> Z축 (0, 0, 1) -> X축 (1, 0, 0) 순으로

glm::rotate() 함수를 통해서

회전을 '누적해' 간다는 것입니다.

이때, 저는 Y-Z-X 순서를 사용했지만,

오일러 각으로 회전 행렬을 만들 때에는

3개의 축을 곱하는 순서가 하나로 정해져 있지 않습니다.

따라서 Z-Y-X 같은 순서를 사용하고 싶다면,

전체 엔진 / 프레임워크에서 통일한다는 가정 하에, 그냥 그걸 쓰시면 됩니다.

또한 T * R * S 라는 순서는 Transform2D와 동일합니다.

ViewMatrix3D 구현

뷰 행렬의 경우, 2D 에서는 glm::vec2 m_zoom {1, 1} 이라는

화면 자체를 줌 인 / 아웃 시키는 속성이 있었습니다.

3차원에서의 뷰 행렬은

'3차원 카메라의 위치와 회전 정보'

를 담는 데에 의의가 있습니다.

따라서 3차원 뷰 행렬만으로는 화면을 줌 인/아웃 시키진 못합니다.

거의 대부분의 3D 게임 - 특히 FPS 같은 장르의 게임이라면

화면 자체를 줌 인 / 아웃시킬 때

FoV (Field of View) 를 늘리거나 줄이는데,

이는 뷰 행렬이 아닌,

바로 밑 섹션의 투영 행렬(Projection matrix)에서 담당하는 속성입니다.

그 점만 빼면

ViewMatrix2D 와는 거의 동일합니다.

먼저 클래스 멤버입니다.

class ViewMatrix3D final {
private:
    glm::vec3 m_position { 0.0f, 0.0f, 0.0f };
private:
    float m_yaw = 0.0f;   // Y축(업벡터) 기준
    float m_pitch = 0.0f; // right 축기준
private:
    glm::vec3 m_target { 0.0f, 0.0f, -1.0f };
    glm::vec3 m_up     { 0.0f, 1.0f, 0.0f };
    glm::vec3 m_right { 1.0f, 0.0f, 0.0f };
private:
    glm::mat4 m_matrix{ 1.0f };

m_yawm_pitch는 각각,

3D 카메라가 Y축 기준으로 얼마나 회전했는지와

Right 벡터 축 기준으로 얼마나 회전했는지를 나타냅니다.

여기서 Target, Up, Right 벡터들에 대해서 설명해드리겠습니다.

이전에 좌표계를 설명하면서 보여드린

뷰 공간 에서의 좌표계를 기억하시나요?

오른손 좌표계로써, '카메라의 위치'를 기준으로

카메라는 -Z 방향을 바라보는 형태였죠.

이를 통해 저희는 '3D 카메라의 관점'에서,

  • 앞을 향하는 벡터
  • 오른쪽을 향하는 벡터
  • 위를 향하는 벡터

이렇게 정규화된 기저 벡터 3개를 만들 수 있습니다.

밑에 그림을 참고해주세요.

7_0.png

카메라가 회전하면, 저 3개의 축들도 회전하게 됩니다.

다음으로 생성자 / 소멸자, setter/getter입니다.

public:
    ViewMatrix3D() {
        this->_update_matrix();
    }
    void set_position(const glm::vec3& pos) {
        m_position = pos;
        this->_update_matrix();
    }
    void add_yaw(const float& value) {
        m_yaw += value;
        this->_update_matrix();
    }
    void add_pitch(const float& value) {
        m_pitch += value;
        m_pitch = glm::clamp(m_pitch, -glm::radians(89.0f), glm::radians(89.0f));
        this->_update_matrix();
    }
public:
    glm::vec3 get_front_vector() const {
        return m_target;
    }
    glm::vec3 get_right_vector() const {
        return m_right;
    }
    glm::vec3 get_up_vector() const {
        return m_up;
    }
public:
    const glm::vec3& get_position() const { return m_position; }
    const glm::mat4& get_matrix() const { return m_matrix; }

피치의 경우

하늘을 보려다가 고개가 넘어가거나,

땅을 보다가 너무 숙이지 않도록

[-89도, 89도] 범위 내로 클리핑해줍니다.

마지막으로 _update_matrix 입니다.

private:
    void _update_matrix() {
        const glm::vec3 world_upvec = { 0.0f, 1.0f, 0.0f };

        glm::vec3 forward = {
            std::sin(m_yaw),
            0.0f,
            -std::cos(m_yaw)
        };
        forward = glm::normalize(forward);
        m_right = glm::normalize(glm::cross(forward, world_upvec));

        glm::mat4 pitch_rotmat = glm::rotate(glm::mat4(1.0f), m_pitch, m_right);
        m_target = glm::normalize(glm::vec3(pitch_rotmat * glm::vec4(forward, 0.0f)));

        m_up = glm::normalize(glm::cross(m_right, m_target));

        m_matrix = glm::lookAt(m_position, m_position + m_target, m_up);
    }
};

차근차근 분석해봅시다.

먼저 3D 카메라에서, '위를 가르키는 월드 공간의 벡터' 는

(0, 1, 0) 으로 고정입니다.

이를 선언하고, XZ 평면 위의 forward 라는 3차원 벡터를 만듦니다.

(sin과 cos함수가 사용된 이유는 회전 행렬의 2D 부분을 참고해주세요.

간단히 설명하면, OpenGL 카메라가 기본적으로 바라보는

(0, 0, -1)이라는 벡터를 XZ 평면에서 Yaw각만큼 회전시킨 것입니다.)

이후 정규화된 forward월드 공간 Up벡터 를 외적하여,

Right 벡터를 얻습니다.

다음으로 forward를 Right 축에 대해서 Pitch만큼 회전시켜

Target 벡터를 얻고,

마지막으로 Right와 Target을 외적하여 Up 벡터를 얻게 됩니다.

이해를 위해서 밑의 순서도를 참고하세요.

7_1.png

ProjectionMatrix3D 구현

3차원에서 투영 행렬을 구현하기 전에,

먼저 이전에 언급한 2가지 형태의

투영 방식을 열거형으로 정의합시다.

enum class ProjectionType {
    Perspective,
    Ortho,
};

(각각 원근 투영, 직교 투영을 나타냅니다.)

클래스 멤버입니다.

class ProjectionMatrix3D final {
private:
    glm::uvec2 m_frustrum_size{ /* 0 */ 1280, /* 0 */ 720 };
    float m_near = 0.1f;
    float m_far = 1000.0f;
private:
    float m_fov{ glm::radians(50.0f) };
private:
    ProjectionType m_projection_type = ProjectionType::Perspective;
private:
    glm::mat4 m_matrix{ 1.0f };

절두체를 결정하는 m_frustrum_size, m_near, m_far, m_fov 에 주목하세요.

다음은 생성자와 setter/getter입니다.

public:
    ProjectionMatrix3D() {
        this->_update_matrix();
    }
    ProjectionMatrix3D(const glm::uvec2& frustrum_size, const float& near, const float& far, const float& fov) 
        : m_frustrum_size(frustrum_size),
        m_near(near),
        m_far(far),
        m_fov(fov)
    {
        this->_update_matrix();
    }
    ~ProjectionMatrix3D() = default;
public:
    void set_projection_type(const ProjectionType& type) {
        const auto last_type = m_projection_type;
        m_projection_type = type;
        if (last_type != m_projection_type) {
            this->_update_matrix();
        }
    }
    void set_frustrum_size(const glm::uvec2& value){
        m_frustrum_size = value;
        this->_update_matrix();
    }
    void set_near(const float& value) {
        assert(value != 0.0f);
        m_near = value;
        this->_update_matrix();
    }
    void set_far(const float& value) {
        m_far = value;
        this->_update_matrix();
    }
    void set_fov(const float& value) {
        m_fov = value;
        this->_update_matrix();
    }
public:
    const ProjectionType& get_projection_type() const { return m_projection_type; }
    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; }
    const float& get_fov() const { return m_fov; }
public:
    const glm::mat4& get_matrix() const { return m_matrix; }

마지막으로 _update_matrix입니다.

투영 방식에 따라 행렬을 다르게 만드는 것에 주목하세요.

원근 투영 행렬에는 glm::perspective를,

직교 투영 행렬에는 glm::ortho 를 사용합니다.

private:
    void _update_matrix() {
        if (m_projection_type == ProjectionType::Perspective) {
            m_matrix = glm::perspective(m_fov, float(m_frustrum_size.x) / float(m_frustrum_size.y), m_near, m_far);
        }
        else {
            float width_half = (float(m_frustrum_size.x) / 2.0f);
            float height_half = (float(m_frustrum_size.y) / 2.0f);
            m_matrix = glm::ortho(-width_half, width_half, -height_half, height_half, m_near, m_far);
        }
    }
};

뎁스 테스트와 백페이스 컬링

3D 물체를 그리기 전에 꼭 알아야 하는 것이 있습니다.

바로 뎁스 테스트와 백페이스 컬링입니다.


뎁스 테스트

우선 뎁스 테스트란,

"3차원 공간에서, 이 픽셀이 이전에 그려진 픽셀에 의해 가려지는가?" 를 판단하는 것을 의미합니다.

2. 삼각형 그리기 글에 올린 순서도를 보시면,

레스터라이제이션이 끝난 후에

OpenGL 측에서 해당 픽셀이 가려졌는지를 판단하고,

가려졌다면 그 픽셀을 (보통) 그리지 않습니다.

저희는 지금 3D 공간에서의 물체를 그리기 때문에,

GL 에게 '가려진 픽셀은 그리지 말아 줘' 라는 것을 명시해 줘야 합니다.

관련된 함수들은 다음과 같습니다.

  • glEnable(GL_DEPTH_TEST) / glDisable(GL_DEPTH_TEST)
    -> OpenGL이 뎁스 테스트를 수행할지 여부를 토글
  • glDepthFunc
    -> 뎁스 테스트에서, 새 픽셀의 뎁스와 기존 픽셀의 뎁스를 '어떻게 비교할 건'지 지정
    -> 예를 들어 GL_LESS 를 지정하면 '새 픽셀 뎁스가 기존의 뎁스보다 작을 경우' 통과.
    -> 기본값은 GL_LESS (뒤쪽에 있는 걸 그리지 않음)
  • glDepthMask
    -> 테스트를 통과 시, 기존 뎁스 값을 갱신할지 여부
    -> 쉽게 말해, GL_FALSE를 지정하면 해당 렌더링에 그려진 물체가 다음 뎁스 테스트에 영향을 주지 않음.
  • glClearDepth
    -> 뎁스 버퍼를 초기화할 때 사용할 초기화 값을 지정.
    -> 초기화 값의 기본값은 1이며, 이는 가장 큰 뎁스로 채워놓고 앞쪽에 그려 가면서 갱신하기 위함.

OpenGL 내부에는 창의 크기와 동일한 크기의,
0.0 ~ 1.0 범위의 뎁스 값들을 저장하는 저장소인, '뎁스 버퍼' 가 있습니다.

저희가 삼각형을 그릴 때, 프레임 시작 부분에서

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

GL_DEPTH_BUFFER_BIT 플래그가 뎁스 버퍼의 전체 값을 초기화하라는 뜻입니다.

이전 프레임에 기록된 뎁스를 비우기 위함이죠.

뎁스 버퍼를 시각화하면 밑의 사진과 같아집니다.

물체가 그려지지 않은 곳은 하얀색, 즉 가장 큰 뎁스가 남아있고,

물체가 그려진 곳은 검정색으로, 더 앞에 있는 물체에 의해 갱신된 부분인 것입니다.

7_2.png

Warning

위 사진은 0.0 ~ 1.0 의 뎁스 버퍼를, 시각화를 위해서 0.996 ~ 1.0 범위만 추출하여 나타낸 것입니다.
0.0 ~ 0.99 의 범위에서는 구분이 거의 안 되기 때문입니다.
왜 그렇게 극단적으로 값이 몰려 있는가 하면, 투영 과정에서 뎁스값이 선형으로 저장되지 않기 때문입니다. 저희가 저번에 살펴보았던, 투영에 쓰이는 절두체의 near / far plane 을 떠올려보세요. 뎁스값은 '해당 near / far plane 범위로 잘린 z에 반비례하기' 때문에, 0 ~ 1 범위에 고루 분포하지 않습니다.

이 값을 선형으로 나타내려면 다음과 같은 공식을 쓸 수 있습니다.

Zwin 을 [0, 1] 범위의, Window Space의 뎁스 값이라고 하면 -

Zndc = (2 * Zwin) - 1
Zview = (2 * far * near) / ((far + near) - Zndc * (far - near))
LinDepth = (Zview - near) / (far - near)

뷰 스페이스의 Z를 계산하여, view frustrum 의
[near, far] 영역 안에서의 비율이 선형 뎁스값입니다.
절두체 내의 Z는 아직 원근 나누기가 되기 전이므로,
Z값이 선형으로 나타나는 겁니다.

참고로 NDC 공간의 Z값이 [-1, 1] 인 것은, OpenGL이 유일합니다. DixrectX나 벌칸은 ndc Z에 [0, 1] 범위를 쓴다는 것에 주의하세요.

이에 관해서 더 탐구할 만한 주제로는 이런 게 있습니다.

  • Z-Fighting 방지 (near / far plane, glPolygonOffset)
  • 구간에 따라 달라지는 IEEE 부동 소수점 정밀도
  • Reversed Z

이전에 설명드렸다시피,

glEnable() 을 통해서

OpenGL의 '상태' 를 바꾼 후에야

glDraw* 함수를 통해 그렸을 때 해당 상태가 적용됩니다.

따라서 특정 렌더링에 대해 뎁스 테스트를 토글하고 싶다면

glDraw*같은 렌더 콜이 불리기 전에 상태를 활성 / 비활성화 해주는 걸 잊지 마세요.


지금은 'OpenGL 이 사용자 설정에 따라 뎁스 테스트를 수행하는구나'

라고만 알고 계시면 됩니다.

이후 프레임버퍼 / 렌더버퍼 글에서 뎁스 버퍼에 대해 자세히 설명하겠습니다.

(지금 저희가 쓰고 있는 뎁스 버퍼는 OpenGL이 암시적으로 만드는 '기본 뎁스 버퍼' 입니다)


백페이스 컬링

백페이스 컬링이란,

"카메라 기준으로 보이지 않는 면을 그리지 않는" 기능입니다.

예를 들면, 카메라가 캐릭터의 앞 모습을 보고 있다면

캐릭터의 뒷 모습은 볼 수 없기 때문에,

그러한 부분은 그리지 않는 것이 훨씬 효율적입니다.

관련된 함수들은 다음과 같습니다.

  • glEnable(GL_CULL_FACE) / glDisable(GL_CULL_FACE)
    -> OpenGL이 백페이스 컬링을 수행할지 토글.
  • glFrontFace
    -> 어떤 방향으로 이어지면 '앞면으로 판단'할 건지 결정.
    -> 예를 들어 GL_CCW 로 지정하면, 시계 반대방향으로 이어진 면을 앞면으로 간주.
  • glCullFace
    -> 앞면, 뒷면 중 어느 면을 제거할 건지 결정.
    -> GL_FRONT / GL_BACK 으로 앞면 / 뒷면을 제거.

이전의 순서도를 보시면 아시겠지만,

OpenGL은 프리미티브(Triangle, Line 등) 를

조립(= 정점들을 인덱스로 잇기)한 후에

정점들을 NDC 공간으로 바꿉니다.

이후에, XY축의 평면을 기준으로,

이어진 정점들이 이루는 방향을 계산해서

'이 면(=Face)을 제거할지 말지' 를 결정하는 것이

백페이스 컬링인 것입니다.

이때 사용되는 개념은 다음 수식과 같습니다. $$ (b - a) × (c - a) < 0 $$ 세 개의 2차원 점 a, b, c 가 있을 때,

(b - a) 와 (c - a) 를 외적해서 나온 값(스칼라)이

  • 음수이면 : CW, 시계방향

  • 양수이면 : CCW, 반시계방향

라는 것입니다.

OpenGL에서의 '면' 은 모두

삼각형의 조합으로 표현되기 때문에,

위 공식은 매우 적절합니다.

이해를 위해 다음 그림을 봐주세요.

7_3.png

참고로, 저는 '백페이스' 컬링으로 소개했지만

OpenGL 스펙 상에는 '페이스' 컬링으로 존재합니다.

꼭 카메라 기준 보이지 않는 면만을 없애는 건 아닙니다.

카메라 기준으로 앞면을 없애면

건물의 내부 구조같은 걸 렌더링할 때 유용하기도 하죠.


회전하는 3D 큐브 그리기

3D 렌더링을 위한 인터페이스가 모두 완성되었으니,

이제 멋진 3차원 큐브 하나를 띄워 봅시다.

먼저, 3차원 큐브에 대한

정점 데이터와 인덱스 데이터를 준비해야겠죠?

이전에 텍스쳐를 그리던 코드에서,

BufferData를 준비하는 부분을 다음과 같이 수정해주세요.

큐브, 즉 정육면체를 이루는 정점 정보입니다.

    // 정점 데이터 (vec3 aPos + vec2 aTexCoord)
    BufferData vertices_data{}; {
        // Front (+Z)
        vertices_data.add_vec3({ -0.5f,  0.5f,  0.5f }); vertices_data.add_vec2({ 0.0f, 1.0f });
        vertices_data.add_vec3({ 0.5f,  0.5f,  0.5f }); vertices_data.add_vec2({ 1.0f, 1.0f });
        vertices_data.add_vec3({ 0.5f, -0.5f,  0.5f }); vertices_data.add_vec2({ 1.0f, 0.0f });
        vertices_data.add_vec3({ -0.5f, -0.5f,  0.5f }); vertices_data.add_vec2({ 0.0f, 0.0f });
        // Back (-Z)
        vertices_data.add_vec3({ 0.5f,  0.5f, -0.5f }); vertices_data.add_vec2({ 0.0f, 1.0f });
        vertices_data.add_vec3({ -0.5f,  0.5f, -0.5f }); vertices_data.add_vec2({ 1.0f, 1.0f });
        vertices_data.add_vec3({ -0.5f, -0.5f, -0.5f }); vertices_data.add_vec2({ 1.0f, 0.0f });
        vertices_data.add_vec3({ 0.5f, -0.5f, -0.5f }); vertices_data.add_vec2({ 0.0f, 0.0f });
        // Left (-X)
        vertices_data.add_vec3({ -0.5f,  0.5f, -0.5f }); vertices_data.add_vec2({ 0.0f, 1.0f });
        vertices_data.add_vec3({ -0.5f,  0.5f,  0.5f }); vertices_data.add_vec2({ 1.0f, 1.0f });
        vertices_data.add_vec3({ -0.5f, -0.5f,  0.5f }); vertices_data.add_vec2({ 1.0f, 0.0f });
        vertices_data.add_vec3({ -0.5f, -0.5f, -0.5f }); vertices_data.add_vec2({ 0.0f, 0.0f });
        // Right (+X)
        vertices_data.add_vec3({ 0.5f,  0.5f,  0.5f }); vertices_data.add_vec2({ 0.0f, 1.0f });
        vertices_data.add_vec3({ 0.5f,  0.5f, -0.5f }); vertices_data.add_vec2({ 1.0f, 1.0f });
        vertices_data.add_vec3({ 0.5f, -0.5f, -0.5f }); vertices_data.add_vec2({ 1.0f, 0.0f });
        vertices_data.add_vec3({ 0.5f, -0.5f,  0.5f }); vertices_data.add_vec2({ 0.0f, 0.0f });
        // Top (+Y)
        vertices_data.add_vec3({ -0.5f, 0.5f, -0.5f }); vertices_data.add_vec2({ 0.0f, 1.0f });
        vertices_data.add_vec3({ 0.5f, 0.5f, -0.5f }); vertices_data.add_vec2({ 1.0f, 1.0f });
        vertices_data.add_vec3({ 0.5f, 0.5f,  0.5f }); vertices_data.add_vec2({ 1.0f, 0.0f });
        vertices_data.add_vec3({ -0.5f, 0.5f,  0.5f }); vertices_data.add_vec2({ 0.0f, 0.0f });
        // Bottom (-Y)
        vertices_data.add_vec3({ -0.5f, -0.5f,  0.5f }); vertices_data.add_vec2({ 0.0f, 1.0f });
        vertices_data.add_vec3({ 0.5f, -0.5f,  0.5f }); vertices_data.add_vec2({ 1.0f, 1.0f });
        vertices_data.add_vec3({ 0.5f, -0.5f, -0.5f }); vertices_data.add_vec2({ 1.0f, 0.0f });
        vertices_data.add_vec3({ -0.5f, -0.5f, -0.5f }); vertices_data.add_vec2({ 0.0f, 0.0f });
    }

    // 인덱스 데이터 (CCW 기준)
    BufferData indices_data{}; {
        for (uint32_t i = 0; i < 6; ++i) {
            uint32_t base = i * 4;
            indices_data.add_uint32(base + 0);
            indices_data.add_uint32(base + 3);
            indices_data.add_uint32(base + 1);

            indices_data.add_uint32(base + 1);
            indices_data.add_uint32(base + 3);
            indices_data.add_uint32(base + 2);
        }
    }

이전에는 정점을 나타내기 위해서

vec2 aPos 를 썼다면,

이제는 3차원 큐브이므로

vec3, 따라서 BufferData를 만들 때에도

3차원 위치정보 + vec2 UV값 형태로 추가해야 합니다.

이어서, 정점 배열과 VBO / EBO 부분도 수정합시다.

방금 말했듯이, 위치 정보를 3차원으로 늘려 주세요.

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

다음으로, 유니폼을 등록할 때

uSize 를 3차원 벡터로 등록해주시면 됩니다.

    program.register_uniform("uSize", UniformType::Vec3f); // 3차원!!
    program.register_uniform("uProj", UniformType::Mat4f);
    program.register_uniform("uView", UniformType::Mat4f);
    program.register_uniform("uWorld", UniformType::Mat4f);
    program.register_uniform("uTexture", UniformType::Sampler2D);

이제 이전에 쓰던

ProjectionMatrix2DViewMatrix2D 대신,

이번에 새로 만든 3D 인터페이스로 갈아끼웁시다.

    //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 });

    ProjectionMatrix3D proj_mat{ {1280, 720}, 0.1f, 1000.0f, glm::radians(45.0f) };
    ViewMatrix3D view_mat{};
    view_mat.set_position({ 0.0f, 0.0f, 100.0f });
    Transform3D world_mat{};
    world_mat.set_position({ 0.0f, 0.0f, 0.0f });

set_position에 3차원 점을 넣는 것과,

proj_matProjection Type 이 원근 투영이므로

near plane과 far plane을

0 < near < far 조건에 맞춰 넣는 것에 유의해주세요.

원근 투영일 경우,

절두체의 영역은 반드시 카메라의 앞쪽에 있어야 하므로

near와 far는 모두 양수이며, far는 무조건 near보다 커야 합니다.

이에 반해 직교 투영의 경우,

near plane과 far plane은 단지 클리핑 기능만 수행하므로

near != far 이기만 하면 됩니다.

그대신 near < far 조건은 직교 투영의 경우에도 지키는 게 좋습니다.


간단한 키 입력도 설정해볼까요?

WASD로 뷰 행렬의 위치 속성을 바꾸고,

화살표 키로 뷰 행렬의 pitch / yaw 속성을 바꿔 봅시다.

    while (glfwWindowShouldClose(window) == false) {
        glfwPollEvents();
        {
            // 카메라
            float speed = 2.0f;
            if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) {
                view_mat.set_position(view_mat.get_position() - glm::vec3(speed, 0.0f, 0.0f));
            }
            if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) {
                view_mat.set_position(view_mat.get_position() + glm::vec3(speed, 0.0f, 0.0f));
            }
            if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) {
                view_mat.set_position(view_mat.get_position() - glm::vec3(0.0f, 0.0f, speed));
            }
            if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) {
                view_mat.set_position(view_mat.get_position() + glm::vec3(0.0f, 0.0f, speed));
            }

            if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS) {
                view_mat.add_yaw(-0.01f);
            }
            if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS) {
                view_mat.add_yaw(0.01f);
            }
            if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS) {
                view_mat.add_pitch(0.01f);
            }
            if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS) {
                view_mat.add_pitch(-0.01f);
            }
        }

큐브가 돌아가려면, 매 프레임에

회전값을 누적해줘야 하는 것도 잊지 마세요.

Y축 회전을 누적하면

턴테이블마냥 돌아갑니다.

        {
            world_mat.set_rotation(world_mat.get_rotation() + glm::vec3(0.0f, 0.01f, 0.0f));
        }

이제 매우 중요한 부분입니다.

3차원 큐브를 그리기 위해서는,

3차원 렌더링에 사용되는 설정을 따로 해줘야 합니다.

저희가 이전에 2차원 렌더링에서 아무 설정도 안 해준경우엔?

  • 뎁스 테스트 : 비활성화
  • 백페이스 컬링 : 비활성화

이러한 상태로 그립니다.

3차원 렌더링에서는, 저 두 기능을 모두 켠 후에

세부 설정을 해줘야 합니다.

다음과 같이 수정해주세요.

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

    glEnable(GL_DEPTH_TEST); // 뎁스 테스트 활성화
    glDepthFunc(GL_LESS); // 새 픽셀의 뎁스가 기존 뎁스보다 작을 경우 (더 앞에 있을 경우) 통과
    glDepthMask(GL_TRUE); // 뎁스 테스트 이후, 뎁스 쓰기(갱신)를 활성화

    glEnable(GL_CULL_FACE);  // 백페이스 컬링 활성화
    glFrontFace(GL_CCW); // 삼각형을 CCW 방향으로 묶은 면이 앞면
    glCullFace(GL_BACK); // 뒷면을 컬링


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

    program.upload_uniform_vec3f("uSize", { 30.0f, 30.0f, 30.0f });
    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, 36, GL_UNSIGNED_INT, 0);
}

저희가 주목해야 할 것은

  • glClearDepth 를 통해 깊이 초기화 값 설정
  • 뎁스 테스트와 관련 세부설정
  • 백페이스 컬링과 관련 세부설정
  • 유니폼 uSize에 3차원 값을 전달
  • glDrawElements 호출 시에, 인덱스 개수값으로 6이 아닌 36을 전달

입니다.

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

부분에서 컬러 버퍼와 뎁스 버퍼가 초기화되는데,

이때의 각 버퍼 초기값을 지정하는 것이

glClearColorglClearDepth 인 것입니다.

또한, 인덱스 개수가 6이 아닌 36을 주어야 하는 이유는

그냥 사각형을 그릴 때에는 삼각형 2개, 즉 인덱스 3개 * 2 였으므로,

당연히 6개의 면이 존재하는 정육면체의 경우 6 * 6 으로 36개의 인덱스를 갖게 됩니다.

indices_data.get_length() / sizeof(uint32_t) 로도 확인하실 수 있습니다.


마지막으로 셰이더 코드만 수정하면 끝입니다.

정점 속성부분을 3차원으로 확장하고,

넘길 때에도 3차원 벡터 그대로 넘겨주세요.

//     이제 3차원 정점이므로 vec3으로 받아야 합니다.
layout (location = 0) in vec3 aPos; 
layout (location = 1) in vec2 aTexCoord; 

layout (location = 0) uniform vec3 uSize = vec3(64, 64, 64);
void main() {
    vec3 pos = (aPos * uSize);

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

프래그먼트 셰이더는 그대로 두어도 괜찮습니다.

실행해보시면, 다음과 같은 화면이 나올겁니다.

(WASD키로 XZ 평면을 돌아다니고, 화살표 키로 상하좌우를 볼 수 있습니다.

잠시 인생처럼 하염없이 돌아가는 큐브를 감상해보세요.)

7_4.png

전체 코드는 다음과 같습니다.

다음 글에서는,

마우스 커서로 자유롭게 카메라의 관점을 조절하고

해당 카메라를 기준으로 앞쪽/뒤쪽/오른쪽/왼쪽/위/아래

6방향으로 이동할 수 있도록

ViewMatrix3D / ProjectionMatrix3D 를 포함한

3차원 카메라 클래스를 만들고,

모든 3D 클래스에 쿼터니언을 도입하여 완전한 3D 카메라를 완성해보도록 하겠습니다.

전체 코드 보기

   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
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
#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

//     이제 3차원 정점이므로 vec3으로 받아야 합니다.
layout (location = 0) in vec3 aPos; 
layout (location = 1) in vec2 aTexCoord; 

layout (location = 0) uniform vec3 uSize = vec3(64, 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() {
    vec3 pos = (aPos * uSize);

    gl_Position = uProj * uView * uWorld * vec4(pos, 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 Transform3D final {
private:
    glm::vec3 m_position{ 0.0f, 0.0f, 0.0f };
private:
    glm::vec3 m_rotation{ 0.0f, 0.0f, 0.0f}; // 라디안입니다
private:
    glm::vec3 m_scale{ 1.0f, 1.0f, 1.0f };
private:
    glm::mat4 m_matrix{ 1.0f };
public:
    Transform3D() {
        this->_update_matrix();
    }
    Transform3D(const glm::vec3& pos, const glm::vec3& rot, const glm::vec3& scl) 
        : m_position(pos), m_rotation(rot), m_scale(scl)
    {
        _update_matrix();
    }
    ~Transform3D() = default;
public:
    void set_position(const glm::vec3& value) { m_position = value; _update_matrix(); }
    void set_rotation(const glm::vec3& value) { m_rotation = value; _update_matrix(); }
    void set_scale(const glm::vec3& value) { m_scale = value; _update_matrix(); }
public:
    const glm::mat4& get_matrix() const { return m_matrix; }
    const glm::vec3& get_position() const { return m_position; }
    const glm::vec3& get_rotation() const { return m_rotation; }
    const glm::vec3& get_scale() const { return m_scale; }
private:
    void _update_matrix() {
        auto scaling = glm::scale(glm::mat4{ 1.0f }, m_scale);
        auto rotation =
            glm::rotate(glm::mat4(1.0f), m_rotation.y, { 0.0f, 1.0f, 0.0f });
        rotation = glm::rotate(rotation, m_rotation.z, { 0.0f, 0.0f, 1.0f });
        rotation = glm::rotate(rotation, m_rotation.x, { 1.0f, 0.0f, 0.0f });
        auto translation = glm::translate(glm::mat4{ 1.0f }, m_position);
        m_matrix = translation * rotation * scaling;
    }
};

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 ViewMatrix3D final {
private:
    glm::vec3 m_position { 0.0f, 0.0f, 0.0f };
private:
    float m_yaw = 0.0f;   // Y축(업벡터) 기준
    float m_pitch = 0.0f; // right 축기준
private:
    glm::vec3 m_target { 0.0f, 0.0f, -1.0f };
    glm::vec3 m_up     { 0.0f, 1.0f, 0.0f };
    glm::vec3 m_right { 1.0f, 0.0f, 0.0f };
private:
    glm::mat4 m_matrix{ 1.0f };
public:
    ViewMatrix3D() {
        this->_update_matrix();
    }
    void set_position(const glm::vec3& pos) {
        m_position = pos;
        this->_update_matrix();
    }
    void add_yaw(const float& value) {
        m_yaw += value;
        this->_update_matrix();
    }
    void add_pitch(const float& value) {
        m_pitch += value;
        m_pitch = glm::clamp(m_pitch, -glm::radians(89.0f), glm::radians(89.0f));
        this->_update_matrix();
    }
public:
    glm::vec3 get_front_vector() const {
        return m_target;
    }
    glm::vec3 get_right_vector() const {
        return m_right;
    }
    glm::vec3 get_up_vector() const {
        return m_up;
    }
public:
    const glm::vec3& get_position() const { return m_position; }
    const glm::mat4& get_matrix() const { return m_matrix; }
private:
    void _update_matrix() {
        const glm::vec3 world_upvec = { 0.0f, 1.0f, 0.0f };

        glm::vec3 forward = {
            std::sin(m_yaw),
            0.0f,
            -std::cos(m_yaw)
        };
        forward = glm::normalize(forward);
        m_right = glm::normalize(glm::cross(forward, world_upvec));

        glm::mat4 pitch_rotmat = glm::rotate(glm::mat4(1.0f), m_pitch, m_right);
        m_target = glm::normalize(glm::vec3(pitch_rotmat * glm::vec4(forward, 0.0f)));

        m_up = glm::normalize(glm::cross(m_right, m_target));

        m_matrix = glm::lookAt(m_position, m_position + m_target, m_up);
    }
};

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);
    }
};

enum class ProjectionType {
    Perspective,
    Ortho,
};

class ProjectionMatrix3D final {
private:
    glm::uvec2 m_frustrum_size{ /* 0 */ 1280, /* 0 */ 720 };
    float m_near = 0.1f;
    float m_far = 1000.0f;
private:
    float m_fov{ glm::radians(50.0f) };
private:
    ProjectionType m_projection_type = ProjectionType::Perspective;
private:
    glm::mat4 m_matrix{ 1.0f };
public:
    ProjectionMatrix3D() {
        this->_update_matrix();
    }
    ProjectionMatrix3D(const glm::uvec2& frustrum_size, const float& near, const float& far, const float& fov) 
        : m_frustrum_size(frustrum_size),
        m_near(near),
        m_far(far),
        m_fov(fov)
    {
        this->_update_matrix();
    }
    ~ProjectionMatrix3D() = default;
public:
    void set_projection_type(const ProjectionType& type) {
        const auto last_type = m_projection_type;
        m_projection_type = type;
        if (last_type != m_projection_type) {
            this->_update_matrix();
        }
    }
    void set_frustrum_size(const glm::uvec2& value){
        m_frustrum_size = value;

        this->_update_matrix();
    }
    void set_near(const float& value) {
        assert(value != 0.0f);
        m_near = value;
        this->_update_matrix();
    }
    void set_far(const float& value) {
        m_far = value;
        this->_update_matrix();
    }
    void set_fov(const float& value) {
        m_fov = value;

        this->_update_matrix();
    }
public:
    const ProjectionType& get_projection_type() const { return m_projection_type; }
    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; }
    const float& get_fov() const { return m_fov; }
public:
    const glm::mat4& get_matrix() const { return m_matrix; }
private:
    void _update_matrix() {
        if (m_projection_type == ProjectionType::Perspective) {
            assert(m_near > 0.0f);
            assert(m_far > 0.0f);
            m_matrix = glm::perspective(m_fov, float(m_frustrum_size.x) / float(m_frustrum_size.y), m_near, m_far);
        }
        else {
            float width_half = (float(m_frustrum_size.x) / 2.0f);
            float height_half = (float(m_frustrum_size.y) / 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, "Going 3D", nullptr, nullptr);

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

    // 정점 데이터 (vec3 position + vec2 uv)
    BufferData vertices_data{}; {
        // Front (+Z)
        vertices_data.add_vec3({ -0.5f,  0.5f,  0.5f }); vertices_data.add_vec2({ 0.0f, 1.0f });
        vertices_data.add_vec3({ 0.5f,  0.5f,  0.5f }); vertices_data.add_vec2({ 1.0f, 1.0f });
        vertices_data.add_vec3({ 0.5f, -0.5f,  0.5f }); vertices_data.add_vec2({ 1.0f, 0.0f });
        vertices_data.add_vec3({ -0.5f, -0.5f,  0.5f }); vertices_data.add_vec2({ 0.0f, 0.0f });

        // Back (-Z)
        vertices_data.add_vec3({ 0.5f,  0.5f, -0.5f }); vertices_data.add_vec2({ 0.0f, 1.0f });
        vertices_data.add_vec3({ -0.5f,  0.5f, -0.5f }); vertices_data.add_vec2({ 1.0f, 1.0f });
        vertices_data.add_vec3({ -0.5f, -0.5f, -0.5f }); vertices_data.add_vec2({ 1.0f, 0.0f });
        vertices_data.add_vec3({ 0.5f, -0.5f, -0.5f }); vertices_data.add_vec2({ 0.0f, 0.0f });

        // Left (-X)
        vertices_data.add_vec3({ -0.5f,  0.5f, -0.5f }); vertices_data.add_vec2({ 0.0f, 1.0f });
        vertices_data.add_vec3({ -0.5f,  0.5f,  0.5f }); vertices_data.add_vec2({ 1.0f, 1.0f });
        vertices_data.add_vec3({ -0.5f, -0.5f,  0.5f }); vertices_data.add_vec2({ 1.0f, 0.0f });
        vertices_data.add_vec3({ -0.5f, -0.5f, -0.5f }); vertices_data.add_vec2({ 0.0f, 0.0f });

        // Right (+X)
        vertices_data.add_vec3({ 0.5f,  0.5f,  0.5f }); vertices_data.add_vec2({ 0.0f, 1.0f });
        vertices_data.add_vec3({ 0.5f,  0.5f, -0.5f }); vertices_data.add_vec2({ 1.0f, 1.0f });
        vertices_data.add_vec3({ 0.5f, -0.5f, -0.5f }); vertices_data.add_vec2({ 1.0f, 0.0f });
        vertices_data.add_vec3({ 0.5f, -0.5f,  0.5f }); vertices_data.add_vec2({ 0.0f, 0.0f });

        // Top (+Y)
        vertices_data.add_vec3({ -0.5f, 0.5f, -0.5f }); vertices_data.add_vec2({ 0.0f, 1.0f });
        vertices_data.add_vec3({ 0.5f, 0.5f, -0.5f }); vertices_data.add_vec2({ 1.0f, 1.0f });
        vertices_data.add_vec3({ 0.5f, 0.5f,  0.5f }); vertices_data.add_vec2({ 1.0f, 0.0f });
        vertices_data.add_vec3({ -0.5f, 0.5f,  0.5f }); vertices_data.add_vec2({ 0.0f, 0.0f });

        // Bottom (-Y)
        vertices_data.add_vec3({ -0.5f, -0.5f,  0.5f }); vertices_data.add_vec2({ 0.0f, 1.0f });
        vertices_data.add_vec3({ 0.5f, -0.5f,  0.5f }); vertices_data.add_vec2({ 1.0f, 1.0f });
        vertices_data.add_vec3({ 0.5f, -0.5f, -0.5f }); vertices_data.add_vec2({ 1.0f, 0.0f });
        vertices_data.add_vec3({ -0.5f, -0.5f, -0.5f }); vertices_data.add_vec2({ 0.0f, 0.0f });
    }

    // 인덱스 데이터 (각 면 CCW)
    BufferData indices_data{}; {
        for (uint32_t i = 0; i < 6; ++i) {
            uint32_t base = i * 4;

            indices_data.add_uint32(base + 0);
            indices_data.add_uint32(base + 3);
            indices_data.add_uint32(base + 1);

            indices_data.add_uint32(base + 1);
            indices_data.add_uint32(base + 3);
            indices_data.add_uint32(base + 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, 3);
        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::Vec3f);
    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("C:/cat.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 });

    ProjectionMatrix3D proj_mat{ {1280, 720}, 0.1f, 1000.0f, glm::radians(45.0f) };
    ViewMatrix3D view_mat{};
    view_mat.set_position({ 0.0f, 0.0f, 100.0f });
    Transform3D world_mat{};
    world_mat.set_position({ 0.0f, 0.0f, 0.0f });

    while (glfwWindowShouldClose(window) == false) {
        glfwPollEvents();
        {
            // 카메라
            float speed = 2.0f;
            if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) {
                view_mat.set_position(view_mat.get_position() - glm::vec3(speed, 0.0f, 0.0f));
            }
            if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) {
                view_mat.set_position(view_mat.get_position() + glm::vec3(speed, 0.0f, 0.0f));
            }
            if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) {
                view_mat.set_position(view_mat.get_position() - glm::vec3(0.0f, 0.0f, speed));
            }
            if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) {
                view_mat.set_position(view_mat.get_position() + glm::vec3(0.0f, 0.0f, speed));
            }

            if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS) {
                view_mat.add_yaw(-0.01f);
            }
            if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS) {
                view_mat.add_yaw(0.01f);
            }
            if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS) {
                view_mat.add_pitch(0.01f);
            }
            if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS) {
                view_mat.add_pitch(-0.01f);
            }
        }
        {
            world_mat.set_rotation(world_mat.get_rotation() + glm::vec3(0.0f, 0.01f, 0.0f));
        }
        {
            // 화면 초기화 색상을 초록색으로 정하고, 컬러 버퍼와 깊이 버퍼를 초기화합니다.
            glClearColor(0.2f, 0.3f, 0.1f, 1.0f);
            glClearDepth(1.0f);   // 깊이 버퍼 초기화 값을 1(가장 큰 뎁스)로.
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

            glEnable(GL_DEPTH_TEST); // 뎁스 테스트 활성화
            glDepthFunc(GL_LESS); // 새 픽셀의 뎁스가 기존 뎁스보다 작을 경우 (더 앞에 있을 경우) 통과
            glDepthMask(GL_TRUE); // 뎁스 테스트 이후, 뎁스 쓰기(갱신)를 활성화

            glEnable(GL_CULL_FACE);  // 백페이스 컬링 활성화
            glFrontFace(GL_CCW); // 삼각형을 CCW 방향으로 묶은 면이 앞면
            glCullFace(GL_BACK); // 뒷면을 컬링


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

            program.upload_uniform_vec3f("uSize", { 30.0f, 30.0f, 30.0f });
            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, 36, GL_UNSIGNED_INT, 0);
        }
        glfwSwapBuffers(window);
    }

    glfwDestroyWindow(window);

    glfwTerminate();
}