找回密码
 立即注册
首页 业界区 业界 【OpenGL ES】在Windows上手撕一个mini版的渲染框架 ...

【OpenGL ES】在Windows上手撕一个mini版的渲染框架

卢莹洁 前天 11:20
1 前言

1.1 开发该框架的动机

​    OpenGL ES 是一个渲染指令接口集合,每渲染一帧图像都是一系列渲染指令的排列组合。常用的渲染指令约有 70 个,记住这些渲染指令及其排列组合方式,是一件痛苦的事情。另外,在图形开发中,经常因为功耗、丢帧等问题需要性能优化,如何从框架层面进行性能优化是一件有挑战的问题。
​    基于上述原因,笔者手撕了一个 nimi 版的渲染框架,将这些常用的渲染指令有条理地封装、组织、归类,方便愉快并高效地进行 OpenGL ES 渲染开发。笔者在 OpenGL ES 领域从业也有些时日,对现有碎片化的知识进行归纳凝练,形成系统的认知,是件势在必行的事。
1.2 一个 mini 版的渲染框架应该具备哪些能力

​    一个 mini 版的渲染框架需要对 OpenGL ES 的常用指令进行归类(如下图),封装 EGL、error check、Shader Program、Mesh、VAO、VBO、IBO、Texture、FBO 等类,方便开发者快速开发渲染程序,将更多的注意力聚焦在业务上,而不是如何去组织 OpenGL ES 指令上。
1.png

1.3 为什么强调 mini 版渲染框架

​    从渲染指令的角度来看,OpenGL ES 3.0 约有 300 个渲染指令,本文框架只封装其中最常用的 70 个,指令覆盖程度仍有较大提升空间。
​    从功能的角度来看,笔者深知一个成熟完备的渲染框架应该具备相机、光源、光照模型(Lambert、Phong、PBR 等)、阴影、射线拾取、重力、碰撞检测、粒子系统等功能。
​    鉴于上述原因,笔者审慎地保留了 "mini" 前缀。
1.4 本框架的优势

​    本框架具有以下优势。

  • 封装友好:对常用的 EGL 和 GL 指令(约 70 个)进行封装,提供了 EGL 环境搭建、着色器程序生成、网格构建、纹理贴图、离屏渲染、异常检测等基础能力,方便开发者快速开发渲染程序,将精力从繁杂的渲染指令中解放出来,将更多的注意力聚焦到业务上。
  • 代码规整:框架中多处设计了 bind 和 unbind 接口,用于绑定和解绑 OpenGL ES 状态机相关 “插槽”,如:VBO、IBO、VAO 中都设计了 bind 和 unbind 接口,ShaderProgram、Texture、FBO、TextureAction 中都设计了 bind 接口;另外,在 FBO 中设计了 begin 和 end 接口,很直观地告诉用户夹在这中间的内容将渲染到 FBO。接口规整简洁,方便用户记忆。
  • 易于扩展:定义了 TextureAction 接口,并提供 bind 函数,GLTexture、FBO 都继承了 TextureAction,用户自定义的渲染器或特效类也可以继承 TextureAction,将它们统一视为纹理活动(可绑定),这在特效叠加(或后处理)中非常有用,方便管理多渲染目标图层,易于扩展。
  • 性能高效:封装了 VBO、IBO、VAO,用于缓存顶点数据、索引、格式等信息到显存,减少 CPU 到 GPU 的数据传输,提高渲染效率;缓存了 attribute 和 uniform 变量的 location,避免 CPU 频繁向 GPU 查询 location,进一步提高渲染效率;基于 C++ 语言实现渲染框架,代码执行效率较高。
  • 跨平台:基于 C++ 语言实现,具有更好的跨平台特性;封装了 core_lib,使得平台相关头文件可以轻松替换;封装了 Application,使得平台相关 api 可以轻松替换。
  • 方便调试:设计了 EGL_CALL 和 GL_CALL 两个宏,对每个 EGL 和 GL 指令进行异常检测,方便调试渲染指令,并且通过预编译宏 DEBUG 开关动态控制是否生成异常检测的代码,Release 版本会自动屏蔽异常检测代码,避免带来额外功耗。
2 渲染框架

​    经过深思熟虑,笔者给该渲染框架命名为 glcore,命名空间也是 glcore。Windows 上 OpenGL 环境搭建主要有 GLFW / freeglut + Glad / GLEW 方案,详见 → Windows上OpenGL环境搭建,本文采用目前广泛使用的 GLFW + Glad 方案。Android 版本的 glcore 实现详见 → 在Android上手撕一个mini版的渲染框架。
​    本文完整资源(包含 glcore 框架和第 4 节的应用)详见 →【OpenGL ES】一个mini版的Windows渲染框架。
2.1 框架结构

2.png

2.2 CMakeLists

​    CMakeLists.txt
  1. # 设置库名
  2. set(LIB_GL_CORE_NAME "glcore")
  3. # 递归添加源文件列表
  4. file(GLOB_RECURSE GL_CORE_SOURCES ./src/ *.cpp)
  5. # 添加预构建库
  6. add_library(${LIB_GL_CORE_NAME} ${GL_CORE_SOURCES})
  7. # 将当前目录设为公共头文件目录 (任何链接glcore库的目标都能自动获得这个头文件路径)
  8. target_include_directories(${LIB_GL_CORE_NAME} PUBLIC ./)
复制代码
2.3 核心头文件

​    核心头文件分为对内和对外的,即内部依赖 core_lib,外部开放 core。
​    core_lib.h
  1. #pragma once
  2. /**
  3. * glcore 依赖的核心 GL 库, 便于将 glcore 移植到其他平台
  4. * Android: EGL + GLESv3
  5. * Windows: glfw / freeglut + glad / glew
  6. *
  7. * @author little fat sheep
  8. */
  9. #include <glad/glad.h>
  10. #include <GLFW/glfw3.h>
复制代码
​    之所以要单独拎出 core_lib.h,是为了方便将该框架迁移到其他平台,如 Android 上依赖的三方渲染库是 EGL + GLESv3,如果不抽出 core_lib.h,就需要将很多地方的 glfw3.h + glad.h 改为 egl.h + gl3.h ,工作量大,也容易漏改。另外,还可以很方便地替换渲染环境,如将 glfw3.h + glad.h 替换为 freeglut.h + glew.h。
​    core.h
  1. #pragma once
  2. /**
  3. * glcore核心头文件
  4. * 该头文件是留给外部使用的, glcore内部不能使用, 避免自己包含自己
  5. * @author little fat sheep
  6. */
  7. // OpenGL ES API
  8. #include "core_lib.h"
  9. // glcore 核心头文件
  10. #include "application.h"
  11. #include "elg_surface_view.h"
  12. #include "format.h"
  13. #include "frame_buffer_object.h"
  14. #include "gl_inspector.h"
  15. #include "gl_texture.h"
  16. #include "mesh.h"
  17. #include "mesh_utils.h"
  18. #include "shader_program.h"
  19. #include "texture_action.h"
  20. #include "vertex_attribute.h"
复制代码
​     core.h 只提供给外部使用,方便外部只需要包含一个头文件,就能获取 glcore 的基础能力。
2.4 Application

​    Application 主要用于管理全局环境,使用单例模式,方便获取一些全局的变量。它也是 glcore 中唯一一个依赖平台相关的接口(除日志 log 接口外),如:m_window 是 Windows 特有的,如果将 glcore 迁移到 Android 中,就需要将该变量替换为 ANativeWindow* 类型,将这些平台相关变量都集中在 Application 中,迁移平台时修改起来也比较容易,避免太分散容易漏掉。另外,还可以很方便地替换渲染环境,如渲染平台替换为 freeglut 时,需要将 GLFWwindow 替换为 void*,因为 freeglut 未提供类似 window 的数据结构。
​    application.h
  1. #pragma once
  2. #include "core_lib.h"
  3. #define app Application::getInstance()
  4. namespace glcore
  5. {
  6. /**
  7. * 应用程序, 存储全局的参数, 便于访问
  8. * @author little fat sheep
  9. */
  10. class Application {
  11. private:
  12.     static Application* sInstance;
  13. public:
  14.     int width = 0;
  15.     int height = 0;
  16.     float aspect = 1.0f;
  17. private:
  18.     GLFWwindow* m_window = nullptr;
  19. public:
  20.     static Application* getInstance();
  21.     ~Application();
  22.     void resize(int width, int height);
  23.     GLFWwindow* getWindow() { return m_window; }
  24.     void setWindow(GLFWwindow* window);
  25.     void releaseWindow();
  26. private:
  27.     Application() {};
  28. };
  29. } // namespace glcore
复制代码
​    application.cpp
  1. #include "glcore/application.h"
  2. namespace glcore
  3. {
  4. Application* Application::sInstance = nullptr;
  5. Application *Application::getInstance()
  6. {
  7.     if (sInstance == nullptr)
  8.     {
  9.         sInstance = new Application();
  10.     }
  11.     return sInstance;
  12. }
  13. Application::~Application()
  14. {
  15.    
  16. }
  17. void Application::resize(int width, int height)
  18. {
  19.     this->width = width;
  20.     this->height = height;
  21.     this->aspect = (float) width / (float) height;
  22. }
  23. void Application::setWindow(GLFWwindow* window)
  24. {
  25.     m_window = window;
  26.     int width, height;
  27.     glfwGetFramebufferSize(window, &width, &height);
  28.     resize(width, height);
  29. }
  30. void Application::releaseWindow()
  31. {
  32.     if (m_window)
  33.     {
  34.         m_window = nullptr;
  35.     }
  36. }
  37. } // namespace glcore
复制代码
2.5 GLInspector

​    GLInspector 主要用于异常信息检测,另外设计了 EGL_CALL 和 GL_CALL 两个宏,分别对 EGL 和 GL 指令进行装饰。如果定义了 DEBUG 宏,就会对每个 EGL 和 GL 指令进行异常检测,方便调试代码;如果未定义了 DEBUG 宏,就不会进行异常检测。
​    用户可以在 CMakeLists.txt 中添加预编译宏 DEBUG,这样就可以根据 Release 和 Debug 版本自动构建不同的版本。
  1. if (CMAKE_BUILD_TYPE STREQUAL "Debug")
  2.     # 添加预编译宏
  3.     add_definitions(-DDEBUG)
  4. endif ()
复制代码
​    gl_inspector.h
  1. #pragma once
  2. #include "core_lib.h"
  3. #ifdef DEBUG
  4. #define EGL_CALL(func) func;GLInspector::checkEGLError();
  5. #define GL_CALL(func) func;GLInspector::checkGLError();
  6. #else
  7. #define EGL_CALL(func) func;
  8. #define GL_CALL(func) func;
  9. #endif
  10. namespace glcore
  11. {
  12. /**
  13. * OpenGL ES命令报错监视器
  14. * @author little fat sheep
  15. */
  16. class GLInspector
  17. {
  18. public:
  19.     static void checkEGLError(const char* tag); // 检查EGL配置
  20.     static void checkEGLError(); // 通用检查EGL错误
  21.     static void printShaderInfoLog(GLuint shader, const char* tag); // 打印Shader错误日志
  22.     static void printProgramInfoLog(GLuint program, const char* tag); // 打印Program错误日志
  23.     static void checkGLError(const char* tag); // 检查GL报错信息
  24.     static void checkGLError(); // 通用检查GL错误
  25. };
  26. } // namespace glcore
复制代码
​    gl_inspector.cpp
  1. #include <iostream>
  2. #include
  3. #include <string>
  4. #include "glcore/core_lib.h"
  5. #include "glcore/gl_inspector.h"
  6. // 以下内容为了不报错临时添加的 (glfw/freeglut已经创建了egl环境)
  7. #define EGL_SUCCESS             0x3000
  8. #define EGL_NOT_INITIALIZED     0x3001
  9. #define EGL_BAD_ACCESS          0x3002
  10. #define EGL_BAD_ALLOC           0x3003
  11. #define EGL_BAD_ATTRIBUTE       0x3004
  12. #define EGL_BAD_CONFIG          0x3005
  13. #define EGL_BAD_CONTEXT         0x3006
  14. #define EGL_BAD_SURFACE         0x3007
  15. #define EGL_BAD_DISPLAY         0x3008
  16. #define EGL_BAD_CURRENT_SURFACE 0x3009
  17. #define EGL_BAD_NATIVE_PIXMAP   0x300A
  18. #define EGL_BAD_NATIVE_WINDOW   0x300D
  19. #define EGL_BAD_PARAMETER       0x300C
  20. #define EGL_BAD_MATCH           0x3010
  21. #define EGL_CONTEXT_LOST        0x300E
  22. // 以上内容为了不报错临时添加的
  23. #define TAG "GLInspector"
  24. int eglGetError() { return 0; }
  25. using namespace std;
  26. namespace glcore
  27. {
  28. void GLInspector::checkEGLError(const char *tag)
  29. {
  30.     int error = eglGetError();
  31.     if (error != EGL_SUCCESS) {
  32.         printf("%s: %s failed: 0x%x\n", TAG, tag, error);
  33.     }
  34. }
  35. void GLInspector::checkEGLError()
  36. {
  37.     GLenum errorCode = eglGetError();
  38.     if (errorCode != EGL_SUCCESS) {
  39.         string error;
  40.         switch (errorCode)
  41.         {
  42.         case EGL_BAD_DISPLAY:
  43.             error = "EGL_BAD_DISPLAY";
  44.             break;
  45.         case EGL_NOT_INITIALIZED:
  46.             error = "EGL_NOT_INITIALIZED";
  47.             break;
  48.         case EGL_BAD_CONFIG:
  49.             error = "EGL_BAD_CONFIG";
  50.             break;
  51.         case EGL_BAD_CONTEXT:
  52.             error = "EGL_BAD_CONTEXT";
  53.             break;
  54.         case EGL_BAD_NATIVE_WINDOW:
  55.             error = "EGL_BAD_NATIVE_WINDOW";
  56.             break;
  57.         case EGL_BAD_SURFACE:
  58.             error = "EGL_BAD_SURFACE";
  59.             break;
  60.         case EGL_BAD_CURRENT_SURFACE:
  61.             error = "EGL_BAD_CURRENT_SURFACE";
  62.             break;
  63.         case EGL_BAD_ACCESS:
  64.             error = "EGL_BAD_ACCESS";
  65.             break;
  66.         case EGL_BAD_ALLOC:
  67.             error = "EGL_BAD_ALLOC";
  68.             break;
  69.         case EGL_BAD_ATTRIBUTE:
  70.             error = "EGL_BAD_ATTRIBUTE";
  71.             break;
  72.         case EGL_BAD_PARAMETER:
  73.             error = "EGL_BAD_PARAMETER";
  74.             break;
  75.         case EGL_BAD_NATIVE_PIXMAP:
  76.             error = "EGL_BAD_NATIVE_PIXMAP";
  77.             break;
  78.         case EGL_BAD_MATCH:
  79.             error = "EGL_BAD_MATCH";
  80.             break;
  81.         case EGL_CONTEXT_LOST:
  82.             error = "EGL_CONTEXT_LOST";
  83.             break;
  84.         default:
  85.             error = "UNKNOW";
  86.             break;
  87.         }
  88.         printf("checkEGLError failed: %s, 0x%x", error.c_str(), errorCode);
  89.         assert(false);
  90.     }
  91. }
  92. void GLInspector::printShaderInfoLog(GLuint shader, const char* tag)
  93. {
  94.     char infoLog[512];
  95.     glGetShaderInfoLog(shader, 512, nullptr, infoLog);
  96.     printf("%s: %s failed: %s\n", TAG, tag, infoLog);
  97. }
  98. void GLInspector::printProgramInfoLog(GLuint program, const char* tag)
  99. {
  100.     char infoLog[512];
  101.     glGetProgramInfoLog(program, 512, nullptr, infoLog);
  102.     printf("%s: %s failed: %s\n", TAG, tag, infoLog);
  103. }
  104. void GLInspector::checkGLError(const char *tag) {
  105.     GLenum error = glGetError();
  106.     if(error != GL_NO_ERROR) {
  107.         printf("%s: %s failed: 0x%x\n", TAG, tag, error);
  108.     }
  109. }
  110. void GLInspector::checkGLError()
  111. {
  112.     GLenum errorCode = glGetError();
  113.     if (errorCode != GL_NO_ERROR)
  114.     {
  115.         string error;
  116.         switch (errorCode)
  117.         {
  118.         case GL_INVALID_ENUM:
  119.             error = "GL_INVALID_ENUM";
  120.             break;
  121.         case GL_INVALID_VALUE:
  122.             error = "GL_INVALID_VALUE";
  123.             break;
  124.         case GL_INVALID_OPERATION:
  125.             error = "GL_INVALID_OPERATION";
  126.             break;
  127.         case GL_INVALID_INDEX:
  128.             error = "GL_INVALID_INDEX";
  129.             break;
  130.         case GL_INVALID_FRAMEBUFFER_OPERATION:
  131.             error = "GL_INVALID_FRAMEBUFFER_OPERATION";
  132.             break;
  133.         case GL_OUT_OF_MEMORY:
  134.             error = "GL_OUT_OF_MEMORY";
  135.             break;
  136.         default:
  137.             error = "UNKNOW";
  138.             break;
  139.         }
  140.         printf("checkError failed: %s, 0x%x\n", error.c_str(), errorCode);
  141.         assert(false);
  142.     }
  143. }
  144. } // namespace glcore
复制代码
2.6 EGLSurfaceView

​    EGLSurfaceView 主要承载了 EGL 环境搭建。EGL 详细介绍见 → 【OpenGL ES】EGL+FBO离屏渲染。
​    由于 GLFW 中已经创建了 EGL 环境,EGLSurfaceView 实际上是多余的,为了保持 glcore 在各个平台上的代码具有高度一致性,并且方便随时自主创建 EGL 环境,这里仍然保留了 EGLSurfaceView。本文中主要使用到 EGLSurfaceView 的内部类 Renderer,起到定制渲染流程规范的作用。
​    elg_surface_view.h
  1. #pragma once
  2. #include "core_lib.h"
  3. // 以下内容为了不报错临时添加的 (glfw/freeglut创建了egl环境)
  4. typedef void* EGLDisplay;
  5. typedef void* EGLConfig;
  6. typedef void* EGLContext;
  7. typedef void* EGLSurface;
  8. // 以上内容为了不报错临时添加的
  9. namespace glcore
  10. {
  11. /**
  12. * EGL环境封装类
  13. * glfw和freeglut中创建了egl环境, 因此该类可以去掉,
  14. * 但是为了方便将glcore迁移到需要用户搭建egl环境的平台中,
  15. * 暂时保留该类.
  16. *
  17. * @author little fat sheep
  18. */
  19. class EGLSurfaceView
  20. {
  21. public:
  22.     class Renderer;
  23. private:
  24.     Renderer* m_renderer = nullptr;
  25.     EGLDisplay m_eglDisplay;
  26.     EGLConfig m_eglConfig;
  27.     EGLContext m_eglContext;
  28.     EGLSurface m_eglSurface;
  29.     bool m_firstCreateSurface = true;
  30. public:
  31.     EGLSurfaceView();
  32.     ~EGLSurfaceView();
  33.     void setRenderer(Renderer* renderer);
  34.     bool surfaceCreated();
  35.     void surfaceChanged(int width, int height);
  36.     void drawFrame();
  37.     void surfaceDestroy();
  38. private:
  39.     void createDisplay();
  40.     void createConfig();
  41.     void createContext();
  42.     void createSurface();
  43.     void makeCurrent();
  44. public:
  45.     /**
  46.         * 渲染器接口, 类比GLSurfaceView.Renderer
  47.         * @author little fat sheep
  48.         */
  49.     class Renderer {
  50.     public:
  51.         virtual ~Renderer() {};
  52.         virtual void onSurfaceCreated() = 0;
  53.         virtual void onSurfaceChanged(int width, int height) = 0;
  54.         virtual void onDrawFrame() = 0;
  55.     };
  56. };
  57. } // namespace glcore
复制代码
​    elg_surface_view.cpp
  1. #include <iostream>
  2. #include "glcore/application.h"
  3. #include "glcore/elg_surface_view.h"
  4. #include "glcore/gl_inspector.h"
  5. #define TAG "EGLSurfaceView"
  6. // 以下内容为了不报错临时添加的 (glfw/freeglut已经创建了egl环境)
  7. #define EGL_RED_SIZE               0x3024
  8. #define EGL_GREEN_SIZE             0x3023
  9. #define EGL_BLUE_SIZE              0x3022
  10. #define EGL_ALPHA_SIZE             0x3021
  11. #define EGL_DEPTH_SIZE             0x3025
  12. #define EGL_RENDERABLE_TYPE        0x3040
  13. #define EGL_OPENGL_ES3_BIT         0x0040
  14. #define EGL_SURFACE_TYPE           0x3033
  15. #define EGL_WINDOW_BIT             0x0004
  16. #define EGL_NONE                   0x3038
  17. #define EGL_CONTEXT_CLIENT_VERSION 0x3098
  18. #define EGL_DEFAULT_DISPLAY ((EGLDisplay)0)
  19. #define EGL_NO_DISPLAY ((EGLDisplay)0)
  20. #define EGL_NO_CONTEXT ((EGLContext)0)
  21. #define EGL_NO_SURFACE ((EGLSurface)0)
  22. typedef int32_t EGLint;
  23. EGLDisplay eglGetDisplay(EGLDisplay a1) { return nullptr; }
  24. void eglInitialize(EGLDisplay a1, int* a3, int* a4) {}
  25. void eglChooseConfig(EGLDisplay a1, const EGLint* a2, EGLConfig* a3, EGLint a4, EGLint* a5) {}
  26. EGLContext eglCreateContext(EGLDisplay a1, EGLConfig a2, EGLContext a3, const EGLint* a4) { return nullptr; }
  27. EGLSurface eglCreateWindowSurface(EGLDisplay a1, EGLConfig a2, void* a3, const EGLint* a4) { return nullptr; }
  28. void eglMakeCurrent(EGLDisplay a1, EGLSurface a2, EGLSurface a3, EGLContext a4) {}
  29. void eglSwapBuffers(EGLDisplay a1, EGLSurface a2) {}
  30. void eglDestroySurface(EGLDisplay a1, EGLSurface a2) {}
  31. void eglDestroyContext(EGLDisplay a1, EGLContext a2) {}
  32. void eglTerminate(EGLDisplay a1) {}
  33. // 以上内容为了不报错临时添加的
  34. namespace glcore
  35. {
  36. EGLSurfaceView::EGLSurfaceView()
  37. {
  38.     printf("%s: init\n", TAG);
  39.     createDisplay();
  40.     createConfig();
  41.     createContext();
  42. }
  43. EGLSurfaceView::~EGLSurfaceView()
  44. {
  45.     printf("%s: destroy\n", TAG);
  46.     if (m_renderer)
  47.     {
  48.         delete m_renderer;
  49.         m_renderer = nullptr;
  50.     }
  51.     if (m_eglDisplay && m_eglDisplay != EGL_NO_DISPLAY)
  52.     {
  53.         // 与显示设备解绑
  54.         EGL_CALL(eglMakeCurrent(m_eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT));
  55.         // 销毁 EGLSurface
  56.         if (m_eglSurface && m_eglSurface != EGL_NO_SURFACE)
  57.         {
  58.             EGL_CALL(eglDestroySurface(m_eglDisplay, m_eglSurface));
  59.             delete &m_eglSurface;
  60.         }
  61.         // 销毁 EGLContext
  62.         if (m_eglContext && m_eglContext != EGL_NO_CONTEXT)
  63.         {
  64.             EGL_CALL(eglDestroyContext(m_eglDisplay, m_eglContext));
  65.             delete &m_eglContext;
  66.         }
  67.         // 销毁 EGLDisplay (显示设备)
  68.         EGL_CALL(eglTerminate(m_eglDisplay));
  69.         delete &m_eglDisplay;
  70.     }
  71.     app->releaseWindow();
  72.     delete app;
  73. }
  74. void EGLSurfaceView::setRenderer(Renderer *renderer)
  75. {
  76.     printf("%s: setRenderer\n", TAG);
  77.     m_renderer = renderer;
  78. }
  79. bool EGLSurfaceView::surfaceCreated()
  80. {
  81.     printf("%s: surfaceCreated\n", TAG);
  82.     app->resize(app->width, app->height);
  83.     createSurface();
  84.     makeCurrent();
  85.     if (m_renderer && m_firstCreateSurface)
  86.     {
  87.         m_renderer->onSurfaceCreated();
  88.         m_firstCreateSurface = false;
  89.     }
  90.     return true;
  91. }
  92. void EGLSurfaceView::surfaceChanged(int width, int height)
  93. {
  94.     printf("%s: surfaceChanged, width: %d, height: %d\n", TAG, width, height);
  95.     app->resize(width, height);
  96.     if (m_renderer)
  97.     {
  98.         m_renderer->onSurfaceChanged(width, height);
  99.     }
  100. }
  101. void EGLSurfaceView::drawFrame()
  102. {
  103.     if (!m_eglSurface || m_eglSurface == EGL_NO_SURFACE || !m_renderer)
  104.     {
  105.         return;
  106.     }
  107.     m_renderer->onDrawFrame();
  108.     EGL_CALL(eglSwapBuffers(m_eglDisplay, m_eglSurface));
  109. }
  110. void EGLSurfaceView::surfaceDestroy()
  111. {
  112.     printf("%s: surfaceDestroy\n", TAG);
  113.     if (m_eglDisplay && m_eglDisplay != EGL_NO_DISPLAY)
  114.     {
  115.         // 与显示设备解绑
  116.         EGL_CALL(eglMakeCurrent(m_eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT));
  117.         // 销毁 EGLSurface
  118.         if (m_eglSurface && m_eglSurface != EGL_NO_SURFACE)
  119.         {
  120.             EGL_CALL(eglDestroySurface(m_eglDisplay, m_eglSurface));
  121.             m_eglSurface = nullptr;
  122.         }
  123.     }
  124.     app->releaseWindow();
  125. }
  126. // 1.创建EGLDisplay
  127. void EGLSurfaceView::createDisplay()
  128. {
  129.     EGL_CALL(m_eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY));
  130.     EGL_CALL(eglInitialize(m_eglDisplay, nullptr, nullptr));
  131. }
  132. // 2.创建EGLConfig
  133. void EGLSurfaceView::createConfig()
  134. {
  135.     if (m_eglDisplay && m_eglDisplay != EGL_NO_DISPLAY)
  136.     {
  137.         const EGLint configAttrs[] = {
  138.                 EGL_RED_SIZE, 8,
  139.                 EGL_GREEN_SIZE, 8,
  140.                 EGL_BLUE_SIZE, 8,
  141.                 EGL_ALPHA_SIZE, 8,
  142.                 EGL_DEPTH_SIZE, 8,
  143.                 EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT,
  144.                 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
  145.                 EGL_NONE
  146.         };
  147.         EGLint numConfigs;
  148.         EGL_CALL(eglChooseConfig(m_eglDisplay, configAttrs, &m_eglConfig, 1, &numConfigs));
  149.     }
  150. }
  151. // 3.创建EGLContext
  152. void EGLSurfaceView::createContext()
  153. {
  154.     if (m_eglConfig)
  155.     {
  156.         const EGLint contextAttrs[] = {
  157.                 EGL_CONTEXT_CLIENT_VERSION, 3,
  158.                 EGL_NONE
  159.         };
  160.         EGL_CALL(m_eglContext = eglCreateContext(m_eglDisplay, m_eglConfig, EGL_NO_CONTEXT, contextAttrs));
  161.     }
  162. }
  163. // 4.创建EGLSurface
  164. void EGLSurfaceView::createSurface()
  165. {
  166.     if (m_eglContext && m_eglContext != EGL_NO_CONTEXT) {
  167.         EGL_CALL(m_eglSurface = eglCreateWindowSurface(m_eglDisplay, m_eglConfig, app->getWindow(), nullptr));
  168.     }
  169. }
  170. // 5.绑定EGLSurface和EGLContext到显示设备(EGLDisplay)
  171. void EGLSurfaceView::makeCurrent()
  172. {
  173.     if (m_eglSurface && m_eglSurface != EGL_NO_SURFACE)
  174.     {
  175.         EGL_CALL(eglMakeCurrent(m_eglDisplay, m_eglSurface, m_eglSurface, m_eglContext));
  176.     }
  177. }
  178. } // namespace glcore
复制代码
2.7 ShaderProgram

​    ShaderProgram 主要用于编译 Shader、链接 Program、设置 attribute 属性、更新 uniform 属性。
​    glGetAttribLocation、glGetUniformLocation 两个接口需要 CPU 向 GPU 查询 location 信息,并且会频繁调用,为提高性能,笔者设计了 m_attributes 和 m_uniforms 两个 map 存储 name 到 location 的映射,方便快速获取 location,避免 CPU 频繁与 GPU 交互,以提高渲染性能。
​    shader_program.h
  1. #pragma once
  2. #include <map>
  3. #include "core_lib.h"
  4. using namespace std;
  5. namespace glcore
  6. {
  7. /**
  8. * 着色器程序
  9. * @author little fat sheep
  10. */
  11. class ShaderProgram
  12. {
  13. public:
  14.     static constexpr char* ATTRIBUTE_POSITION = "a_position"; // 着色器中位置属性名
  15.     static constexpr char* ATTRIBUTE_NORMAL = "a_normal"; // 着色器中位法线性名
  16.     static constexpr char* ATTRIBUTE_COLOR = "a_color"; // 着色器中颜色属性名
  17.     static constexpr char* ATTRIBUTE_TEXCOORD = "a_texCoord"; // 着色器中纹理坐标属性名
  18.     static constexpr char* ATTRIBUTE_TANGENT = "a_tangent"; // 着色器中切线属性名
  19.     static constexpr char* ATTRIBUTE_BINORMAL = "a_binormal"; // 着色器中副切线属性名
  20.     static constexpr char* UNIFORM_TEXTURE = "u_texture"; // 着色器中纹理名
  21.     static constexpr char* UNIFORM_VP = "u_projectionViewMatrix"; // 着色器中VP名
  22. private:
  23.     GLuint m_program;
  24.     map<const char*, int> m_attributes;
  25.     map<const char*, int> m_uniforms;
  26. public:
  27.     ShaderProgram(const char* vertexCode, const char* fragmentCode);
  28.     ~ShaderProgram();
  29.     void bind();
  30.     GLuint getHandle() { return m_program; }
  31.     // 操作attribute属性
  32.     void enableVertexAttribArray(const char* name);
  33.     void enableVertexAttribArray(int location);
  34.     void setVertexAttribPointer(const char* name, int size, int type, bool normalize, int stride, int offset);
  35.     void setVertexAttribPointer(int location, int size, int type, bool normalize, int stride, int offset);
  36.     void disableVertexAttribArray(const char* name);
  37.     void disableVertexAttribArray(int location);
  38.     // 操作uniform属性
  39.     void setUniformi(const char* name, int value);
  40.     void setUniformi(int location, int value);
  41.     void setUniformi(const char* name, int value1, int value2);
  42.     void setUniformi(int location, int value1, int value2);
  43.     void setUniformi(const char* name, int value1, int value2, int value3);
  44.     void setUniformi(int location, int value1, int value2, int value3);
  45.     void setUniformi(const char* name, int value1, int value2, int value3, int value4);
  46.     void setUniformi(int location, int value1, int value2, int value3, int value4);
  47.     void setUniformf(const char* name, float value);
  48.     void setUniformf(int location, float value);
  49.     void setUniformf(const char* name, float value1, float value2);
  50.     void setUniformf(int location, float value1, float value2);
  51.     void setUniformf(const char* name, float value1, float value2, int value3);
  52.     void setUniformf(int location, float value1, float value2, int value3);
  53.     void setUniformf(const char* name, float value1, float value2, int value3, int value4);
  54.     void setUniformf(int location, float value1, float value2, int value3, int value4);
  55.     void setUniform1fv(const char* name, int length, const float values[]);
  56.     void setUniform1fv(int location, int count, float const values[]);
  57.     void setUniform2fv(const char* name, int count, const float values[]);
  58.     void setUniform2fv(int location, int count, const float values[]);
  59.     void setUniform3fv(const char* name, int count, const float values[]);
  60.     void setUniform3fv(int location, int count, const float values[]);
  61.     void setUniform4fv(const char* name, int count, const float values[]);
  62.     void setUniform4fv(int location, int count, const float values[]);
  63.     void setUniformMatrix2fv(const char* name, int count, bool transpose, const float *value);
  64.     void setUniformMatrix2fv(int location, int count, bool transpose, const float *value);
  65.     void setUniformMatrix3fv(const char* name, int count, bool transpose, const float *value);
  66.     void setUniformMatrix3fv(int location, int count, bool transpose, const float *value);
  67.     void setUniformMatrix4fv(const char* name, int count, bool transpose, const float *value);
  68.     void setUniformMatrix4fv(int location, int count, bool transpose, const float *value);
  69.     int fetchAttributeLocation(const char* name);
  70.     int fetchUniformLocation(const char* name);
  71. private:
  72.     void compileShaders(const char* vertexCode, const char* fragmentCode);
  73.     GLuint loadShader(GLenum type, const char* source);
  74.     GLuint linkProgram(GLuint vertexShader, GLuint fragmentShader);
  75. };
  76. } // namespace glcore
复制代码
​    shader_program.cpp
  1. #include <iostream>
  2. #include "glcore/gl_inspector.h"
  3. #include "glcore/shader_program.h"
  4. #define TAG "ShaderProgram"
  5. namespace glcore
  6. {
  7. ShaderProgram::ShaderProgram(const char* vertexCode, const char* fragmentCode)
  8. {
  9.     compileShaders(vertexCode, fragmentCode);
  10. }
  11. ShaderProgram::~ShaderProgram()
  12. {
  13.     if (m_program)
  14.     {
  15.         GL_CALL(glUseProgram(0));
  16.         GL_CALL(glDeleteProgram(m_program));
  17.         m_program = 0;
  18.     }
  19.     m_attributes.clear();
  20.     m_uniforms.clear();
  21. }
  22. void ShaderProgram::bind()
  23. {
  24.     GL_CALL(glUseProgram(m_program));
  25. }
  26. void ShaderProgram::enableVertexAttribArray(const char* name)
  27. {
  28.     int location = fetchAttributeLocation(name);
  29.     enableVertexAttribArray(location);
  30. }
  31. void ShaderProgram::enableVertexAttribArray(int location)
  32. {
  33.     GL_CALL(glEnableVertexAttribArray(location));
  34. }
  35. void ShaderProgram::setVertexAttribPointer(const char *name, int size, int type, bool normalize, int stride, int offset)
  36. {
  37.     int location = fetchAttributeLocation(name);
  38.     setVertexAttribPointer(location, size, type, normalize, stride, offset);
  39. }
  40. void ShaderProgram::setVertexAttribPointer(int location, int size, int type, bool normalize, int stride, int offset)
  41. {
  42.     GL_CALL(glVertexAttribPointer(location, size, type, normalize, stride, (void*) offset));
  43. }
  44. void ShaderProgram::disableVertexAttribArray(const char* name)
  45. {
  46.     int location = fetchAttributeLocation(name);
  47.     disableVertexAttribArray(location);
  48. }
  49. void ShaderProgram::disableVertexAttribArray(int location)
  50. {
  51.     GL_CALL(glDisableVertexAttribArray(location));
  52. }
  53. void ShaderProgram::setUniformi(const char* name, int value)
  54. {
  55.     int location = fetchUniformLocation(name);
  56.     GL_CALL(glUniform1i(location, value));
  57. }
  58. void ShaderProgram::setUniformi(int location, int value)
  59. {
  60.     GL_CALL(glUniform1i(location, value));
  61. }
  62. void ShaderProgram::setUniformi(const char* name, int value1, int value2)
  63. {
  64.     int location = fetchUniformLocation(name);
  65.     GL_CALL(glUniform2i(location, value1, value2));
  66. }
  67. void ShaderProgram::setUniformi(int location, int value1, int value2)
  68. {
  69.     GL_CALL(glUniform2i(location, value1, value2));
  70. }
  71. void ShaderProgram::setUniformi(const char* name, int value1, int value2, int value3)
  72. {
  73.     int location = fetchUniformLocation(name);
  74.     GL_CALL(glUniform3i(location, value1, value2, value3));
  75. }
  76. void ShaderProgram::setUniformi(int location, int value1, int value2, int value3)
  77. {
  78.     GL_CALL(glUniform3i(location, value1, value2, value3));
  79. }
  80. void ShaderProgram::setUniformi(const char* name, int value1, int value2, int value3, int value4)
  81. {
  82.     int location = fetchUniformLocation(name);
  83.     GL_CALL(glUniform4i(location, value1, value2, value3, value4));
  84. }
  85. void ShaderProgram::setUniformi(int location, int value1, int value2, int value3, int value4)
  86. {
  87.     GL_CALL(glUniform4i(location, value1, value2, value3, value4));
  88. }
  89. void ShaderProgram::setUniformf(const char* name, float value)
  90. {
  91.     int location = fetchUniformLocation(name);
  92.     GL_CALL(glUniform1f(location, value));
  93. }
  94. void ShaderProgram::setUniformf(int location, float value)
  95. {
  96.     GL_CALL(glUniform1f(location, value));
  97. }
  98. void ShaderProgram::setUniformf(const char* name, float value1, float value2)
  99. {
  100.     int location = fetchUniformLocation(name);
  101.     GL_CALL(glUniform2f(location, value1, value2));
  102. }
  103. void ShaderProgram::setUniformf(int location, float value1, float value2)
  104. {
  105.     GL_CALL(glUniform2f(location, value1, value2));
  106. }
  107. void ShaderProgram::setUniformf(const char* name, float value1, float value2, int value3)
  108. {
  109.     int location = fetchUniformLocation(name);
  110.     GL_CALL(glUniform3f(location, value1, value2, value3));
  111. }
  112. void ShaderProgram::setUniformf(int location, float value1, float value2, int value3)
  113. {
  114.     GL_CALL(glUniform3f(location, value1, value2, value3));
  115. }
  116. void ShaderProgram::setUniformf(const char* name, float value1, float value2, int value3, int value4)
  117. {
  118.     int location = fetchUniformLocation(name);
  119.     GL_CALL(glUniform4f(location, value1, value2, value3, value4));
  120. }
  121. void ShaderProgram::setUniformf(int location, float value1, float value2, int value3, int value4)
  122. {
  123.     GL_CALL(glUniform4f(location, value1, value2, value3, value4));
  124. }
  125. void ShaderProgram::setUniform1fv(const char* name, int count, const float values[])
  126. {
  127.     int location = fetchUniformLocation(name);
  128.     GL_CALL(glUniform1fv(location, count, values));
  129. }
  130. void ShaderProgram::setUniform1fv(int location, int count, const float values[])
  131. {
  132.     GL_CALL(glUniform1fv(location, count, values));
  133. }
  134. void ShaderProgram::setUniform2fv(const char* name, int count, const float values[])
  135. {
  136.     int location = fetchUniformLocation(name);
  137.     GL_CALL(glUniform2fv(location, count / 2, values));
  138. }
  139. void ShaderProgram::setUniform2fv(int location, int count, const float values[])
  140. {
  141.     GL_CALL(glUniform2fv(location, count / 2, values));
  142. }
  143. void ShaderProgram::setUniform3fv(const char* name, int count, const float values[])
  144. {
  145.     int location = fetchUniformLocation(name);
  146.     GL_CALL(glUniform3fv(location, count / 3, values));
  147. }
  148. void ShaderProgram::setUniform3fv(int location, int count, const float values[])
  149. {
  150.     GL_CALL(glUniform3fv(location, count / 3, values));
  151. }
  152. void ShaderProgram::setUniform4fv(const char* name, int count, const float values[])
  153. {
  154.     int location = fetchUniformLocation(name);
  155.     GL_CALL(glUniform4fv(location, count / 4, values));
  156. }
  157. void ShaderProgram::setUniform4fv(int location, int count, const float values[])
  158. {
  159.     GL_CALL(glUniform4fv(location, count / 4, values));
  160. }
  161. void ShaderProgram::setUniformMatrix2fv(const char* name, int count, bool transpose, const float *value)
  162. {
  163.     int location = fetchUniformLocation(name);
  164.     GL_CALL(glUniformMatrix2fv(location, count, transpose, value));
  165. }
  166. void ShaderProgram::setUniformMatrix2fv(int location, int count, bool transpose, const float *value)
  167. {
  168.     GL_CALL(glUniformMatrix2fv(location, count, transpose, value));
  169. }
  170. void ShaderProgram::setUniformMatrix3fv(const char* name, int count, bool transpose, const float *value)
  171. {
  172.     int location = fetchUniformLocation(name);
  173.     GL_CALL(glUniformMatrix3fv(location, count, transpose, value));
  174. }
  175. void ShaderProgram::setUniformMatrix3fv(int location, int count, bool transpose, const float *value)
  176. {
  177.     GL_CALL(glUniformMatrix3fv(location, count, transpose, value));
  178. }
  179. void ShaderProgram::setUniformMatrix4fv(const char* name, int count, bool transpose, const float *value)
  180. {
  181.     int location = fetchUniformLocation(name);
  182.     GL_CALL(glUniformMatrix4fv(location, count, transpose, value));
  183. }
  184. void ShaderProgram::setUniformMatrix4fv(int location, int count, bool transpose, const float *value)
  185. {
  186.     GL_CALL(glUniformMatrix4fv(location, count, transpose, value));
  187. }
  188. int ShaderProgram::fetchAttributeLocation(const char* name)
  189. {
  190.     int location;
  191.     auto it = m_attributes.find(name);
  192.     if (it == m_attributes.end())
  193.     {
  194.         GL_CALL(location = glGetAttribLocation(m_program, name));
  195.         if (location == -1) {
  196.             printf("%s: no attribute: %s\n", TAG, name);
  197.             //GLInspector::printProgramInfoLog(m_program, "fetchAttributeLocation");
  198.             return -1;
  199.         }
  200.         m_attributes[name] = location;
  201.     }
  202.     else
  203.     {
  204.         location = it->second;
  205.     }
  206.     return location;
  207. }
  208. int ShaderProgram::fetchUniformLocation(const char* name)
  209. {
  210.     int location;
  211.     auto it = m_uniforms.find(name);
  212.     if (it == m_uniforms.end())
  213.     {
  214.         GL_CALL(location = glGetUniformLocation(m_program, name));
  215.         if (location == -1) {
  216.             printf("%s: no uniform: %s\n", TAG, name);
  217.             //GLInspector::printProgramInfoLog(m_program, "fetchUniformLocation");
  218.             return -1;
  219.         }
  220.         m_uniforms[name] = location;
  221.     }
  222.     else
  223.     {
  224.         location = it->second;
  225.     }
  226.     return location;
  227. }
  228. void ShaderProgram::compileShaders(const char* vertexCode, const char* fragmentCode)
  229. {
  230.     GLuint vertexShader = loadShader(GL_VERTEX_SHADER, vertexCode);
  231.     GLuint fragmentShader = loadShader(GL_FRAGMENT_SHADER, fragmentCode);
  232.     m_program = linkProgram(vertexShader, fragmentShader);
  233. }
  234. GLuint ShaderProgram::loadShader(GLenum type, const char* source)
  235. {
  236.     GL_CALL(GLuint shader = glCreateShader(type));
  237.     GL_CALL(glShaderSource(shader, 1, &source, nullptr));
  238.     GL_CALL(glCompileShader(shader));
  239.     GLint success;
  240.     glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
  241.     if (!success) {
  242.         GLInspector::printShaderInfoLog(shader, "loadShader");
  243.         return 0;
  244.     }
  245.     return shader;
  246. }
  247. GLuint ShaderProgram::linkProgram(GLuint vertexShader, GLuint fragmentShader)
  248. {
  249.     GL_CALL(GLuint program = glCreateProgram());
  250.     GL_CALL(glAttachShader(program, vertexShader));
  251.     GL_CALL(glAttachShader(program, fragmentShader));
  252.     GL_CALL(glLinkProgram(program));
  253.     GLint success;
  254.     glGetProgramiv(program, GL_LINK_STATUS, &success);
  255.     if (!success) {
  256.         GLInspector::printProgramInfoLog(m_program, "linkProgram");
  257.     }
  258.     GL_CALL(glDeleteShader(vertexShader));
  259.     GL_CALL(glDeleteShader(fragmentShader));
  260.     return program;
  261. }
  262. } // namespace glcore
复制代码
2.8 VBO

​    VBO 是 Vertex Buffer Object 的简称,即顶点缓冲对象,作用是缓存顶点数据到显存中,避免频繁调用 glVertexAttribPointer 传输顶点数据,减少 CPU 到 GPU 的数据传输,提高渲染效率。
​    顶点属性主要有位置、颜色、纹理坐标、法线、切线、副切线等,每个属性又有属性标识、维数、是否已标准化、数据类型、偏移、别名、纹理单元等。
​    由于 VBO 中有多个属性数据,每个属性有多个字段,笔者除了封装 VertexBufferObject 类,还封装了 VertexAttributes 和 VertexAttribute 两个类。VertexAttribute 是属性描述类,VertexAttributes 是属性描述集合。
​    vertex_buffer_object.h
  1. #pragma once
  2. #include <initializer_list>
  3. #include <vector>
  4. #include "core_lib.h"
  5. #include "shader_program.h"
  6. #include "vertex_attributes.h"
  7. #include "vertex_attribute.h"
  8. #include "vertex_attributes.h"
  9. using namespace std;
  10. namespace glcore
  11. {
  12. /**
  13. * 顶点属性缓冲对象 (简称VBO)
  14. * @author little fat sheep
  15. */
  16. class VertexBufferObject
  17. {
  18. protected:
  19.     bool m_isBound = false; // 是否已绑定到VBO (或VAO)
  20.     bool m_isDirty = false; // 是否有脏数据 (缓存的数据需要更新)
  21. private:
  22.     GLuint m_vboHandle; // VBO句柄
  23.     VertexAttributes* m_attributes; // 顶点属性
  24.     GLuint m_usage; // GL_STATIC_DRAW 或 GL_DYNAMIC_DRAW
  25.     const float* m_vertices; // 顶点属性数据
  26.     int m_vertexNum = 0; // 顶点个数
  27.     int m_bytes = 0; // 顶点属性字节数
  28. public:
  29.     VertexBufferObject(bool isStatic, initializer_list<VertexAttribute*> attributes);
  30.     VertexBufferObject(bool isStatic, VertexAttributes* attributes);
  31.     virtual ~VertexBufferObject();
  32.     void setVertices(float* vertices, int bytes);
  33.     void bind(ShaderProgram* shader);
  34.     virtual void bind(ShaderProgram* shader, int* locations);
  35.     void unbind(ShaderProgram* shader);
  36.     virtual void unbind(ShaderProgram* shader, int* locations);
  37.     int getNumVertices() { return m_vertexNum; }
  38. private:
  39.     void applyBufferData(); // 缓存数据
  40. };
  41. } // namespace glcore
复制代码
​    vertex_buffer_object.cpp
  1. #include <iostream>
  2. #include "glcore/gl_inspector.h"
  3. #include "glcore/vertex_buffer_object.h"
  4. #define TAG "VertexBufferObject"
  5. namespace glcore
  6. {
  7. VertexBufferObject::VertexBufferObject(bool isStatic, initializer_list<VertexAttribute*> attributes):
  8.     VertexBufferObject(isStatic, new VertexAttributes(attributes))
  9. {
  10. }
  11. VertexBufferObject::VertexBufferObject(bool isStatic, VertexAttributes* attributes):
  12.     m_attributes(attributes)
  13. {
  14.     m_usage = isStatic ? GL_STATIC_DRAW : GL_DYNAMIC_DRAW;
  15.     GL_CALL(glGenBuffers(1, &m_vboHandle));
  16.     printf("%s: init: %d\n", TAG, m_vboHandle);
  17. }
  18. VertexBufferObject::~VertexBufferObject()
  19. {
  20.     printf("%s: destroy\n", TAG);
  21.     GL_CALL(glBindBuffer(GL_ARRAY_BUFFER, 0));
  22.     GL_CALL(glDeleteBuffers(1, &m_vboHandle));
  23.     m_vboHandle = 0;
  24.     delete m_attributes;
  25.     delete[] m_vertices;
  26. }
  27. void VertexBufferObject::setVertices(float* vertices, int bytes)
  28. {
  29.     m_vertices = vertices;
  30.     m_vertexNum = bytes / m_attributes->vertexSize;
  31.     m_bytes = bytes;
  32.     m_isDirty = true;
  33.     if (m_isBound)
  34.     {
  35.         applyBufferData();
  36.     }
  37. }
  38. void VertexBufferObject::bind(ShaderProgram* shader)
  39. {
  40.     bind(shader, nullptr);
  41. }
  42. void VertexBufferObject::bind(ShaderProgram* shader, int* locations)
  43. {
  44.     GL_CALL(glBindBuffer(GL_ARRAY_BUFFER, m_vboHandle));
  45.     if (m_isDirty)
  46.     {
  47.         applyBufferData();
  48.     }
  49.     if (locations == nullptr)
  50.     {
  51.         for (int i = 0; i < m_attributes->size(); i++)
  52.         {
  53.             VertexAttribute* attribute = m_attributes->get(i);
  54.             shader->enableVertexAttribArray(attribute->alias);
  55.             shader->setVertexAttribPointer(attribute->alias, attribute->numComponents,
  56.                attribute->type, attribute->normalized, m_attributes->vertexSize,
  57.                attribute->offset);
  58.         }
  59.     }
  60.     else
  61.     {
  62.         for (int i = 0; i < m_attributes->size(); i++)
  63.         {
  64.             VertexAttribute* attribute = m_attributes->get(i);
  65.             shader->enableVertexAttribArray(locations[i]);
  66.             shader->setVertexAttribPointer(locations[i], attribute->numComponents,
  67.                attribute->type, attribute->normalized, m_attributes->vertexSize,
  68.                attribute->offset);
  69.         }
  70.     }
  71.     m_isBound = true;
  72. }
  73. void VertexBufferObject::unbind(ShaderProgram* shader)
  74. {
  75.     unbind(shader, nullptr);
  76. }
  77. void VertexBufferObject::unbind(ShaderProgram* shader, int* locations)
  78. {
  79.     if (locations == nullptr)
  80.     {
  81.         for (int i = 0; i < m_attributes->size(); i++)
  82.         {
  83.             shader->disableVertexAttribArray(m_attributes->get(i)->alias);
  84.         }
  85.     }
  86.     else
  87.     {
  88.         for (int i = 0; i < m_attributes->size(); i++)
  89.         {
  90.             shader->disableVertexAttribArray(locations[i]);
  91.         }
  92.     }
  93.     m_isBound = false;
  94. }
  95. void VertexBufferObject::applyBufferData()
  96. {
  97.     GL_CALL(glBufferData(GL_ARRAY_BUFFER, m_bytes, m_vertices, m_usage));
  98.     m_isDirty = false;
  99. }
  100. } // namespace glcore
复制代码
​    vertex_attributes.h
  1. #pragma once
  2. #include <initializer_list>
  3. #include <vector>
  4. #include "vertex_attribute.h"
  5. using namespace std;
  6. namespace glcore
  7. {
  8. /**
  9. * 顶点属性集(位置、颜色、纹理坐标、法线、切线、副切线等中的一部分)
  10. * 每个顶点属性可以看作一个通道, 这个通道可能是多维的, 每个维度可能是多字节的
  11. * @author little fat sheep
  12. */
  13. class VertexAttributes
  14. {
  15. public:
  16.     int vertexSize; // 所有顶点属性的字节数
  17. private:
  18.     vector<VertexAttribute*> m_attributes; // 顶点属性列表
  19. public:
  20.     VertexAttributes(initializer_list<VertexAttribute*> attributes);
  21.     ~VertexAttributes();
  22.     VertexAttribute* get(int index); // 根据索引获取属性
  23.     int size(); // 获取属性个数
  24. private:
  25.     int calculateOffsets(); // 计算偏移
  26. };
  27. /**
  28. * 顶点属性标识
  29. * @author little fat sheep
  30. */
  31. class Usage {
  32. public:
  33.     static const int Position = 1;
  34.     static const int ColorUnpacked = 2;
  35.     static const int ColorPacked = 4;
  36.     static const int Normal = 8;
  37.     static const int TextureCoordinates = 16;
  38.     static const int Tangent = 32;
  39.     static const int BiNormal = 64;
  40. };
  41. } // namespace glcore
复制代码
​    vertex_attributes.cpp
  1. #include "glcore/vertex_attributes.h"
  2. namespace glcore
  3. {
  4. VertexAttributes::VertexAttributes(initializer_list<VertexAttribute*> attributes):
  5.         m_attributes(attributes)
  6. {
  7.     vertexSize = calculateOffsets();
  8. }
  9. VertexAttributes::~VertexAttributes()
  10. {
  11.     m_attributes.clear();
  12. }
  13. VertexAttribute* VertexAttributes::get(int index)
  14. {
  15.     if (index >= 0 && index < m_attributes.size())
  16.     {
  17.         return m_attributes[index];
  18.     }
  19.     return nullptr;
  20. }
  21. int VertexAttributes::size()
  22. {
  23.     return m_attributes.size();
  24. }
  25. int VertexAttributes::calculateOffsets() {
  26.     int count = 0;
  27.     for (VertexAttribute* attribute : m_attributes) {
  28.         attribute->offset = count;
  29.         count += attribute->getSizeInBytes();
  30.     }
  31.     return count;
  32. }
  33. } // namespace glcore
复制代码
​    vertex_attribute.h
  1. #pragma once
  2. namespace glcore
  3. {
  4. /**
  5. * 单个顶点属性(位置、颜色、纹理坐标、法线、切线、副切线等中的一个)
  6. * 每个顶点属性可以看作一个通道, 这个通道可能是多维的, 每个维度可能是多字节的
  7. * @author little fat sheep
  8. */
  9. class VertexAttribute
  10. {
  11. public:
  12.     int usage; // 顶点属性标识
  13.     int numComponents; // 顶点属性维数 (如顶点坐标属性是3维的, 纹理坐标是2维的)
  14.     bool normalized; // 顶点属性是否已经标准化 (有符号: -1~1, 无符号: 0~1)
  15.     int type; // 顶点属性的变量类型 (GL_FLOAT、GL_UNSIGNED_BYTE等)
  16.     int offset; // 顶点属性在字节上的偏移
  17.     const char* alias; // 顶点属性别名 (着色器中变量名)
  18.     int unit; // 纹理单元 (可能有多个纹理, 可选)
  19. public:
  20.     VertexAttribute(int usage, int numComponents, const char* alias);
  21.     VertexAttribute(int usage, int numComponents, const char* alias, int unit);
  22.     VertexAttribute(int usage, int numComponents, int type, bool normalized, const char* alias);
  23.     VertexAttribute(int usage, int numComponents, int type, bool normalized, const char* alias, int unit);
  24.     ~VertexAttribute();
  25.     static VertexAttribute* Position(); // 位置参数信息
  26.     static VertexAttribute* TexCoords(int unit); // 纹理坐标参数信息
  27.     static VertexAttribute* Normal(); // 法线参数信息
  28.     static VertexAttribute* ColorPacked(); // 颜色参数信息
  29.     static VertexAttribute* ColorUnpacked(); // 颜色参数信息
  30.     static VertexAttribute* Tangent(); // 切线参数信息
  31.     static VertexAttribute* Binormal(); // 副切线参数信息
  32.     int getSizeInBytes(); // 属性对应的字节数
  33. private:
  34.     void create(int usage, int numComponents, int type, bool normalized, const char* alias, int unit);
  35. };
  36. } // namespace glcore
复制代码
​    vertex_attribute.cpp
  1. #include <iostream>
  2. #include <string>
  3. #include "glcore/core_lib.h"
  4. #include "glcore/shader_program.h"
  5. #include "glcore/vertex_attribute.h"
  6. #include "glcore/vertex_attributes.h"
  7. #define TAG "VertexAttribute"
  8. using namespace std;
  9. namespace glcore
  10. {
  11. VertexAttribute::VertexAttribute(int usage, int numComponents, const char* alias):
  12.         VertexAttribute(usage, numComponents, alias, 0)
  13. {
  14. }
  15. VertexAttribute::VertexAttribute(int usage, int numComponents, const char* alias, int unit)
  16. {
  17.     int type = usage == Usage::ColorPacked ? GL_UNSIGNED_BYTE : GL_FLOAT;
  18.     bool normalized = usage == Usage::ColorPacked;
  19.     create(usage, numComponents, type, normalized, alias, unit);
  20. }
  21. VertexAttribute::VertexAttribute(int usage, int numComponents, int type, bool normalized, const char* alias)
  22. {
  23.     create(usage, numComponents, type, normalized, alias, 0);
  24. }
  25. VertexAttribute::VertexAttribute(int usage, int numComponents, int type, bool normalized, const char* alias, int unit)
  26. {
  27.     create(usage, numComponents, type, normalized, alias, unit);
  28. }
  29. VertexAttribute::~VertexAttribute()
  30. {
  31.     free((void*)alias);
  32. }
  33. VertexAttribute* VertexAttribute::Position() {
  34.     return new VertexAttribute(Usage::Position, 3, ShaderProgram::ATTRIBUTE_POSITION);
  35. }
  36. VertexAttribute* VertexAttribute::TexCoords(int unit) {
  37.     string str = string(ShaderProgram::ATTRIBUTE_TEXCOORD) + to_string(unit);
  38.     // 复制字符串, 避免str被回收导致悬垂指针问题, 通过free((void*)alias)释放内存
  39.     const char* combined = strdup(str.c_str());
  40.     return new VertexAttribute(Usage::TextureCoordinates, 2, combined, unit);
  41. }
  42. VertexAttribute* VertexAttribute::Normal() {
  43.     return new VertexAttribute(Usage::Normal, 3, ShaderProgram::ATTRIBUTE_NORMAL);
  44. }
  45. VertexAttribute* VertexAttribute::ColorPacked() {
  46.     return new VertexAttribute(Usage::ColorPacked, 4, GL_UNSIGNED_BYTE, true, ShaderProgram::ATTRIBUTE_COLOR);
  47. }
  48. VertexAttribute* VertexAttribute::ColorUnpacked() {
  49.     return new VertexAttribute(Usage::ColorUnpacked, 4, GL_FLOAT, false, ShaderProgram::ATTRIBUTE_COLOR);
  50. }
  51. VertexAttribute* VertexAttribute::Tangent() {
  52.     return new VertexAttribute(Usage::Tangent, 3, ShaderProgram::ATTRIBUTE_TANGENT);
  53. }
  54. VertexAttribute* VertexAttribute::Binormal() {
  55.     return new VertexAttribute(Usage::BiNormal, 3, ShaderProgram::ATTRIBUTE_BINORMAL);
  56. }
  57. int VertexAttribute::getSizeInBytes()
  58. {
  59.     switch (type) {
  60.         case GL_FLOAT:
  61.         case GL_FIXED:
  62.             return 4 * numComponents;
  63.         case GL_UNSIGNED_BYTE:
  64.         case GL_BYTE:
  65.             return numComponents;
  66.         case GL_UNSIGNED_SHORT:
  67.         case GL_SHORT:
  68.             return 2 * numComponents;
  69.     }
  70.     return 0;
  71. }
  72. void VertexAttribute::create(int usage, int numComponents, int type, bool normalized, const char* alias, int unit)
  73. {
  74.     this->usage = usage;
  75.     this->numComponents = numComponents;
  76.     this->type = type;
  77.     this->normalized = normalized;
  78.     this->alias = alias;
  79.     this->unit = unit;
  80.     printf("%s: create, alias: %s\n", TAG, alias);
  81. }
  82. } // namespace glcore
复制代码
2.9 VAO

​    VAO 是 Vertex Array Object 的简称,即顶点数组对象,作用是缓存顶点属性的指针和描述(或格式)信息,简化顶点属性设置的流程,避免频繁调用 glVertexAttribPointer 设置属性描述(或格式)信息,减少 CPU 与 GPU 的交互,提高渲染效率。
​    vertex_buffer_object_with_vao.h
  1. #pragma once
  2. #include <initializer_list>
  3. #include "core_lib.h"
  4. #include "vertex_buffer_object.h"
  5. namespace glcore
  6. {
  7. /**
  8. * 携带VAO的顶点属性缓冲对象
  9. * @author little fat sheep
  10. */
  11. class VertexBufferObjectWithVAO : public VertexBufferObject
  12. {
  13. private:
  14.     GLuint m_vaoHandle; // VAO句柄
  15. public:
  16.     VertexBufferObjectWithVAO(bool isStatic, initializer_list<VertexAttribute*> attributes);
  17.     VertexBufferObjectWithVAO(bool isStatic, VertexAttributes* attributes);
  18.     ~VertexBufferObjectWithVAO() override;
  19.     void bind(ShaderProgram* shader, int* locations) override;
  20.     void unbind(ShaderProgram* shader, int* locations) override;
  21. };
  22. } // namespace glcore
复制代码
​    vertex_buffer_object_with_vao.cpp
  1. #include <iostream>
  2. #include "glcore/gl_inspector.h"
  3. #include "glcore/vertex_buffer_object_with_vao.h"
  4. #define TAG "VertexBufferObjectWithVAO"
  5. namespace glcore
  6. {
  7. VertexBufferObjectWithVAO::VertexBufferObjectWithVAO(bool isStatic,
  8.     initializer_list<VertexAttribute*> attributes):
  9.         VertexBufferObjectWithVAO(isStatic, new VertexAttributes(attributes))
  10. {
  11. }
  12. VertexBufferObjectWithVAO::VertexBufferObjectWithVAO(bool isStatic, VertexAttributes* attributes):
  13.     VertexBufferObject(isStatic, attributes)
  14. {
  15.     GL_CALL(glGenVertexArrays(1, &m_vaoHandle));
  16.     printf("%s: init: %d\n", TAG, m_vaoHandle);
  17. }
  18. VertexBufferObjectWithVAO::~VertexBufferObjectWithVAO()
  19. {
  20.     printf("%s: destroy\n", TAG);
  21.     GL_CALL(glDeleteVertexArrays(1, &m_vaoHandle));
  22. }
  23. void VertexBufferObjectWithVAO::bind(ShaderProgram* shader, int* locations)
  24. {
  25.     GL_CALL(glBindVertexArray(m_vaoHandle));
  26.     if (m_isDirty)
  27.     {
  28.         VertexBufferObject::bind(shader, locations);
  29.     }
  30.     m_isBound = true;
  31. }
  32. void VertexBufferObjectWithVAO::unbind(ShaderProgram* shader, int* locations)
  33. {
  34.     GL_CALL(glBindVertexArray(0));
  35.     m_isBound = false;
  36. }
  37. } // namespace glcore
复制代码
2.10 IBO

​    IBO 是 Index Buffer Object 的简称,即索引缓冲对象,作用是缓存顶点索引到显存中,避免频繁调用 glDrawElements 传输顶点索引,减少 CPU 到 GPU 的数据传输,提高渲染效率。由于 IBO 绑定的是 OpenGL ES 状态机的 GL_ELEMENT_ARRAY_BUFFER “插槽”,并且对应的绘制指令又是 glDrawElements (都有 Element),因此 IBO 也被称为 EBO。
​    index_buffer_object.h
  1. #pragma once
  2. #include "core_lib.h"
  3. namespace glcore
  4. {
  5. /**
  6. * 顶点索引缓冲对象 (简称IBO)
  7. * @author little fat sheep
  8. */
  9. class IndexBufferObject
  10. {
  11. private:
  12.     GLuint m_iboHandle; // IBO句柄
  13.     GLuint m_usage; // GL_STATIC_DRAW 或 GL_DYNAMIC_DRAW
  14.     GLenum m_type = GL_UNSIGNED_SHORT; // 索引数据类型 (GL_UNSIGNED_SHORT 或 GL_UNSIGNED_INT)
  15.     const void* m_indices; // 顶点索引数据(short*或int*类型)
  16.     int m_indexNum = 0; // 索引个数
  17.     int m_bytes = 0; // 顶点索引字节数
  18.     bool m_isDirty = false; // 是否有脏数据 (缓存的数据需要更新)
  19.     bool m_isBound = false; // 是否已绑定到IBO
  20. public:
  21.     IndexBufferObject(bool isStatic);
  22.     IndexBufferObject(bool isStatic, GLenum type);
  23.     ~IndexBufferObject();
  24.     void setIndices (void* indices, int bytes);
  25.     void setIndices (void* indices, int bytes, GLenum type);
  26.     void bind();
  27.     void unbind();
  28.     int getNumIndices() { return m_indexNum; }
  29.     GLenum getType() { return m_type; }
  30. private:
  31.     void applyBufferData(); // 缓存数据
  32.     int getTypeSize(); // 获取type对应的字节数
  33. };
  34. } // namespace glcore
复制代码
​    index_buffer_object.cpp
  1. #include <iostream>
  2. #include "glcore/gl_inspector.h"
  3. #include "glcore/index_buffer_object.h"
  4. #define TAG "IndexBufferObject"
  5. namespace glcore
  6. {
  7. IndexBufferObject::IndexBufferObject(bool isStatic):
  8.         IndexBufferObject(isStatic, GL_UNSIGNED_SHORT)
  9. {
  10. }
  11. IndexBufferObject::IndexBufferObject(bool isStatic, GLenum type)
  12. {
  13.     m_usage = isStatic ? GL_STATIC_DRAW : GL_DYNAMIC_DRAW;
  14.     m_type = type;
  15.     GL_CALL(glGenBuffers(1, &m_iboHandle));
  16.     printf("%s: init: %d\n", TAG, m_iboHandle);
  17. }
  18. IndexBufferObject::~IndexBufferObject()
  19. {
  20.     printf("%s: destroy\n", TAG);
  21.     GL_CALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0));
  22.     GL_CALL(glDeleteBuffers(1, &m_iboHandle));
  23.     m_iboHandle = 0;
  24.     delete[] m_indices;
  25. }
  26. void IndexBufferObject::setIndices(void* indices, int bytes)
  27. {
  28.     setIndices(indices, bytes, m_type);
  29. }
  30. void IndexBufferObject::setIndices(void* indices, int bytes, GLenum type)
  31. {
  32.     m_indices = indices;
  33.     m_type = type;
  34.     m_indexNum = bytes > 0 ? bytes / getTypeSize() : 0;
  35.     m_bytes = bytes;
  36.     m_isDirty = true;
  37.     if (m_isBound)
  38.     {
  39.         applyBufferData();
  40.     }
  41. }
  42. void IndexBufferObject::bind()
  43. {
  44.     GL_CALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_iboHandle));
  45.     if (m_isDirty)
  46.     {
  47.         applyBufferData();
  48.     }
  49.     m_isBound = true;
  50. }
  51. void IndexBufferObject::unbind()
  52. {
  53.     GL_CALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0));
  54.     m_isBound = false;
  55. }
  56. void IndexBufferObject::applyBufferData()
  57. {
  58.     GL_CALL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_bytes, m_indices, m_usage));
  59.     //GLInspector::checkGLError("ibo: glBufferData");
  60.     m_isDirty = false;
  61. }
  62. int IndexBufferObject::getTypeSize() {
  63.     switch (m_type) {
  64.         case GL_UNSIGNED_SHORT:
  65.             return 2;
  66.         case GL_UNSIGNED_INT:
  67.             return 4;
  68.     }
  69.     return 2;
  70. }
  71. } // namespace glcore
复制代码
2.11 Mesh

​    Mesh 是网格类,用于管理顶点数据、索引、描述(或格式)等信息,由于 VBO 管理了顶点数据、IBO 管理了顶点索引、VAO 管理了顶点描述(或格式),因此 Mesh 只需管理 VBO、IBO、VAO。另外 IBO 和 VAO 是可选的,Mesh 中需要根据用户的行为调整渲染指令。
​    为方便用户快速创建平面网格,笔者提供了 MeshUtils 类,用户也可以根据该类提供的模板创建自己的网格。
​    mesh.h
  1. #pragma once
  2. #include <initializer_list>
  3. #include "core_lib.h"
  4. #include "index_buffer_object.h"
  5. #include "shader_program.h"
  6. #include "vertex_buffer_object.h"
  7. #include "vertex_attribute.h"
  8. #include "vertex_attributes.h"
  9. using namespace std;
  10. namespace glcore
  11. {
  12. /**
  13. * 网格
  14. * @author little fat sheep
  15. */
  16. class Mesh
  17. {
  18. private:
  19.     VertexBufferObject* m_vbo; // 顶点属性缓冲对象
  20.     IndexBufferObject* m_ibo; // 顶点索引缓冲对象
  21. public:
  22.     Mesh(bool isStatic, initializer_list<VertexAttribute*> attributes);
  23.     Mesh(bool isStatic, VertexAttributes* attributes);
  24.     Mesh(bool useVao, bool isStatic, initializer_list<VertexAttribute*> attributes);
  25.     Mesh(bool useVao, bool isStatic, VertexAttributes* attributes);
  26.     ~Mesh();
  27.     void setVertices(float* vertices, int bytes); // 设置顶点属性
  28.     void setIndices(void* indices, int bytes); // 设置顶点索引
  29.     void setIndices(void* indices, int bytes, GLenum type); // 设置顶点索引
  30.     void render(ShaderProgram* shader, GLenum primitiveType); // 渲染
  31. };
  32. } // namespace glcore
复制代码
​    mesh.cpp
  1. #include "glcore/gl_inspector.h"
  2. #include "glcore/mesh.h"
  3. #include "glcore/vertex_buffer_object_with_vao.h"
  4. namespace glcore
  5. {
  6. Mesh::Mesh(bool isStatic, initializer_list<VertexAttribute*> attributes):
  7.     Mesh(true, isStatic, new VertexAttributes(attributes))
  8. {
  9. }
  10. Mesh::Mesh(bool isStatic, VertexAttributes* attributes):
  11.     Mesh(true, isStatic, attributes)
  12. {
  13. }
  14. Mesh::Mesh(bool useVao, bool isStatic, initializer_list<VertexAttribute*> attributes):
  15.     Mesh(useVao, isStatic, new VertexAttributes(attributes))
  16. {
  17. }
  18. Mesh::Mesh(bool useVao, bool isStatic, VertexAttributes* attributes)
  19. {
  20.     m_vbo = useVao ? new VertexBufferObjectWithVAO(isStatic, attributes) :
  21.             new VertexBufferObject(isStatic, attributes);
  22.     m_ibo = new IndexBufferObject(isStatic);
  23. }
  24. Mesh::~Mesh()
  25. {
  26.     delete m_vbo;
  27.     delete m_ibo;
  28. }
  29. void Mesh::setVertices(float* vertices, int bytes)
  30. {
  31.     m_vbo->setVertices(vertices, bytes);
  32. }
  33. void Mesh::setIndices(void* indices, int bytes)
  34. {
  35.     m_ibo->setIndices(indices, bytes);
  36. }
  37. void Mesh::setIndices(void* indices, int bytes, GLenum type)
  38. {
  39.     m_ibo->setIndices(indices, bytes, type);
  40. }
  41. void Mesh::render(ShaderProgram* shader, GLenum primitiveType)
  42. {
  43.     m_vbo->bind(shader);
  44.     if (m_ibo->getNumIndices() > 0) {
  45.         m_ibo->bind();
  46.         GL_CALL(glDrawElements(primitiveType, m_ibo->getNumIndices(), m_ibo->getType(), nullptr));
  47.         m_ibo->unbind();
  48.     } else {
  49.         GL_CALL(glDrawArrays(primitiveType, 0, m_vbo->getNumVertices()));
  50.     }
  51.     m_vbo->unbind(shader);
  52. }
  53. } // namespace glcore
复制代码
​    mesh_utils.h
  1. #pragma once
  2. #include "mesh.h"
  3. namespace glcore
  4. {
  5. /**
  6. * 网格工具类
  7. * @author little fat sheep
  8. */
  9. class MeshUtils
  10. {
  11. public:
  12.     static Mesh* createRect(bool reverse);
  13. private:
  14.     static float* getRectVertices(bool reverse);
  15. };
  16. } // namespace glcore
复制代码
​    mesh_utils.cpp
  1. #include "glcore/mesh_utils.h"
  2. namespace glcore
  3. {
  4. Mesh* MeshUtils::createRect(bool reverse)
  5. {
  6.     Mesh* mesh = new Mesh(true, {
  7.             VertexAttribute::Position(),
  8.             VertexAttribute::TexCoords(0)
  9.     });
  10.     float* vertices = getRectVertices(reverse);
  11.     mesh->setVertices(vertices, 4 * 5 * sizeof(float));
  12.     void* indices = new short[6] { 0, 1, 2, 2, 3, 0 };
  13.     mesh->setIndices(indices, 6 * sizeof(short));
  14.     return mesh;
  15. }
  16. float* MeshUtils::getRectVertices(bool reverse)
  17. {
  18.     if (reverse) {
  19.         return new float[20] { // 中间渲染(FBO)使用
  20.                 -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, // 左下
  21.                 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, // 右下
  22.                 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, // 右上
  23.                 -1.0f, 1.0f, 0.0f, 0.0f, 1.0f // 左上
  24.         };
  25.     }
  26.     return new float[20] { // 终端渲染使用
  27.             -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, // 左下
  28.             1.0f, -1.0f, 0.0f, 1.0f, 1.0f, // 右下
  29.             1.0f, 1.0f, 0.0f, 1.0f, 0.0f, // 右上
  30.             -1.0f, 1.0f, 0.0f, 0.0f, 0.0f // 左上
  31.     };
  32. }
  33. } // namespace glcore
复制代码
2.12 GLTexture

​    封装 GLTexture 类是了方便用户进行纹理贴图。为了方便管理多渲染目标图层,定义了 TextureAction 接口,并提供 bind 函数,GLTexture、FBO 都继承了 TextureAction,用户自定义的渲染器或特效类也可以继承 TextureAction,将它们统一视为纹理活动(可绑定),这在特效叠加(或后处理)中非常有用,易于扩展。
​    texture_action.h
  1. #pragma once
  2. #include "core_lib.h"
  3. #include "shader_program.h"
  4. namespace glcore
  5. {
  6. /**
  7. * 纹理活动 (纹理绑定、FBO绑定)
  8. * @author little fat sheep
  9. */
  10. class TextureAction
  11. {
  12. public:
  13.     virtual ~TextureAction() = default;
  14.     virtual void setTexParameter(GLint filter, GLint wrap) {}
  15.     virtual void setBindParameter(char* alias, GLenum unit) {}
  16.     virtual void bind(ShaderProgram* shader) = 0;
  17. };
  18. } // namespace glcore
复制代码
​    gl_texture.h
  1. #pragma once
  2. #include "core_lib.h"
  3. #include "shader_program.h"
  4. #include "texture_action.h"
  5. namespace glcore
  6. {
  7. /**
  8. * 纹理贴图
  9. * @author little fat sheep
  10. */
  11. class GLTexture: public TextureAction
  12. {
  13. private:
  14.     GLuint m_textureHandle = 0; // 纹理句柄
  15.     int m_width = 0; // 纹理宽度
  16.     int m_height = 0; // 纹理高度
  17.     GLint m_filter = GL_LINEAR; // 滤波方式
  18.     GLint m_wrap = GL_CLAMP_TO_EDGE; // 环绕方式
  19.     const char* m_alias = ShaderProgram::UNIFORM_TEXTURE; // 纹理别名(着色器中变量名)
  20.     GLenum m_unit = 0; // 纹理单元 (可能有多个纹理)
  21.     bool m_isDirty = false; // 是否有脏数据 (纹理参数需要更新)
  22. public:
  23.     GLTexture(int width, int height);
  24.     GLTexture(void *buffer, int width, int height);
  25.     ~GLTexture() override;
  26.     void setTexture(const void *buffer);
  27.     void setTexParameter(GLint filter, GLint wrap) override;
  28.     void setBindParameter(char* alias, GLenum unit) override;
  29.     void bind(ShaderProgram* shader) override;
  30.     int getWidth() { return m_width; }
  31.     int getHeight() { return m_height; }
  32. private:
  33.     void applyTexParameter();
  34. };
  35. } // namespace glcore
复制代码
​    gl_texture.cpp
  1. #include "glcore/gl_inspector.h"
  2. #include "glcore/gl_texture.h"
  3. namespace glcore
  4. {
  5. GLTexture::GLTexture(int width, int height):
  6.     m_width(width),
  7.     m_height(height)
  8. {
  9. }
  10. GLTexture::GLTexture(void *buffer, int width, int height): GLTexture(width, height)
  11. {
  12.     setTexture(buffer);
  13. }
  14. GLTexture::~GLTexture()
  15. {
  16.     GL_CALL(glBindTexture(GL_TEXTURE_2D, 0));
  17.     if (m_textureHandle != 0) {
  18.         GL_CALL(glDeleteTextures(1, &m_textureHandle));
  19.         m_textureHandle = 0;
  20.     }
  21. }
  22. /**
  23. * buffer 可以通过以下两种方式得到
  24. * void* buffer = stbi_load(filePath, &width, &height, &channels, STBI_rgb_alpha)
  25. */
  26. void GLTexture::setTexture(const void *buffer)
  27. {
  28.     GL_CALL(glGenTextures(1, &m_textureHandle));
  29.     GL_CALL(glBindTexture(GL_TEXTURE_2D, m_textureHandle));
  30.     applyTexParameter();
  31.     GL_CALL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_width, m_height, 0,
  32.                  GL_RGBA, GL_UNSIGNED_BYTE, buffer));
  33.     GL_CALL(glGenerateMipmap(GL_TEXTURE_2D));
  34.     GL_CALL(glBindTexture(GL_TEXTURE_2D, 0));
  35.     //GLInspector::checkGLError("setTexture");
  36. }
  37. void GLTexture::setTexParameter(GLint filter, GLint wrap)
  38. {
  39.     m_filter = filter;
  40.     m_wrap = wrap;
  41.     m_isDirty = true;
  42. }
  43. void GLTexture::setBindParameter(char *alias, GLenum unit)
  44. {
  45.     m_alias = alias;
  46.     m_unit = unit;
  47. }
  48. void GLTexture::bind(ShaderProgram *shader)
  49. {
  50.     shader->setUniformi(m_alias, m_unit);
  51.     GL_CALL(glActiveTexture(GL_TEXTURE0 + m_unit));
  52.     GL_CALL(glBindTexture(GL_TEXTURE_2D, m_textureHandle));
  53.     if (m_isDirty)
  54.     {
  55.         applyTexParameter();
  56.     }
  57. }
  58. void GLTexture::applyTexParameter()
  59. {
  60.     GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, m_filter));
  61.     GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, m_filter));
  62.     GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, m_wrap));
  63.     GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, m_wrap));
  64.     m_isDirty = false;
  65. }
  66. } // namespace glcore
复制代码
2.13 FBO

​    FBO 是 Frame Buffer Object 的简称,即帧缓冲对象,主要用于离屏渲染、特效叠加,
​    frame_buffer_object.h
  1. #pragma once
  2. #include "core_lib.h"
  3. #include "shader_program.h"
  4. #include "texture_action.h"
  5. #include "format.h"
  6. namespace glcore
  7. {
  8. /**
  9. * 帧缓冲对象 (简称FBO, 用于离屏渲染)
  10. * @author little fat sheep
  11. */
  12. class FrameBufferObject: public TextureAction
  13. {
  14. private:
  15.     Format* m_format; // 颜色格式
  16.     int m_width; // 缓冲区宽度
  17.     int m_height; // 缓冲区高度
  18.     bool m_hasDepth; // 是否有深度缓冲区
  19.     bool m_hasStencil; // 是否有模板缓冲区
  20.     GLuint m_frameBufferHandle; // 帧缓冲区句柄
  21.     GLuint m_depthBufferHandle; // 深度缓冲区句柄
  22.     GLuint m_stencilBufferHandle; // 模板缓冲区句柄
  23.     GLuint m_colorTextureHandle; // 颜色缓冲区句柄
  24.     GLint m_preFramebufferHandle; // 前一个帧缓冲区句柄
  25.     int m_preFramebufferViewPort[4]; // 前一个帧缓冲区视口
  26.     GLint m_filter = GL_LINEAR; // 滤波方式
  27.     GLint m_wrap = GL_CLAMP_TO_EDGE; // 环绕方式
  28.     const char* m_alias = ShaderProgram::UNIFORM_TEXTURE; // 纹理别名(着色器中变量名)
  29.     GLenum m_unit = 0; // 纹理单元 (可能有多个纹理)
  30.     bool m_isDirty = true; // 是否有脏数据 (纹理参数需要更新)
  31. public:
  32.     FrameBufferObject(Format* format, int width, int height, bool hasDepth, bool hasStencil);
  33.     ~FrameBufferObject() override;
  34.     void setTexParameter(GLint filter, GLint wrap) override;
  35.     void setBindParameter(char* alias, GLenum unit) override;
  36.     void begin(); // 开始将内容渲染到fbo
  37.     void end(); // 结束将内容渲染到fbo
  38.     void bind(ShaderProgram* shader) override;
  39. private:
  40.     void applyTexParameter();
  41. };
  42. } // namespace glcore
复制代码
​    frame_buffer_object.cpp
  1. #include "glcore/frame_buffer_object.h"
  2. #include "glcore/gl_inspector.h"
  3. namespace glcore
  4. {
  5. FrameBufferObject::FrameBufferObject(Format* format, int width, int height, bool hasDepth, bool hasStencil)
  6. {
  7.     m_format = format;
  8.     m_width = width;
  9.     m_height = height;
  10.     m_hasDepth = hasDepth;
  11.     m_hasStencil = hasStencil;
  12.     GL_CALL(glGenFramebuffers(1, &m_frameBufferHandle));
  13.     begin();
  14.     if (m_hasDepth)
  15.     {
  16.         GL_CALL(glGenRenderbuffers(1, &m_depthBufferHandle));
  17.         GL_CALL(glBindRenderbuffer(GL_RENDERBUFFER, m_depthBufferHandle));
  18.         GL_CALL(glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, width, height));
  19.         GL_CALL(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
  20.             GL_RENDERBUFFER, m_depthBufferHandle));
  21.         GL_CALL(glBindRenderbuffer(GL_RENDERBUFFER, 0));
  22.     }
  23.     if (m_hasStencil)
  24.     {
  25.         GL_CALL(glGenRenderbuffers(1, &m_stencilBufferHandle));
  26.         GL_CALL(glBindRenderbuffer(GL_RENDERBUFFER, m_stencilBufferHandle));
  27.         GL_CALL(glRenderbufferStorage(GL_RENDERBUFFER, GL_STENCIL_INDEX8, width, height));
  28.         GL_CALL(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT,
  29.             GL_RENDERBUFFER, m_stencilBufferHandle));
  30.         GL_CALL(glBindRenderbuffer(GL_RENDERBUFFER, 0));
  31.     }
  32.     GL_CALL(glGenTextures(1, &m_colorTextureHandle));
  33.     GL_CALL(glBindTexture(GL_TEXTURE_2D, m_colorTextureHandle));
  34.     GL_CALL(glTexImage2D(GL_TEXTURE_2D, 0, m_format->getFormat(), m_width,
  35.     m_height, 0, m_format->getFormat(), m_format->getType(), nullptr));
  36.     applyTexParameter();
  37.     GL_CALL(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
  38.         GL_TEXTURE_2D, m_colorTextureHandle, 0));
  39.     end();
  40. }
  41. FrameBufferObject::~FrameBufferObject()
  42. {
  43.     GL_CALL(glBindTexture(GL_TEXTURE_2D, 0));
  44.     GL_CALL(glDeleteTextures(1, &m_colorTextureHandle));
  45.     if (m_hasDepth) {
  46.         GL_CALL(glDeleteRenderbuffers(1, &m_depthBufferHandle));
  47.     }
  48.     if (m_hasStencil) {
  49.         GL_CALL(glDeleteRenderbuffers(1, &m_stencilBufferHandle));
  50.     }
  51.     GL_CALL(glDeleteFramebuffers(1, &m_frameBufferHandle));
  52. }
  53. void FrameBufferObject::setTexParameter(GLint filter, GLint wrap)
  54. {
  55.     m_filter = filter;
  56.     m_wrap = wrap;
  57.     m_isDirty = true;
  58. }
  59. void FrameBufferObject::setBindParameter(char* alias, GLenum unit)
  60. {
  61.     m_alias = alias;
  62.     m_unit = unit;
  63. }
  64. void FrameBufferObject::begin()
  65. {
  66.     GL_CALL(glGetIntegerv(GL_FRAMEBUFFER_BINDING, &m_preFramebufferHandle));
  67.     GL_CALL(glGetIntegerv(GL_VIEWPORT, m_preFramebufferViewPort));
  68.     GL_CALL(glBindFramebuffer(GL_FRAMEBUFFER, m_frameBufferHandle));
  69.     GL_CALL(glViewport(0, 0, m_width, m_height));
  70. }
  71. void FrameBufferObject::end()
  72. {
  73.     GL_CALL(glBindFramebuffer(GL_FRAMEBUFFER, m_preFramebufferHandle));
  74.     GL_CALL(glViewport(m_preFramebufferViewPort[0], m_preFramebufferViewPort[1],
  75.         m_preFramebufferViewPort[2], m_preFramebufferViewPort[3]));
  76. }
  77. void FrameBufferObject::bind(ShaderProgram* shader)
  78. {
  79.     shader->setUniformi(m_alias, m_unit);
  80.     GL_CALL(glActiveTexture(GL_TEXTURE0 + m_unit));
  81.     GL_CALL(glBindTexture(GL_TEXTURE_2D, m_colorTextureHandle));
  82.     if (m_isDirty)
  83.     {
  84.         applyTexParameter();
  85.     }
  86. }
  87. void FrameBufferObject::applyTexParameter()
  88. {
  89.     GL_CALL(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, m_filter));
  90.     GL_CALL(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, m_filter));
  91.     GL_CALL(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, m_wrap));
  92.     GL_CALL(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, m_wrap));
  93.     m_isDirty = false;
  94. }
  95. } // namespace glcore
复制代码
​    format.h
  1. #pragma once
  2. #include "core_lib.h"
  3. namespace glcore
  4. {
  5. /**
  6. * 纹理格式
  7. * @author little fat sheep
  8. */
  9. class Format
  10. {
  11. private:
  12.     GLint format;
  13.     GLenum type;
  14. public:
  15.     Format(GLint format, GLenum type);
  16.     GLint getFormat() { return format; }
  17.     GLenum getType() { return type; }
  18.     static Format* Alpha();
  19.     static Format* LuminanceAlpha();
  20.     static Format* RGB565();
  21.     static Format* RGBA4444();
  22.     static Format* RGB888();
  23.     static Format* RGBA8888();
  24. };
  25. } // namespace glcore
复制代码
​    format.cpp
  1. #include "glcore/format.h"
  2. namespace glcore
  3. {
  4. Format::Format(GLint format, GLenum type):
  5.     format(format),
  6.     type(type)
  7. {
  8. }
  9. Format *Format::Alpha()
  10. {
  11.     return new Format(GL_ALPHA, GL_UNSIGNED_BYTE);
  12. }
  13. Format *Format::RGB565()
  14. {
  15.     return new Format(GL_RGB, GL_UNSIGNED_SHORT_5_6_5);
  16. }
  17. Format *Format::RGBA4444()
  18. {
  19.     return new Format(GL_RGB, GL_UNSIGNED_SHORT_4_4_4_4);
  20. }
  21. Format *Format::RGB888()
  22. {
  23.     return new Format(GL_RGB, GL_UNSIGNED_BYTE);
  24. }
  25. Format *Format::RGBA8888()
  26. {
  27.     return new Format(GL_RGBA, GL_UNSIGNED_BYTE);
  28. }
  29. } // namespace glcore
复制代码
3 工具相关

​    本节主要介绍 glcore 框架在初始化过程中所依附的工具类,如字符串加载工具、图片加载工具等,它们与平台相关(如 Android 平台字符串和图片加载依赖 JNI),不便于进行跨平台迁移,因此不能将它们归入 glcore 框架中。
3.1 StringUtils

​    StringUtils 用于加载顶点和片元着色器资源为字符串。
​    string_utils.h
  1. #pragma once
  2. /**
  3. * String工具类
  4. * @author little fat sheep
  5. */
  6. class StringUtils
  7. {
  8. public:
  9.     /**
  10.      * 根据资源路径读取字符串
  11.      * @param filePath 资源文件路径, 如: "assets/shaders/vertex_shader.glsl"
  12.      */
  13.     static const char* loadStringFromFile(const char* filePath);
  14. };
复制代码
​    string_utils.cpp
  1. #include <fstream>
  2. #include <sstream>
  3. #include <string>
  4. #include "utils/string_utils.h"
  5. using namespace std;
  6. const char* StringUtils::loadStringFromFile(const char* filePath)
  7. {
  8.     ifstream file(filePath);
  9.     if (!file.is_open())
  10.     {
  11.                 printf("failed to open file: %s\n", filePath);
  12.                 return nullptr;
  13.     }
  14.     stringstream buffer;
  15.     buffer << file.rdbuf();
  16.     file.close();
  17.     string content = buffer.str();
  18.     // 复制字符串, 避免content被回收导致悬垂指针问题
  19.     char * res = strdup(content.c_str());
  20.     return res;
  21. }
复制代码
4 应用

​    本节将基于 glcore 框架写一个色散特效叠加果冻特效的 Demo,体验一下 glcore 的便捷之处。
4.1 MyRenderer

​    my_renderer.h
  1. #pragma once
  2. struct BitmapData
  3. {
  4.     void* buffer;
  5.     int width;
  6.     int height;
  7. };
  8. /**
  9. * Bitmap工具类
  10. * @author little fat sheep
  11. */
  12. class BitmapUtils
  13. {
  14. public:
  15.     /**
  16.     * 根据资源文件路径读取bitmap
  17.     * @param filePath 资源路径, 如: "assets/textures/xxx.jpg"
  18.     */
  19.     static BitmapData* loadBitmapDataFromFile(const char* filePath);
  20. };
复制代码
​    my_renderer.cpp
  1. #define STB_IMAGE_IMPLEMENTATION
  2. #include "stb/stb_image.h"
  3. #include "utils/bitmap_utils.h"
  4. BitmapData* BitmapUtils::loadBitmapDataFromFile(const char* filePath) {
  5.     int width, height, channels;
  6.         unsigned char* data = stbi_load(filePath, &width, &height, &channels, STBI_rgb_alpha);
  7.         BitmapData* bitmapData = new BitmapData();
  8.         bitmapData->buffer = data;
  9.         bitmapData->width = width;
  10.         bitmapData->height = height;
  11.         return bitmapData;
  12. }
复制代码
4.2 DispersionEffect

​    DispersionEffect 是色散特效。
​    dispersion_effect.h
  1. #pragma once
  2. #include "glcore/core.h"
  3. #include "dispersion_effect.h"
  4. #include "jelly_effect.h"
  5. using namespace glcore;
  6. /**
  7. * 自定义渲染器
  8. * @author little fat sheep
  9. */
  10. class MyRenderer : public EGLSurfaceView::Renderer
  11. {
  12. private:
  13.     DispersionEffect* m_dispersionEffect;
  14.     JellyEffect* m_jellyEffect;
  15.     long m_startTime = 0;
  16.     float m_runTime = 0.0f;
  17. public:
  18.     MyRenderer();
  19.     ~MyRenderer() override;
  20.     void onSurfaceCreated() override;
  21.     void onSurfaceChanged(int width, int height) override;
  22.     void onDrawFrame() override;
  23. private:
  24.     long getTimestamp();
  25. };
复制代码
​    dispersion_effect.cpp
  1. #include <chrono>
  2. #include <iostream>
  3. #include "glcore/core.h"
  4. #include "render/my_renderer.h"
  5. #define TAG "MyRenderer"
  6. using namespace glcore;
  7. using namespace std::chrono;
  8. MyRenderer::MyRenderer()
  9. {
  10.     printf("%s: init\n", TAG);
  11.     m_dispersionEffect = new DispersionEffect();
  12.     m_jellyEffect = new JellyEffect();
  13.     m_jellyEffect->setTexAction(m_dispersionEffect);
  14. }
  15. MyRenderer::~MyRenderer()
  16. {
  17.     printf("%s: destroy\n", TAG);
  18.     delete m_dispersionEffect;
  19.     delete m_jellyEffect;
  20. }
  21. void MyRenderer::onSurfaceCreated()
  22. {
  23.     printf("%s: onSurfaceCreated\n", TAG);
  24.     m_dispersionEffect->onCreate();
  25.     m_jellyEffect->onCreate();
  26.     GL_CALL(glClearColor(0.1f, 0.2f, 0.3f, 0.4f));
  27.     m_startTime = getTimestamp();
  28. }
  29. void MyRenderer::onSurfaceChanged(int width, int height)
  30. {
  31.     printf("%s: onSurfaceChanged, width: %d, height: %d\n", TAG, width, height);
  32.     glViewport(0, 0, width, height);
  33.     m_dispersionEffect->onResize(width, height);
  34.     m_jellyEffect->onResize(width, height);
  35. }
  36. void MyRenderer::onDrawFrame()
  37. {
  38.     m_runTime = (getTimestamp() - m_startTime) / 1000.0f;
  39.     GL_CALL(glClear(GL_COLOR_BUFFER_BIT));
  40.     m_dispersionEffect->onDraw(m_runTime);
  41.     m_jellyEffect->onDraw(m_runTime);
  42. }
  43. long MyRenderer::getTimestamp()
  44. {
  45.     auto now = std::chrono::system_clock::now(); // 获取当前时间
  46.     auto duration = now.time_since_epoch(); // 转换为自纪元以来的时间
  47.     return duration_cast<milliseconds>(duration).count();
  48. }
复制代码
​    dispersion_vert.glsl
  1. #pragma once
  2. #include "glcore/core.h"
  3. using namespace glcore;
  4. /**
  5. * 色散特效
  6. * @author little fat sheep
  7. */
  8. class DispersionEffect: public TextureAction
  9. {
  10. private:
  11.     ShaderProgram* m_program;
  12.     Mesh* m_mesh;
  13.     GLTexture* m_glTexture;
  14.     FrameBufferObject* m_fbo;
  15. public:
  16.     DispersionEffect();
  17.     ~DispersionEffect() override;
  18.     void onCreate();
  19.     void onResize(int width, int height);
  20.     void onDraw(float runtime);
  21.     void bind(ShaderProgram* shader) override;
  22. private:
  23.     void createProgram();
  24.     void createTexture();
  25. };
复制代码
​    dispersion_frag.glsl
  1. #include <iostream>
  2. #include "glcore/core.h"
  3. #include "render/dispersion_effect.h"
  4. #include "utils/bitmap_utils.h"
  5. #include "utils/string_utils.h"
  6. #define TAG "DispersionEffect"
  7. using namespace glcore;
  8. DispersionEffect::DispersionEffect()
  9. {
  10.     printf("%s: init\n", TAG);
  11. }
  12. DispersionEffect::~DispersionEffect()
  13. {
  14.     printf("%s: destroy\n", TAG);
  15.     delete m_program;
  16.     delete m_mesh;
  17.     delete m_glTexture;
  18.     delete m_fbo;
  19. }
  20. void DispersionEffect::onCreate()
  21. {
  22.     printf("%s: onCreate\n", TAG);
  23.     createProgram();
  24.     createTexture();
  25.     m_mesh = MeshUtils::createRect(true);
  26.     m_fbo = new FrameBufferObject(Format::RGBA8888(), app->width, app->height, false, false);
  27. }
  28. void DispersionEffect::onResize(int width, int height)
  29. {
  30.     printf("%s: onResize, width: %d, height: %d\n", TAG, width, height);
  31. }
  32. void DispersionEffect::onDraw(float runtime)
  33. {
  34.     m_fbo->begin();
  35.     m_program->bind();
  36.     m_program->setUniformf("u_time", runtime);
  37.     m_program->setUniformf("u_aspect", app->aspect);
  38.     m_glTexture->bind(m_program);
  39.     m_mesh->render(m_program, GL_TRIANGLES);
  40.     m_fbo->end();
  41. }
  42. void DispersionEffect::bind(ShaderProgram* shader)
  43. {
  44.     m_fbo->bind(shader);
  45. }
  46. void DispersionEffect::createProgram()
  47. {
  48.     printf("%s: createProgram\n", TAG);
  49.     const char* vertexCode = StringUtils::loadStringFromFile("assets/shaders/dispersion_vert.glsl");
  50.     const char* fragmentCode = StringUtils::loadStringFromFile("assets/shaders/dispersion_frag.glsl");
  51.     m_program = new ShaderProgram(vertexCode, fragmentCode);
  52. }
  53. void DispersionEffect::createTexture()
  54. {
  55.     printf("%s: createTexture\n", TAG);
  56.     BitmapData* data = BitmapUtils::loadBitmapDataFromFile("assets/textures/girl.jpg");
  57.     m_glTexture = new GLTexture(data->buffer, data->width, data->height);
  58. }
复制代码
4.3 JellyEffect

​    JellyEffect 是果冻特效。
​    jelly_effect.h
  1. attribute vec4 a_position;
  2. attribute vec2 a_texCoord0;
  3. varying vec2 v_texCoord;
  4. void main() {
  5.      gl_Position = a_position;
  6.      v_texCoord = a_texCoord0;
  7. }
复制代码
​    jelly_effect.cpp
  1. precision highp float;
  2. uniform float u_aspect;
  3. uniform float u_time;
  4. uniform sampler2D u_texture;
  5. varying vec2 v_texCoord;
  6. vec2 getOffset() { // 偏移函数
  7.      float time = u_time * 1.5;
  8.      vec2 dire = vec2(sin(time), cos(time));
  9.      float strength = sin(u_time * 2.0) * 0.004;
  10.      return dire * strength * vec2(1.0, 1.0 / u_aspect);
  11. }
  12. void main() {
  13.      vec2 offset = getOffset();
  14.      vec4 color = texture2D(u_texture, v_texCoord);
  15.      color.r = texture2D(u_texture, v_texCoord + offset).r;
  16.      color.b = texture2D(u_texture, v_texCoord - offset).b;
  17.      gl_FragColor = color;
  18. }
复制代码
​    jelly_vert.glsl
  1. #pragma once
  2. #include "glcore/core.h"
  3. using namespace glcore;
  4. /**
  5. * 色散特效
  6. * @author little fat sheep
  7. */
  8. class DispersionEffect: public TextureAction
  9. {
  10. private:
  11.     ShaderProgram* m_program;
  12.     Mesh* m_mesh;
  13.     GLTexture* m_glTexture;
  14.     FrameBufferObject* m_fbo;
  15. public:
  16.     DispersionEffect();
  17.     ~DispersionEffect() override;
  18.     void onCreate();
  19.     void onResize(int width, int height);
  20.     void onDraw(float runtime);
  21.     void bind(ShaderProgram* shader) override;
  22. private:
  23.     void createProgram();
  24.     void createTexture();
  25. };
复制代码
​    jelly_frag.glsl
  1. #include <iostream>
  2. #include "glcore/core.h"
  3. #include "render/jelly_effect.h"
  4. #include "utils/string_utils.h"
  5. #define TAG "JellyEffect"
  6. using namespace glcore;
  7. JellyEffect::JellyEffect()
  8. {
  9.     printf("%s: init\n", TAG);
  10. }
  11. JellyEffect::~JellyEffect()
  12. {
  13.     printf("%s: destroy\n", TAG);
  14.     delete m_program;
  15.     delete m_mesh;
  16. }
  17. void JellyEffect::setTexAction(TextureAction* texAction)
  18. {
  19.     m_texAction = texAction;
  20. }
  21. void JellyEffect::onCreate()
  22. {
  23.     printf("%s: onCreate\n", TAG);
  24.     createProgram();
  25.     m_mesh = MeshUtils::createRect(false);
  26. }
  27. void JellyEffect::onResize(int width, int height)
  28. {
  29.     printf("%s: onResize, width: %d, height: %d\n", TAG, width, height);
  30. }
  31. void JellyEffect::onDraw(float runtime)
  32. {
  33.     m_program->bind();
  34.     m_program->setUniformf("u_time", runtime);
  35.     m_program->setUniformf("u_aspect", app->aspect);
  36.     m_texAction->bind(m_program);
  37.     m_mesh->render(m_program, GL_TRIANGLE_FAN);
  38. }
  39. void JellyEffect::createProgram()
  40. {
  41.     printf("%s: createProgram\n", TAG);
  42.     const char* vertexCode = StringUtils::loadStringFromFile("assets/shaders/jelly_vert.glsl");
  43.     const char* fragmentCode = StringUtils::loadStringFromFile("assets/shaders/jelly_frag.glsl");
  44.     m_program = new ShaderProgram(vertexCode, fragmentCode);
  45. }
复制代码
4.4 运行效果

​    运行效果如下,可以看到叠加了色散和果冻特效。
3.gif

​    声明:本文转自【OpenGL ES】在Windows上手撕一个mini版的渲染框架。

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

您需要登录后才可以回帖 登录 | 立即注册