C++ Vector属性Swizzle实现

一.前言

  • 在写gl shader的时候, 我发现glsl的语法中vec可以支持如同如下的语法任意混合属性
vec3 pos;
pos.xyz
pos.yxz
pos.xxx
pos.zx
...
  • 我们可以很容易的在C++写一个2、3个属性的vec类,但是如何使得vec也支持如上语法将属性进行混合呢?


二.方案一

  • 我们或许可以想到,利用uion+struct来实现
struct vec3
{
    union
    {
        struct
        {
            int x,y,z;
        };

        struct
        {
            vec2 xy;
            int z;
        };
        struct
        {
            int x;
            vec2 yz;
        };
        struct
        {
            vec3 xyz;
        };
    }
}
  • 利用union的特性可以使得多个”名字”使用同一块内存区,然而以上方法并不能很好的实现我们想要的Swizzle。比如,我们不能使用类似于 xz(有间隔)、zy(逆序) 这样的属性。


二.方案二

  • 利用宏、将属性转变为方法
#include <iostream>

using namespace std;

class Vec2
{
public:
    Vec2(int xx, int yy):x(xx), y(yy){}
    int x, y;
};

class Vec2Ref
{
public:
    Vec2Ref(int& x, int& y):m_x(x), m_y(y){}
    Vec2Ref(const Vec2Ref& v):m_x(v.m_x), m_y(v.m_y){}

    void operator=(Vec2 v)
    {
        m_x = v.x;
        m_y = v.y;
    }
    operator Vec2()
    {
        return Vec2(m_x, m_y);
    }
private:
    int& m_x;
    int& m_y;
};

class Vec3
{
public:
    Vec3(int xx, int yy, int zz):x(xx), y(yy), z(zz){}

    int x, y, z;
public:
    Vec2Ref FunXY() { return Vec2Ref(x, y);}
    Vec2Ref FunYZ() { return Vec2Ref(y, z);}
    Vec2Ref FunXZ() { return Vec2Ref(x, z);}
#define xy FunXY()
#define yz FunYZ()
#define xz FunXZ()
};
int main()
{
    Vec3 v3(1,2,3);
    Vec2 v2(4,5);
    cout << "sizeof(Vec3): " << sizeof(Vec3) << endl;
    v3.xy = v2;
    cout << v3.x << v3.y << v3.z << endl;
    return 0;
}
  • 利用添加中间层和构造函数和引用成员变量使得可以灵活的重组属性,不过缺点是宏会造成全局污染。其他地方也没办法正常使用x,y这样的变量。


二.方案三

  • 使用glm库的时候,发现glm库提供了这样的方法,使得可以对成员的Swizzle。需要添加GLM_SWIZZLE宏。
  • 下面这段代码主要Copy自glm库,个人只进行了少量的修改。
template <typename T>
struct _swizzle_base0
{
protected:
    inline T& elem(size_t i) { return (reinterpret_cast<T*>(_buffer))[i]; }
    inline T const& elem(size_t i) const { return (reinterpret_cast<const T*>(_buffer))[i]; }

    char    _buffer[1];
};

template <int N, typename T, template <typename> class vecType, int E0, int E1, int E2>
struct _swizzle_base1 : public _swizzle_base0<T>
{
};

template <typename T, template <typename> class vecType, int E0, int E1>
struct _swizzle_base1<2, T, vecType, E0, E1, -1> : public _swizzle_base0<T>
{
    inline vecType<T> operator ()()  const { return vecType<T>(this->elem(E0), this->elem(E1)); }
};

template <typename T, template <typename> class vecType, int E0, int E1, int E2>
struct _swizzle_base1<3, T, vecType, E0, E1, E2> : public _swizzle_base0<T>
{
    inline vecType<T> operator ()()  const { return vecType<T>(this->elem(E0), this->elem(E1), this->elem(E2)); }
};

template <int N, typename T, template <typename> class vecType, int E0, int E1, int E2, int DUPLICATE_ELEMENTS>
struct _swizzle_base2 : public _swizzle_base1<N, T, vecType, E0, E1, E2>
{
    inline _swizzle_base2& operator= (const T& t)
    {
        for (int i = 0; i < N; ++i)
            (*this)[i] = t;
        return *this;
    }

#   define APPLY_OP(EXP)               \
inline void                            \
operator EXP (vecType<T> const& that)  \
{                                      \
    struct op {                        \
        inline void                    \
        operator() (T& e, T& t)        \
        { e EXP t; }                   \
    };                                 \
    _apply_op(that, op());             \
}

    inline _swizzle_base2& operator= (vecType<T> const& that)
    {
        struct op {
            inline void operator() (T& e, T& t) { e = t; }
        };
        _apply_op(that, op());
        return *this;
    }

    APPLY_OP(-=)
    APPLY_OP(+=)
    APPLY_OP(*=)
    APPLY_OP(/=)

    inline T& operator[](size_t i)
    {
        const int offset_dst[4] = { E0, E1, E2 };
        return this->elem(offset_dst[i]);
    }
    inline T operator[](size_t i) const
    {
        const int offset_dst[4] = { E0, E1, E2 };
        return this->elem(offset_dst[i]);
    }

#undef  APPLY_OP

protected:
    template <typename U>
    inline void _apply_op(vecType<T> const& that, U op)
    {
        T t[N];
        for (int i = 0; i < N; ++i)
            t[i] = that[i];
        for (int i = 0; i < N; ++i)
            op((*this)[i], t[i]);
    }
};

template <int N, typename T, template <typename> class vecType, int E0, int E1, int E2>
struct _swizzle_base2<N, T, vecType, E0, E1, E2, 1> : public _swizzle_base1<N, T, vecType, E0, E1, E2>
{
    struct Stub {};

    inline _swizzle_base2& operator= (Stub const &) { return *this; }

    inline T operator[]  (size_t i) const
    {
        const int offset_dst[4] = { E0, E1, E2 };
        return this->elem(offset_dst[i]);
    }
};

template <int N, typename T, template <typename> class vecType, int E0, int E1, int E2>
struct _swizzle : public _swizzle_base2<N, T, vecType, E0, E1, E2, (E0 == E1 || E0 == E2 || E1 == E2)>
{
    typedef _swizzle_base2<N, T, vecType, E0, E1, E2, (E0 == E1 || E0 == E2 || E1 == E2)> base_type;

    using base_type::operator=;

    inline operator vecType<T>() const { return (*this)(); }
};

#define _SWIZZLE3_2_MEMBERS(T, V, E0,E1,E2) \
    struct { _swizzle<2,T, V, 0,0,-1> E0 ## E0; }; \
    struct { _swizzle<2,T, V, 0,1,-1> E0 ## E1; }; \
    struct { _swizzle<2,T, V, 0,2,-1> E0 ## E2; }; \
    struct { _swizzle<2,T, V, 1,0,-1> E1 ## E0; }; \
    struct { _swizzle<2,T, V, 1,1,-1> E1 ## E1; }; \
    struct { _swizzle<2,T, V, 1,2,-1> E1 ## E2; }; \
    struct { _swizzle<2,T, V, 2,0,-1> E2 ## E0; }; \
    struct { _swizzle<2,T, V, 2,1,-1> E2 ## E1; }; \
    struct { _swizzle<2,T, V, 2,2,-1> E2 ## E2; };

#define _SWIZZLE3_3_MEMBERS(T, V ,E0,E1,E2) \
    struct { _swizzle<3, T, V, 0,0,0> E0 ## E0 ## E0; }; \
    struct { _swizzle<3, T, V, 0,0,1> E0 ## E0 ## E1; }; \
    struct { _swizzle<3, T, V, 0,0,2> E0 ## E0 ## E2; }; \
    struct { _swizzle<3, T, V, 0,1,0> E0 ## E1 ## E0; }; \
    struct { _swizzle<3, T, V, 0,1,1> E0 ## E1 ## E1; }; \
    struct { _swizzle<3, T, V, 0,1,2> E0 ## E1 ## E2; }; \
    struct { _swizzle<3, T, V, 0,2,0> E0 ## E2 ## E0; }; \
    struct { _swizzle<3, T, V, 0,2,1> E0 ## E2 ## E1; }; \
    struct { _swizzle<3, T, V, 0,2,2> E0 ## E2 ## E2; }; \
    struct { _swizzle<3, T, V, 1,0,0> E1 ## E0 ## E0; }; \
    struct { _swizzle<3, T, V, 1,0,1> E1 ## E0 ## E1; }; \
    struct { _swizzle<3, T, V, 1,0,2> E1 ## E0 ## E2; }; \
    struct { _swizzle<3, T, V, 1,1,0> E1 ## E1 ## E0; }; \
    struct { _swizzle<3, T, V, 1,1,1> E1 ## E1 ## E1; }; \
    struct { _swizzle<3, T, V, 1,1,2> E1 ## E1 ## E2; }; \
    struct { _swizzle<3, T, V, 1,2,0> E1 ## E2 ## E0; }; \
    struct { _swizzle<3, T, V, 1,2,1> E1 ## E2 ## E1; }; \
    struct { _swizzle<3, T, V, 1,2,2> E1 ## E2 ## E2; }; \
    struct { _swizzle<3, T, V, 2,0,0> E2 ## E0 ## E0; }; \
    struct { _swizzle<3, T, V, 2,0,1> E2 ## E0 ## E1; }; \
    struct { _swizzle<3, T, V, 2,0,2> E2 ## E0 ## E2; }; \
    struct { _swizzle<3, T, V, 2,1,0> E2 ## E1 ## E0; }; \
    struct { _swizzle<3, T, V, 2,1,1> E2 ## E1 ## E1; }; \
    struct { _swizzle<3, T, V, 2,1,2> E2 ## E1 ## E2; }; \
    struct { _swizzle<3, T, V, 2,2,0> E2 ## E2 ## E0; }; \
    struct { _swizzle<3, T, V, 2,2,1> E2 ## E2 ## E1; }; \
    struct { _swizzle<3, T, V, 2,2,2> E2 ## E2 ## E2; };

template<typename T>
struct vec2
{
    union
    {
        struct {
            T x, y;
        };
    };
    vec2(T tx, T ty) :x(tx), y(ty) {}
};


template<typename T>
struct vec3
{
    union 
    {
        struct {
            T x, y, z;
        };
        _SWIZZLE3_2_MEMBERS(T, ::vec2, x, y, z)
        _SWIZZLE3_3_MEMBERS(T, ::vec3, x, y, z)
    };
    vec3(T tx, T ty, T tz) :x(tx), y(ty), z(tz) {}
};

int main()
{
    vec3<float> v(1, 2, 3);
    vec3<float> v3 = v.yzy;
    printf("%f %f %f\n", v3.x, v3.y, v3.z);

    getchar();
    return 0;
}

就以上的代码,做简要的分析。

1. class _swizzle_base0

    _swizzle_base0 作为 swizzle 最底层的类仅仅是提供elem接口,利用 i 来获取第 i 个 element。

2. class _swizzle_base1 : public _swizzle_base0

    _swizzle_base1<N, T, VecType, E0, E1, E2>
    N:         swizzle的属性的个数
    T:        属性类型
    VecType:   Swizzle elem后的目标类型
    E0,E1,E2: Swizzle 的每个elem的索引

    _swizzle_base1 以N的个数来做特化,主要是为 swizzle 属性 提供 get 属性。
    也就是说当我们使用 vec2 v2 = v3.xz 的时候实则是调用了 _swizzle_base1::operator()() 来构造了一个vec2。
    根据N分别为2,3来构造由2个elem或者3个elem swizzle的VecType.

3. class _swizzle_base2 : public _swizzle_base1

    _swizzle_base2<N, T, VecType, E0, E1, E2, DUPLICATE_ELEMENTS>
    DUPLICATE_ELEMENTS: 这个参数是指swizzle的属性中是否有相同的,比如: vec3.yxy
    事实上,当swizzle的属性中有相同的elem时,只有get属性,因为当对其赋值时vec3.yxy = (1,2,3)行为是不确定的。

    _swizzle_base2 以 DUPLICATE_ELEMENTS(0,1)特化
    当DUPLICATE_ELEMENTS为0时,也就是无相同元素,有set属性。
    _swizzle_base2::operator=(vecType<T> const& )
    _swizzle_base2::operator+=(vecType<T> const& )
    _swizzle_base2::operator-=(vecType<T> const& )
    _swizzle_base2::operator*=(vecType<T> const& )
    _swizzle_base2::operator/=(vecType<T> const& )
    以上方法提供了set属性,
    也就是说当vec3.zy = vec2(2,1)的时候实则调用了_swizzle_base2::operator=(vecType<T> const&)

    _swizzle_base2::operator[](size_t i)
    提供的是按照索引访问swizzle之后的属性,注意区别和_swizzle_base0::elem的区别。

4. class _swizzle : public _swizzle_base2

    _swizzle<N, T, VecType, E0, E1, E2>
    提供_swizzle::operator vecType<T>()转换函数,根据特化调用基类的operator()得到相应的swizzle属性。

5. uinon + struct + 宏

    利用宏完成对属性swizzle的排列组合
    _SWIZZLE3_2_MEMBERS(T, ::vec2, x, y, z)
    只需如上申明,就可以完成对x,y,z三个属性的任意两个元素的swizzle。
以下是一个简单的Vulkan在桌面写字的代码示例: ```c #define GLFW_INCLUDE_VULKAN #include <GLFW/glfw3.h> #include <vulkan/vulkan.h> #include <stdio.h> #include <stdlib.h> #include <string.h> // 定义窗口宽度和高度 const uint32_t WIDTH = 800; const uint32_t HEIGHT = 600; // 定义顶点数据 const float vertices[] = { -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, 0.0f, 1.0f, 0.5f, 0.5f, 0.0f, 1.0f, -0.5f, 0.5f, 0.0f, 1.0f }; // 定义顶点索引 const uint16_t indices[] = { 0, 1, 2, 2, 3, 0 }; int main() { // 初始化GLFW库 if (!glfwInit()) { printf("Failed to initialize GLFW\n"); return -1; } // 创建GLFW窗口 glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "Vulkan", NULL, NULL); // 创建Vulkan实例 VkInstance instance; VkApplicationInfo appInfo = {}; appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; appInfo.pApplicationName = "Vulkan Example"; appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.pEngineName = "No Engine"; appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.apiVersion = VK_API_VERSION_1_0; VkInstanceCreateInfo createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; createInfo.pApplicationInfo = &appInfo; uint32_t glfwExtensionCount = 0; const char** glfwExtensions; glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); createInfo.enabledExtensionCount = glfwExtensionCount; createInfo.ppEnabledExtensionNames = glfwExtensions; createInfo.enabledLayerCount = 0; if (vkCreateInstance(&createInfo, NULL, &instance) != VK_SUCCESS) { printf("Failed to create Vulkan instance\n"); return -1; } // 创建Vulkan设备 VkPhysicalDevice physicalDevice = VK_NULL_HANDLE; uint32_t deviceCount = 0; vkEnumeratePhysicalDevices(instance, &deviceCount, NULL); if (deviceCount == 0) { printf("Failed to find Vulkan physical device\n"); return -1; } VkPhysicalDevice* devices = (VkPhysicalDevice*)malloc(deviceCount * sizeof(VkPhysicalDevice)); vkEnumeratePhysicalDevices(instance, &deviceCount, devices); for (uint32_t i = 0; i < deviceCount; i++) { VkPhysicalDeviceProperties deviceProperties; vkGetPhysicalDeviceProperties(devices[i], &deviceProperties); if (deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) { physicalDevice = devices[i]; break; } } if (physicalDevice == VK_NULL_HANDLE) { physicalDevice = devices[0]; } free(devices); float queuePriority = 1.0f; VkDeviceQueueCreateInfo queueCreateInfo = {}; queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queueCreateInfo.queueFamilyIndex = 0; queueCreateInfo.queueCount = 1; queueCreateInfo.pQueuePriorities = &queuePriority; VkDeviceCreateInfo deviceCreateInfo = {}; deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; deviceCreateInfo.queueCreateInfoCount = 1; deviceCreateInfo.pQueueCreateInfos = &queueCreateInfo; deviceCreateInfo.enabledExtensionCount = 0; deviceCreateInfo.ppEnabledExtensionNames = NULL; deviceCreateInfo.enabledLayerCount = 0; deviceCreateInfo.ppEnabledLayerNames = NULL; VkDevice device; if (vkCreateDevice(physicalDevice, &deviceCreateInfo, NULL, &device) != VK_SUCCESS) { printf("Failed to create Vulkan device\n"); return -1; } // 创建Vulkan交换链 VkSurfaceKHR surface; if (glfwCreateWindowSurface(instance, window, NULL, &surface) != VK_SUCCESS) { printf("Failed to create Vulkan window surface\n"); return -1; } uint32_t formatCount = 0; vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surface, &formatCount, NULL); VkSurfaceFormatKHR* formats = (VkSurfaceFormatKHR*)malloc(formatCount * sizeof(VkSurfaceFormatKHR)); vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surface, &formatCount, formats); VkSurfaceFormatKHR surfaceFormat; if (formatCount == 1 && formats[0].format == VK_FORMAT_UNDEFINED) { surfaceFormat.format = VK_FORMAT_B8G8R8A8_UNORM; surfaceFormat.colorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR; } else { for (uint32_t i = 0; i < formatCount; i++) { if (formats[i].format == VK_FORMAT_B8G8R8A8_UNORM) { surfaceFormat = formats[i]; break; } } } free(formats); VkPresentModeKHR presentMode = VK_PRESENT_MODE_FIFO_KHR; uint32_t presentModeCount = 0; vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, surface, &presentModeCount, NULL); VkPresentModeKHR* presentModes = (VkPresentModeKHR*)malloc(presentModeCount * sizeof(VkPresentModeKHR)); vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, surface, &presentModeCount, presentModes); for (uint32_t i = 0; i < presentModeCount; i++) { if (presentModes[i] == VK_PRESENT_MODE_MAILBOX_KHR) { presentMode = presentModes[i]; break; } } free(presentModes); VkSurfaceCapabilitiesKHR surfaceCapabilities; vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice, surface, &surfaceCapabilities); uint32_t imageCount = surfaceCapabilities.minImageCount + 1; if (surfaceCapabilities.maxImageCount > 0 && imageCount > surfaceCapabilities.maxImageCount) { imageCount = surfaceCapabilities.maxImageCount; } VkSwapchainCreateInfoKHR swapchainCreateInfo = {}; swapchainCreateInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; swapchainCreateInfo.surface = surface; swapchainCreateInfo.minImageCount = imageCount; swapchainCreateInfo.imageFormat = surfaceFormat.format; swapchainCreateInfo.imageColorSpace = surfaceFormat.colorSpace; swapchainCreateInfo.imageExtent = { WIDTH, HEIGHT }; swapchainCreateInfo.imageArrayLayers = 1; swapchainCreateInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; swapchainCreateInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; swapchainCreateInfo.preTransform = surfaceCapabilities.currentTransform; swapchainCreateInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; swapchainCreateInfo.presentMode = presentMode; swapchainCreateInfo.clipped = VK_TRUE; VkSwapchainKHR swapchain; if (vkCreateSwapchainKHR(device, &swapchainCreateInfo, NULL, &swapchain) != VK_SUCCESS) { printf("Failed to create Vulkan swapchain\n"); return -1; } uint32_t swapchainImageCount = 0; vkGetSwapchainImagesKHR(device, swapchain, &swapchainImageCount, NULL); VkImage* swapchainImages = (VkImage*)malloc(swapchainImageCount * sizeof(VkImage)); vkGetSwapchainImagesKHR(device, swapchain, &swapchainImageCount, swapchainImages); // 创建Vulkan渲染通道 VkRenderPass renderPass; VkAttachmentDescription attachmentDescription = {}; attachmentDescription.format = surfaceFormat.format; attachmentDescription.samples = VK_SAMPLE_COUNT_1_BIT; attachmentDescription.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; attachmentDescription.storeOp = VK_ATTACHMENT_STORE_OP_STORE; attachmentDescription.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; attachmentDescription.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; attachmentDescription.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; attachmentDescription.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; VkAttachmentReference attachmentReference = {}; attachmentReference.attachment = 0; attachmentReference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkSubpassDescription subpassDescription = {}; subpassDescription.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpassDescription.colorAttachmentCount = 1; subpassDescription.pColorAttachments = &attachmentReference; VkRenderPassCreateInfo renderPassCreateInfo = {}; renderPassCreateInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; renderPassCreateInfo.attachmentCount = 1; renderPassCreateInfo.pAttachments = &attachmentDescription; renderPassCreateInfo.subpassCount = 1; renderPassCreateInfo.pSubpasses = &subpassDescription; if (vkCreateRenderPass(device, &renderPassCreateInfo, NULL, &renderPass) != VK_SUCCESS) { printf("Failed to create Vulkan render pass\n"); return -1; } // 创建Vulkan管线布局 VkPipelineLayout pipelineLayout; VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo = {}; pipelineLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pipelineLayoutCreateInfo.setLayoutCount = 0; pipelineLayoutCreateInfo.pSetLayouts = NULL; pipelineLayoutCreateInfo.pushConstantRangeCount = 0; pipelineLayoutCreateInfo.pPushConstantRanges = NULL; if (vkCreatePipelineLayout(device, &pipelineLayoutCreateInfo, NULL, &pipelineLayout) != VK_SUCCESS) { printf("Failed to create Vulkan pipeline layout\n"); return -1; } // 创建Vulkan图形管线 VkShaderModule vertexShaderModule; VkShaderModuleCreateInfo vertexShaderModuleCreateInfo = {}; vertexShaderModuleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; vertexShaderModuleCreateInfo.codeSize = sizeof(uint32_t) * 4; vertexShaderModuleCreateInfo.pCode = (const uint32_t*)vertices; if (vkCreateShaderModule(device, &vertexShaderModuleCreateInfo, NULL, &vertexShaderModule) != VK_SUCCESS) { printf("Failed to create Vulkan vertex shader module\n"); return -1; } VkShaderModule fragmentShaderModule; VkShaderModuleCreateInfo fragmentShaderModuleCreateInfo = {}; fragmentShaderModuleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; fragmentShaderModuleCreateInfo.codeSize = sizeof(uint32_t) * 4; fragmentShaderModuleCreateInfo.pCode = (const uint32_t*)vertices; if (vkCreateShaderModule(device, &fragmentShaderModuleCreateInfo, NULL, &fragmentShaderModule) != VK_SUCCESS) { printf("Failed to create Vulkan fragment shader module\n"); return -1; } VkPipelineShaderStageCreateInfo vertexShaderStageCreateInfo = {}; vertexShaderStageCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; vertexShaderStageCreateInfo.stage = VK_SHADER_STAGE_VERTEX_BIT; vertexShaderStageCreateInfo.module = vertexShaderModule; vertexShaderStageCreateInfo.pName = "main"; VkPipelineShaderStageCreateInfo fragmentShaderStageCreateInfo = {}; fragmentShaderStageCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; fragmentShaderStageCreateInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT; fragmentShaderStageCreateInfo.module = fragmentShaderModule; fragmentShaderStageCreateInfo.pName = "main"; VkPipelineShaderStageCreateInfo shaderStages[] = { vertexShaderStageCreateInfo, fragmentShaderStageCreateInfo }; VkPipelineVertexInputStateCreateInfo vertexInputStateCreateInfo = {}; vertexInputStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; vertexInputStateCreateInfo.vertexBindingDescriptionCount = 0; vertexInputStateCreateInfo.pVertexBindingDescriptions = NULL; vertexInputStateCreateInfo.vertexAttributeDescriptionCount = 0; vertexInputStateCreateInfo.pVertexAttributeDescriptions = NULL; VkPipelineInputAssemblyStateCreateInfo inputAssemblyStateCreateInfo = {}; inputAssemblyStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; inputAssemblyStateCreateInfo.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; inputAssemblyStateCreateInfo.primitiveRestartEnable = VK_FALSE; VkViewport viewport = {}; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = (float)WIDTH; viewport.height = (float)HEIGHT; viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; VkRect2D scissor = {}; scissor.offset = { 0, 0 }; scissor.extent = { WIDTH, HEIGHT }; VkPipelineViewportStateCreateInfo viewportStateCreateInfo = {}; viewportStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; viewportStateCreateInfo.viewportCount = 1; viewportStateCreateInfo.pViewports = &viewport; viewportStateCreateInfo.scissorCount = 1; viewportStateCreateInfo.pScissors = &scissor; VkPipelineRasterizationStateCreateInfo rasterizationStateCreateInfo = {}; rasterizationStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; rasterizationStateCreateInfo.depthClampEnable = VK_FALSE; rasterizationStateCreateInfo.rasterizerDiscardEnable = VK_FALSE; rasterizationStateCreateInfo.polygonMode = VK_POLYGON_MODE_FILL; rasterizationStateCreateInfo.cullMode = VK_CULL_MODE_BACK_BIT; rasterizationStateCreateInfo.frontFace = VK_FRONT_FACE_CLOCKWISE; rasterizationStateCreateInfo.depthBiasEnable = VK_FALSE; rasterizationStateCreateInfo.lineWidth = 1.0f; VkPipelineMultisampleStateCreateInfo multisampleStateCreateInfo = {}; multisampleStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; multisampleStateCreateInfo.sampleShadingEnable = VK_FALSE; multisampleStateCreateInfo.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; VkPipelineColorBlendAttachmentState colorBlendAttachmentState = {}; colorBlendAttachmentState.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; colorBlendAttachmentState.blendEnable = VK_FALSE; VkPipelineColorBlendStateCreateInfo colorBlendStateCreateInfo = {}; colorBlendStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; colorBlendStateCreateInfo.logicOpEnable = VK_FALSE; colorBlendStateCreateInfo.attachmentCount = 1; colorBlendStateCreateInfo.pAttachments = &colorBlendAttachmentState; VkDynamicState dynamicStates[] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_LINE_WIDTH }; VkPipelineDynamicStateCreateInfo dynamicStateCreateInfo = {}; dynamicStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; dynamicStateCreateInfo.dynamicStateCount = 2; dynamicStateCreateInfo.pDynamicStates = dynamicStates; VkGraphicsPipelineCreateInfo pipelineCreateInfo = {}; pipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; pipelineCreateInfo.stageCount = 2; pipelineCreateInfo.pStages = shaderStages; pipelineCreateInfo.pVertexInputState = &vertexInputStateCreateInfo; pipelineCreateInfo.pInputAssemblyState = &inputAssemblyStateCreateInfo; pipelineCreateInfo.pViewportState = &viewportStateCreateInfo; pipelineCreateInfo.pRasterizationState = &rasterizationStateCreateInfo; pipelineCreateInfo.pMultisampleState = &multisampleStateCreateInfo; pipelineCreateInfo.pColorBlendState = &colorBlendStateCreateInfo; pipelineCreateInfo.pDynamicState = &dynamicStateCreateInfo; pipelineCreateInfo.layout = pipelineLayout; pipelineCreateInfo.renderPass = renderPass; pipelineCreateInfo.subpass = 0; VkPipeline pipeline; if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineCreateInfo, NULL, &pipeline) != VK_SUCCESS) { printf("Failed to create Vulkan graphics pipeline\n"); return -1; } vkDestroyShaderModule(device, vertexShaderModule, NULL); vkDestroyShaderModule(device, fragmentShaderModule, NULL); // 创建Vulkan帧缓冲 VkImageView* swapchainImageViews = (VkImageView*)malloc(swapchainImageCount * sizeof(VkImageView)); for (uint32_t i = 0; i < swapchainImageCount; i++) { VkImageViewCreateInfo imageViewCreateInfo = {}; imageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; imageViewCreateInfo.image = swapchainImages[i]; imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; imageViewCreateInfo.format = surfaceFormat.format; imageViewCreateInfo.components = { VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY }; imageViewCreateInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; imageViewCreateInfo.subresourceRange.baseMipLevel = 0; imageViewCreateInfo.subresourceRange.levelCount = 1; imageViewCreateInfo.subresourceRange.baseArrayLayer = 0; imageViewCreateInfo.subresourceRange.layerCount = 1; if (vkCreateImageView(device, &imageViewCreateInfo, NULL, &swapchainImageViews[i]) != VK_SUCCESS) { printf("Failed to create Vulkan image view\n"); return -1; } } VkFramebuffer* framebuffers = (VkFramebuffer*)malloc(swapchainImageCount * sizeof(VkFramebuffer)); for (uint32_t i = 0; i < swapchainImageCount; i++) { VkFramebufferCreateInfo framebufferCreateInfo = {}; framebufferCreateInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; framebufferCreateInfo.renderPass = renderPass; framebufferCreateInfo.attachmentCount = 1; framebufferCreateInfo.pAttachments = &swapchainImageViews[i]; framebufferCreateInfo.width = WIDTH; framebufferCreateInfo.height = HEIGHT; framebufferCreateInfo.layers = 1; if (vkCreateFramebuffer(device, &framebufferCreateInfo, NULL, &framebuffers[i]) != VK_SUCCESS) { printf("Failed to create Vulkan framebuffer\n"); return -1; } } // 创建Vulkan命令池 VkCommandPool commandPool; VkCommandPoolCreateInfo commandPoolCreateInfo = {}; commandPoolCreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; commandPoolCreateInfo
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值