Vulkan是Khronos Group组织发布的跨平台图像渲染引擎,而Khronos Group是由Intel、Nvidia等公司共同创立,致力于创建开放标准的应用程序API。大名鼎鼎的OpenGL、OpenGL ES、WebGL、Vulkan都是来自Khronos组织。而Vulkan号称为“下一版本的OpenGL”,旨在提供更低的CPU开销和更多GPU控制。Android API 24以后支持vulkan,iOS在WWDC2014也推出Metal图像渲染。短期内全面取代OpenGL应该不现实,但从长远来看,它取代OpenGL应该是大势所趋的。笔者也是新接触Vulkan,从初学者的角度来看,它的程序确实比较繁琐,一个简单的Triangle程序竟然要1000多行的代码,但万丈高楼平地起,像学习OpenGL一样,任何复杂的工程都必须先从简单的三角形开始,这里我把Vulkan的三角形先写下来,给后来者一个参考。
1、配置Vulkan的环境,这里就不细说了,网上有很多教程,这里推荐一篇吧,地址是:https://blog.csdn.net/allflowerup/article/details/89766179,总结下来就是将vulkan下载下来并安装好,再将glfw和glm两个库文件放置到VS的环境设置目录里,后者(glfw和glm)的设置和OpenGL的开发环境搭建一模一样。顺便说下:
GLFW是配合 OpenGL 使用的轻量级工具程序库,缩写自 Graphics Library Framework(图形库框架)。GLFW 的主要功能是创建并管理窗口和 OpenGL 上下文,同时还提供了处理手柄、键盘、鼠标输入的功能。
GLM(OpenGL Mathematics )是基于OpenGL着色语言(GLSL)规范的图形软件的头文件C ++数学库。GLM提供的类和函数使用与GLSL相同的命名约定和功能设计和实现,因此任何知道GLSL的人都可以在C ++中使用GLM。
2、我是用Visual Studio2019,先在VS里创建一个空的项目为HelloTriangle,然后为它添加一个HelloTriangle.cpp的源文件,代码如下:
#define GLFW_INCLUDE_VULKAN
#include
#include
#include
#include
#include
#include
HelloTriangle
3、在项目中再建两个着色器文件,分别为:顶点着色器的shader.vert和片元着色器的shader.frag
shader.vert
#version 450
layout(location = 0) out vec3 fragColor;
vec2 positions[3] = vec2[](
vec2(0.0, -0.5),
vec2(0.5, 0.5),
vec2(-0.5, 0.5)
);
vec3 colors[3] = vec3[](
vec3(1.0, 0.0, 0.0),
vec3(0.0, 1.0, 0.0),
vec3(0.0, 0.0, 1.0)
);
void main() {
gl_Position = vec4(positions[gl_VertexIndex], 0.0, 1.0);
fragColor = colors[gl_VertexIndex];
}
shader.vert
shader.frag
#version 450
#extension GL_ARB_separate_shader_objects : enable
layout(location = 0) in vec3 fragColor;
layout(location = 0) out vec4 outColor;
void main() {
outColor = vec4(fragColor, 1.0);
}
shader.frag
4、将shader.vert和shader.frag分别编译成vert.spv和frag.spv,笔者自己的环境是在F盘,如下:
F:\Study\Vulkan\HelloTriangle1>glslc.exe shader.vert -o vert.spv
F:\Study\Vulkan\HelloTriangle1>glslc.exe shader.frag -o frag.spv
F:\Study\Vulkan\HelloTriangle1>dir
驱动器 F 中的卷是 新加卷
卷的序列号是 86A1-6462
F:\Study\Vulkan\HelloTriangle1 的目录
2022/03/19 17:13 .
2022/03/19 17:13 ..
2022/03/19 17:13 608 frag.spv
2022/03/19 17:13 61,696 HelloTriangle.cpp
2022/03/19 17:08 30,563 HelloTriangle1.vcxproj
2022/03/19 17:08 1,204 HelloTriangle1.vcxproj.filters
2022/03/15 18:08 168 HelloTriangle1.vcxproj.user
2022/03/19 17:08 218 shader.frag
2022/03/19 17:07 391 shader.vert
2022/03/19 17:13 1,504 vert.spv
2022/03/15 18:12 x64
9 个文件 96,352 字节
3 个目录 66,113,679,360 可用字节
F:\Study\Vulkan\HelloTriangle1>
glslc.exe
这里对spriv进行简单描述,它是Standard, Portable Intermediate Representation - V (SPIR-V)的缩写,是一种用于GPU通用计算和图形学的中间语言,在OpenGL4.6版本后才支持SPIR-V,由Khronos开发设计,最初是为OpenCL规范准备的,和Vulkan的标准差不多同时提出,也还在不断发展完善中,详细介绍请移步:https://blog.csdn.net/aoxuestudy/article/details/112350292
5、按VS上的F5执行,结果如下: