Mac CLion下OpenGL环境配置

1. 配置glew和glfw

终端下运行下面两句,安装完后在/usr/local/Cellar/下可以找到对应的目录。

brew install glew
brew install glfw3

效果如下所示:
Mac CLion下OpenGL环境配置

2. 配置glad

glad是为了简化开发而设计的,不是必须的,是一个function loader,在glad文件生成网站配置好,如下所示:
Mac CLion下OpenGL环境配置

在右下角点击generate生成恰当的glad压缩文件,解压缩后将头文件放到/usr/local/include目录下(glad和KHR文件夹),将源文件拷贝到工程目录下,如下两图所示:
Mac CLion下OpenGL环境配置Mac CLion下OpenGL环境配置

3. 配置CMakeLists文件

下面是CMakeLists的详细配置:

cmake_minimum_required(VERSION 3.12)
project(OpenGL) set(CMAKE_CXX_STANDARD 14) set(GLEW_H /usr/local/Cellar/glew/2.1.0/include/GL)
set(GLFW_H /usr/local/Cellar/glfw/3.2.1/include/GLFW)
set(GLAD_H /usr/local/include/glad)
set(KH_H /usr/local/include/KHR)
include_directories(${GLEW_H} ${GLFW_H} ${GLAD_H} ${KH_H}) # 添加目标链接
set(GLEW_LINK /usr/local/Cellar/glew/2.1.0/lib/libGLEW.2.1.dylib)
set(GLFW_LINK /usr/local/Cellar/glfw/3.2.1/lib/libglfw.3.dylib)
link_libraries(${OPENGL} ${GLEW_LINK} ${GLFW_LINK}) # 执行编译命令
# 这个glad.c在第2步中说过要拉到项目中,注意路径
set(SOURCE_FILES "src/glad.c" "main.cpp")
add_executable(OpenGL ${SOURCE_FILES}) # mac下这步很重要
if (APPLE)
target_link_libraries(OpenGL "-framework OpenGL")
target_link_libraries(OpenGL "-framework GLUT")
endif()

注意这样配置之后需要更改/usr/local/include/glad文件夹下的glad.h中的#include <KHR/khrplatform.h>更改为#include <khrplatform.h>,具体步骤:

  1. 在CLion中打开glad.c文件,command+点按#include <glad.h>会跳到glad.h
  2. 然后在glad.h中command+f找到#include <KHR/khrplatform.h>,将它改为#include <khrplatform.h>

如下所示:
Mac CLion下OpenGL环境配置Mac CLion下OpenGL环境配置

4. 运行测试代码

在main.cpp拷贝下面代码,如果能出现图示结果即为成功。
Mac CLion下OpenGL环境配置

#include <glew.h>
#include <glfw3.h>
#include <iostream>
using namespace std; void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
//如果按下ESC,把windowShouldClose设置为True,外面的循环会关闭应用
if(key==GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
std::cout<<"ESC"<<mode;
} int main(void)
{
//初始化GLFW库
if(!glfwInit())
return -1;
//创建窗口以及上下文
GLFWwindow* window = glfwCreateWindow(640, 480, "hello world", NULL, NULL);
if(!window)
{
//创建失败会返回NULL
glfwTerminate();
}
//建立当前窗口的上下文
glfwMakeContextCurrent(window); glfwSetKeyCallback(window, key_callback); //注册回调函数
//循环,直到用户关闭窗口
while(!glfwWindowShouldClose(window))
{
/*******轮询事件*******/
glfwPollEvents(); /*******渲染*******/
//选择清空的颜色RGBA
glClearColor(0.2, 0.3, 0.3, 1);
glClear(GL_COLOR_BUFFER_BIT); //开始画一个三角形
glBegin(GL_TRIANGLES);
glColor3f(1, 0, 0); //Red
glVertex3f(0, 1, 1); glColor3f(0, 1, 0); //Green
glVertex3f(-1, -1, 0); glColor3f(0, 0, 1); //Blue
glVertex3f(1, -1, 0);
//结束一个画图步骤
glEnd(); glBegin(GL_POLYGON);
//再画个梯形,需要注意笔顺
glColor3f(0.5, 0.5, 0.5); //Grey
glVertex2d(0.5, 0.5);
glVertex2d(1, 1);
glVertex2d(1, 0);
glVertex2d(0.5, 0);
glEnd(); /******交换缓冲区,更新window上的内容******/
glfwSwapBuffers(window);
}
glfwTerminate();
return 0;
}

参考资料

http://www.stephenzhang.me/2018/02/06/MacOS%E4%B8%8BCLion%E9%85%8D%E7%BD%AEOpenGL%E5%BC%80%E5%8F%91%E7%8E%AF%E5%A2%83/

上一篇:tomcat错误信息解决方案 严重:StandardServer.await:


下一篇:Ajax核心——XMLHttpRequest基础