documentation

This commit is contained in:
Jorijn van der Graaf 2025-06-13 23:59:36 +02:00
commit 3275eb2f70
135 changed files with 15649 additions and 430 deletions

View file

@ -0,0 +1,63 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include <cstdint>
export module Crafter.Graphics:Camera;
import :VulkanBuffer;
import Crafter.Math;
import Crafter.Event;
namespace Crafter {
/**
* @brief 3D camera with projection and view matrices
* @example examples/VulkanCube/main.cpp
*/
export class Camera {
public:
MatrixRowMajor<float, 4, 4, 1> projection;
MatrixRowMajor<float, 4, 4, 1> view;
MatrixRowMajor<float, 4, 4, 1> projectionView;
Event<void> onUpdate;
/**
* @param fov Field of view in radians.
* @param aspectRatio Aspect ratio of the camera (width / height).
* @param near Near clipping plane.
* @param far Far clipping plane.
* @example examples/VulkanCube/main.cpp
*/
Camera(float fov, float aspectRatio, float near, float far);
/**
* @brief calculates the projectionView matrix by multiplying the projection and view matricies.
*/
void Update();
/**
* @brief Converts screen-space coordinates to a 3D world-space ray.
* @param x The x-coordinate on the screen (in pixels).
* @param y The y-coordinate on the screen (in pixels).
* @return A normalized 3D direction vector representing the ray from the camera.
*/
Vector<float, 3> ToRay(uint32_t x, uint32_t y);
};
}

View file

@ -0,0 +1,166 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include <cstdint>
#include <vulkan/vulkan.h>
#include <cstring>
#include <iostream>
#include <vector>
#include "../../lib/VulkanInitializers.hpp"
export module Crafter.Graphics:DescriptorSet;
import Crafter.Event;
import :VulkanDevice;
import :VulkanShader;
import :WindowWaylandVulkan;
import :VulkanPipeline;
namespace Crafter {
export struct DescriptorEntry {
VkDescriptorType type;
bool occured = true;
};
export template <typename MeshShader, typename FragmentShader>
class DescriptorSet {
public:
VkDescriptorSet set[2];
inline static Event<void> onDescriptorRefresh;
inline static std::vector<DescriptorSet*> sets;
inline static VkDescriptorPool descriptorPool = VK_NULL_HANDLE;
consteval static std::uint32_t GetUniqueDiscriptorCount() {
DescriptorEntry types[] = {{VK_DESCRIPTOR_TYPE_SAMPLER, 0},{VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0},{VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 0},{VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 0},{VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, 0},{VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, 0},{VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0},{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 0},{VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 0},{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, 0},{VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 0},{VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK, 0},{VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR, 0},{VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV, 0},{VK_DESCRIPTOR_TYPE_SAMPLE_WEIGHT_IMAGE_QCOM, 0},{VK_DESCRIPTOR_TYPE_BLOCK_MATCH_IMAGE_QCOM, 0},{VK_DESCRIPTOR_TYPE_MUTABLE_EXT, 0},{VK_DESCRIPTOR_TYPE_PARTITIONED_ACCELERATION_STRUCTURE_NV, 0},{VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT, 0},{VK_DESCRIPTOR_TYPE_MUTABLE_VALVE, 0}};
for(const DescriptorBinding& binding : MeshShader::descriptors) {
for(DescriptorEntry& type : types) {
if(type.type == binding.type) {
type.occured = true;
}
}
}
for(const DescriptorBinding& binding : FragmentShader::descriptors) {
for(DescriptorEntry& type : types) {
if(type.type == binding.type) {
type.occured = true;
}
}
}
std::uint32_t size = 0;
for(DescriptorEntry& type : types) {
if(type.occured) {
size++;
}
}
return size;
}
constexpr static std::uint32_t uniqueDescriptorCount = GetUniqueDiscriptorCount();
consteval static std::array<VkDescriptorPoolSize, uniqueDescriptorCount> GetPoolSizes() {
std::array<VkDescriptorPoolSize, uniqueDescriptorCount> types = {};
for(std::uint32_t i = 0; i < uniqueDescriptorCount; i++){
types[i].descriptorCount = 12345;
}
for(const DescriptorBinding& binding : MeshShader::descriptors) {
bool found = false;
for(VkDescriptorPoolSize& type : types) {
if(type.type == binding.type && type.descriptorCount != 12345) {
type.descriptorCount += 1;
found = true;
}
}
if(!found) {
for(std::uint32_t i = 0; i < uniqueDescriptorCount; i++){
if(types[i].descriptorCount == 12345) {
types[i].type = binding.type;
types[i].descriptorCount = 1;
break;
}
}
}
}
for(const DescriptorBinding& binding : FragmentShader::descriptors) {
bool found = false;
for(VkDescriptorPoolSize& type : types) {
if(type.type == binding.type) {
type.descriptorCount += 1;
found = true;
}
}
if(!found) {
for(std::uint32_t i = 0; i < uniqueDescriptorCount; i++){
if(types[i].descriptorCount == 12345) {
types[i].type = binding.type;
types[i].descriptorCount = 1;
break;
}
}
}
}
return types;
}
DescriptorSet() {
sets.push_back(this);
if(descriptorPool != VK_NULL_HANDLE) {
vkDestroyDescriptorPool(VulkanDevice::device, descriptorPool, nullptr);
}
std::array<VkDescriptorPoolSize, uniqueDescriptorCount> poolSizes = GetPoolSizes();
for(VkDescriptorPoolSize& size : poolSizes) {
size.descriptorCount *= sets.size();
}
VkDescriptorPoolCreateInfo descriptorPoolInfo = vks::initializers::descriptorPoolCreateInfo(uniqueDescriptorCount, poolSizes.data(), sets.size()*2);
VulkanDevice::CHECK_VK_RESULT(vkCreateDescriptorPool(VulkanDevice::device, &descriptorPoolInfo, nullptr, &descriptorPool));
for(DescriptorSet* set : sets) {
VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorPool, &VulkanPipeline<MeshShader, FragmentShader>::descriptorSetLayout[0], 2);
VulkanDevice::CHECK_VK_RESULT(vkAllocateDescriptorSets(VulkanDevice::device, &allocInfo, set->set));
}
onDescriptorRefresh.Invoke();
}
~DescriptorSet() {
sets.erase(find(sets.begin(), sets.end(), this));
}
// void Write(VkWriteDescriptorSet* descriptors, std::uint32_t count) {
// vkUpdateDescriptorSets(VulkanDevice::device, count, descriptors, 0, nullptr);
// }
// void Write(std::uint32_t stage, VkDescriptorType type, std::uint32_t binding, VkDescriptorBufferInfo* buffer) {
// VkWriteDescriptorSet write = vks::initializers::writeDescriptorSet(set[stage], type, binding, buffer);
// vkUpdateDescriptorSets(VulkanDevice::device, 1, &write, 0, nullptr);
// }
// void Write(std::uint32_t stage, VkDescriptorType type, std::uint32_t binding, VkDescriptorImageInfo* buffer) {
// VkWriteDescriptorSet write = vks::initializers::writeDescriptorSet(set[stage], type, binding, buffer);
// vkUpdateDescriptorSets(VulkanDevice::device, 1, &write, 0, nullptr);
// }
};
}

View file

@ -0,0 +1,73 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include <cstdint>
#include <vulkan/vulkan.h>
#include <cstring>
#include <iostream>
#include <cmath>
#include "../../lib/VulkanInitializers.hpp"
export module Crafter.Graphics:HeightmapShader;
import :Camera;
import :VulkanPipeline;
import :DescriptorSet;
import Crafter.Math;
namespace Crafter {
struct HeightMapData {
MatrixRowMajor<float, 4, 4, 1> mvp;
uint32_t stride;
float spacing;
uint32_t padding[14];
};
export template <typename VertexType>
class HeightmapShader {
public:
MatrixRowMajor<float, 4, 4, 1> transform;
Camera* camera;
Buffer<HeightMapData> data;
Buffer<VertexType> heights;
std::uint32_t threadCount;
EventListener<void> cameraUpdate;
HeightmapShader(uint32_t amount, uint32_t stride, float spacing, Camera* camera) : threadCount(amount), heights(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, amount * 4 * 64), data(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT), camera(camera), cameraUpdate(
&camera->onUpdate, [this](){
Update();
}
) {
data.value->stride = stride;
data.value->spacing = spacing;
transform = MatrixRowMajor<float, 4, 4, 1>::Identity();
}
void WriteDescriptors(VkDescriptorSet set) {
VkWriteDescriptorSet write[2] = {
vks::initializers::writeDescriptorSet(set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &data.descriptor),
vks::initializers::writeDescriptorSet(set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, &heights.descriptor)
};
vkUpdateDescriptorSets(VulkanDevice::device, 2, &write[0], 0, nullptr);
}
void Update() {
data.value->mvp = camera->projectionView*transform;
}
};
}

View file

@ -0,0 +1,132 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include <cstdint>
#include <vulkan/vulkan.h>
#include <cstring>
#include <iostream>
export module Crafter.Graphics:Mesh;
import Crafter.Math;
import :VulkanBuffer;
import :Types;
namespace Crafter {
export template <typename VertexType>
class Mesh {
public:
std::uint32_t vertexCount;
std::uint32_t indexCount;
Buffer<VertexType> verticies;
Buffer<std::uint32_t> indicies;
Mesh(std::uint32_t vertexCount, std::uint32_t indexCount) : vertexCount(vertexCount), indexCount(indexCount), verticies(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, vertexCount), indicies(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, indexCount) {
}
Mesh(const char* asset) requires(std::same_as<VertexType, Vertex>) : vertexCount(reinterpret_cast<const std::uint32_t*>(asset)[0]), indexCount(((reinterpret_cast<const std::uint32_t*>(asset)[1]) + 63) & ~63), verticies(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, vertexCount), indicies(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, indexCount) {
uint32_t indexCountNoPadding = reinterpret_cast<const std::uint32_t*>(asset)[1];
const float* verticies = reinterpret_cast<const float*>(asset+sizeof(std::uint32_t)*2);
std::uint32_t counter = 0;
for(std::uint32_t i = 0; i < vertexCount*3; i+=3) {
this->verticies.value[counter].x = verticies[i];
this->verticies.value[counter].y = verticies[i+1];
this->verticies.value[counter].z = verticies[i+2];
this->verticies.value[counter].w = 1.0f;
counter++;
}
memcpy(indicies.value, asset+(sizeof(std::uint32_t)*2)+(vertexCount*sizeof(float)*3), indexCountNoPadding*sizeof(std::uint32_t));
for(std::uint32_t i = indexCountNoPadding; i < indexCountNoPadding+(indexCountNoPadding%64); i++) {
indicies.value[i] = 0;//pad indicies to nearest 64
}
}
Mesh(const char* asset) requires(std::same_as<VertexType, VertexUV>) : vertexCount(reinterpret_cast<const std::uint32_t*>(asset)[0]), indexCount(((reinterpret_cast<const std::uint32_t*>(asset)[1]) + 63) & ~63), verticies(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, vertexCount), indicies(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, indexCount) {
uint32_t indexCountNoPadding = reinterpret_cast<const std::uint32_t*>(asset)[1];
const float* verticies = reinterpret_cast<const float*>(asset+sizeof(std::uint32_t)*2);
std::uint32_t counter = 0;
for(std::uint32_t i = 0; i < vertexCount*5; i+=5) {
this->verticies.value[counter].x = verticies[i];
this->verticies.value[counter].y = verticies[i+1];
this->verticies.value[counter].z = verticies[i+2];
this->verticies.value[counter].u = verticies[i+3];
this->verticies.value[counter].v = verticies[i+4];
this->verticies.value[counter].w = 1.0f;
counter++;
}
memcpy(indicies.value, asset+(sizeof(std::uint32_t)*2)+(vertexCount*sizeof(float)*5), indexCountNoPadding*sizeof(std::uint32_t));
for(std::uint32_t i = indexCountNoPadding; i < indexCountNoPadding+(indexCountNoPadding%64); i++) {
indicies.value[i] = 0;//pad indicies to nearest 64
}
}
Mesh(float* heights, uint32_t sizeX, uint32_t sizeZ, float spacing) : vertexCount(sizeX*sizeZ), indexCount(((((sizeX-1)*(sizeZ-1))*6)+ 63) & ~63), verticies(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, vertexCount), indicies(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, indexCount) {
uint32_t indexCountNoPadding = ((sizeX-1)*(sizeZ-1))*6;
for (float x = 0; x < sizeX; x++)
{
for (float z = 0; z < sizeZ; z++)
{
uint32_t xInt = static_cast<uint32_t>(x);
uint32_t zInt = static_cast<uint32_t>(z);
Vector<float, 3> pos((x * spacing) - ((sizeX*spacing) / 2.0f), heights[xInt * sizeX + zInt], (z * spacing) - ((sizeZ*spacing) / 2.0f));
Vector<float, 2> uv(x / sizeX, z / sizeZ);
VertexType vertex;
vertex.x = pos.x;
vertex.y = pos.y;
vertex.z = pos.z;
vertex.w = 1.0f;
vertex.u = uv.x;
vertex.v = uv.y;
verticies.value[xInt * sizeX + zInt] = vertex;
}
}
for (uint32_t x = 0; x < sizeX - 1; x++)
{
for (uint32_t z = 0; z < sizeZ - 1; z++)
{
uint32_t topLeftIndex = x * sizeZ + z;
uint32_t topRightIndex = topLeftIndex + 1;
uint32_t bottomLeftIndex = topLeftIndex + sizeZ;
uint32_t bottomRightIndex = bottomLeftIndex + 1;
uint32_t index = (x * sizeX + z)*6;
indicies.value[index] = topRightIndex;
indicies.value[index + 1] = bottomLeftIndex;
indicies.value[index + 2] = topLeftIndex;
indicies.value[index + 3] = bottomRightIndex;
indicies.value[index + 4] = bottomLeftIndex;
indicies.value[index + 5] = topRightIndex;
}
}
for(std::uint32_t i = indexCountNoPadding; i < indexCountNoPadding+(indexCountNoPadding%64); i++) {
indicies.value[i] = 0;//pad indicies to nearest 64
}
}
};
}

View file

@ -0,0 +1,70 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include <cstdint>
#include <vulkan/vulkan.h>
#include <cstring>
#include <iostream>
#include <cmath>
#include "../../lib/VulkanInitializers.hpp"
export module Crafter.Graphics:MeshShader;
import :Mesh;
import :Camera;
import :VulkanPipeline;
import :DescriptorSet;
import Crafter.Math;
namespace Crafter {
export template <typename VertexType>
class MeshShader {
public:
MatrixRowMajor<float, 4, 4, 1> transform;
Mesh<VertexType>* mesh;
Camera* camera;
Buffer<MatrixRowMajor<float, 4, 4, 1>> mvp;
std::uint32_t threadCount;
EventListener<void> cameraUpdate;
MeshShader(Mesh<VertexType>* mesh) : threadCount(std::ceil(static_cast<double>(mesh->indexCount)/64/3)), mvp(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT), mesh(mesh), camera(nullptr) {
transform = MatrixRowMajor<float, 4, 4, 1>::Identity();
*mvp.value = MatrixRowMajor<float, 4, 4, 1>::Identity();
}
MeshShader(Mesh<VertexType>* mesh, Camera* camera) : threadCount(std::ceil(static_cast<double>(mesh->indexCount)/64/3)), mvp(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT), mesh(mesh), camera(camera), cameraUpdate(
&camera->onUpdate, [this](){
Update();
}
) {
transform = MatrixRowMajor<float, 4, 4, 1>::Identity();
}
void WriteDescriptors(VkDescriptorSet set) {
VkWriteDescriptorSet write[3] = {
vks::initializers::writeDescriptorSet(set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &mvp.descriptor),
vks::initializers::writeDescriptorSet(set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, &mesh->verticies.descriptor),
vks::initializers::writeDescriptorSet(set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 2, &mesh->indicies.descriptor)
};
vkUpdateDescriptorSets(VulkanDevice::device, 3, &write[0], 0, nullptr);
}
void Update() {
*mvp.value = camera->projectionView*transform;
}
};
}

View file

@ -0,0 +1,70 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include <cstdint>
#include <vulkan/vulkan.h>
#include <cstring>
#include <iostream>
#include "../../lib/VulkanInitializers.hpp"
export module Crafter.Graphics:TextureShader;
import :VulkanTexture;
import :VulkanPipeline;
import :DescriptorSet;
namespace Crafter {
export template <typename PixelType>
class TextureShader {
public:
VkSampler textureSampler;
VkDescriptorImageInfo imageInfo;
VulkanTexture<PixelType>* texture;
TextureShader(VulkanTexture<PixelType>* texture) : texture(texture) {
VkSamplerCreateInfo samplerInfo{};
samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
samplerInfo.magFilter = VK_FILTER_LINEAR;
samplerInfo.minFilter = VK_FILTER_LINEAR;
samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.anisotropyEnable = VK_FALSE;
samplerInfo.maxAnisotropy = 1;
samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
samplerInfo.unnormalizedCoordinates = VK_FALSE;
samplerInfo.compareEnable = VK_FALSE;
samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
samplerInfo.mipLodBias = 0.0f;
samplerInfo.minLod = 0.0f;
samplerInfo.maxLod = 0.0f;
VulkanDevice::CHECK_VK_RESULT(vkCreateSampler(VulkanDevice::device, &samplerInfo, nullptr, &textureSampler));
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->imageView;
imageInfo.sampler = textureSampler;
}
void WriteDescriptors(VkDescriptorSet set) {
VkWriteDescriptorSet write = vks::initializers::writeDescriptorSet(set, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, &imageInfo);
vkUpdateDescriptorSets(VulkanDevice::device, 1, &write, 0, nullptr);
}
};
}

View file

@ -0,0 +1,93 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include <cstdint>
export module Crafter.Graphics:Types;
namespace Crafter {
export struct MousePoint {
double x;
double y;
};
export struct MouseMoveEvent {
MousePoint lastMousePos;
MousePoint currentMousePos;
MousePoint mouseDelta;
};
export struct __attribute__((packed)) Pixel_BU8_GU8_RU8_AU8 {
std::uint8_t b;
std::uint8_t g;
std::uint8_t r;
std::uint8_t a;
};
export struct __attribute__((packed)) Pixel_RU8_GU8_BU8_AU8 {
std::uint8_t r;
std::uint8_t g;
std::uint8_t b;
std::uint8_t a;
};
export struct __attribute__((packed)) Vertex {
float x;
float y;
float z;
float w;
};
export struct __attribute__((packed)) VertexUV {
float x;
float y;
float z;
float w;
float u;
float v;
float pad[2];
};
export struct __attribute__((packed)) VertexRGBA {
float x;
float y;
float z;
float w;
float r;
float g;
float b;
float a;
};
export struct __attribute__((packed)) HeightRGBA {
float height;
float pad[3];
float r;
float g;
float b;
float a;
};
}

View file

@ -0,0 +1,60 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include <cstdint>
#include <vector>
export module Crafter.Graphics:UiElement;
import Crafter.Event;
import :Types;
export namespace Crafter {
class UiElement {
public:
Event<MouseMoveEvent> onMouseMove;
Event<MouseMoveEvent> onMouseEnter;
Event<MouseMoveEvent> onMouseLeave;
Event<MousePoint> onMouseRightClick;
Event<MousePoint> onMouseLeftClick;
Event<MousePoint> onMouseRightHold;
Event<MousePoint> onMouseLeftHold;
Event<MousePoint> onMouseRightRelease;
Event<MousePoint> onMouseLeftRelease;
float z;
float anchorX;
float anchorY;
bool useRelativeSize;
bool ignoreScaling;
std::uint32_t bufferWidth;
std::uint32_t bufferHeight;
std::uint32_t absoluteWidth;
std::uint32_t absoluteHeight;
float relativeWidth;
float relativeHeight;
float anchorOffsetX;
float anchorOffsetY;
std::vector<Pixel_BU8_GU8_RU8_AU8> buffer;
std::vector<UiElement> children;
UiElement(float anchorX, float anchorY, std::uint32_t bufferWidth, std::uint32_t bufferHeight, std::uint32_t absoluteWidth, std::uint32_t absoluteHeight, float anchorOffsetX = 0.5, float anchorOffsetY = 0.5, float z = 0, bool ignoreScaling = false);
UiElement(float anchorX, float anchorY, std::uint32_t bufferWidth, std::uint32_t bufferHeight, float relativeWidth, float relativeHeight, float anchorOffsetX = 0.5, float anchorOffsetY = 0.5, float z = 0, bool ignoreScaling = false);
};
}

View file

@ -0,0 +1,75 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include <cstdint>
#include <vulkan/vulkan.h>
#include <cstring>
#include <iostream>
#include <cmath>
#include "../../lib/VulkanInitializers.hpp"
export module Crafter.Graphics:VoxelShader;
import :Mesh;
import :Camera;
import :VulkanPipeline;
import :DescriptorSet;
import Crafter.Math;
namespace Crafter {
export struct VoxelShaderData {
MatrixRowMajor<float, 4, 4, 1> mvp;
uint32_t sizeX;
uint32_t sizeY;
uint32_t sizeZ;
};
export template <typename VoxelType>
class VoxelShader {
public:
MatrixRowMajor<float, 4, 4, 1> transform;
Camera* camera;
Buffer<VoxelType> grid;
Buffer<VoxelShaderData> data;
std::uint32_t threadCount;
EventListener<void> cameraUpdate;
VoxelShader(uint32_t sizeX, uint32_t sizeY, uint sizeZ, Camera* camera) : threadCount((sizeX*sizeY*sizeZ)/16), data(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT), grid(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, sizeX*sizeY*sizeZ) ,camera(camera), cameraUpdate(
&camera->onUpdate, [this](){
Update();
}
) {
transform = MatrixRowMajor<float, 4, 4, 1>::Identity();
data.value->sizeX = sizeX;
data.value->sizeY = sizeY;
data.value->sizeZ = sizeZ;
}
void WriteDescriptors(VkDescriptorSet set) {
VkWriteDescriptorSet write[2] = {
vks::initializers::writeDescriptorSet(set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &data.descriptor),
vks::initializers::writeDescriptorSet(set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, &grid.descriptor),
};
vkUpdateDescriptorSets(VulkanDevice::device, 2, &write[0], 0, nullptr);
}
void Update() {
data.value->mvp = camera->projectionView*transform;
}
};
}

View file

@ -0,0 +1,79 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include <cstdint>
#include <vulkan/vulkan.h>
#include "../../lib/VulkanInitializers.hpp"
export module Crafter.Graphics:VulkanBuffer;
import :VulkanDevice;
namespace Crafter {
export template <typename T>
class Buffer {
public:
T* value;
VkDescriptorBufferInfo descriptor;
VkBuffer buffer = VK_NULL_HANDLE;
VkDeviceMemory memory = VK_NULL_HANDLE;
Buffer(VkBufferUsageFlags usageFlags, VkMemoryPropertyFlags memoryPropertyFlags, std::uint32_t count = 1) {
VkBufferCreateInfo bufferCreateInfo = vks::initializers::bufferCreateInfo(usageFlags, sizeof(T)*count);
VulkanDevice::CHECK_VK_RESULT(vkCreateBuffer(VulkanDevice::device, &bufferCreateInfo, nullptr, &buffer));
// Create the memory backing up the buffer handle
VkMemoryRequirements memReqs;
VkMemoryAllocateInfo memAlloc = vks::initializers::memoryAllocateInfo();
vkGetBufferMemoryRequirements(VulkanDevice::device, buffer, &memReqs);
memAlloc.allocationSize = memReqs.size;
// Find a memory type index that fits the properties of the buffer
memAlloc.memoryTypeIndex = VulkanDevice::GetMemoryType(memReqs.memoryTypeBits, memoryPropertyFlags);
// If the buffer has VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT set we also need to enable the appropriate flag during allocation
VkMemoryAllocateFlagsInfoKHR allocFlagsInfo{};
if (usageFlags & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) {
allocFlagsInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO_KHR;
allocFlagsInfo.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT_KHR;
memAlloc.pNext = &allocFlagsInfo;
}
VulkanDevice::CHECK_VK_RESULT(vkAllocateMemory(VulkanDevice::device, &memAlloc, nullptr, &memory));
alignment = memReqs.alignment;
usageFlags = usageFlags;
memoryPropertyFlags = memoryPropertyFlags;
descriptor.offset = 0;
descriptor.buffer = buffer;
descriptor.range = sizeof(T)*count;
VulkanDevice::CHECK_VK_RESULT(vkBindBufferMemory(VulkanDevice::device, buffer, memory, 0));
VulkanDevice::CHECK_VK_RESULT(vkMapMemory(VulkanDevice::device, memory, 0, sizeof(T)*count, 0, reinterpret_cast<void**>(&value)));
}
~Buffer() {
vkUnmapMemory(VulkanDevice::device, memory);
vkDestroyBuffer(VulkanDevice::device, buffer, nullptr);
vkFreeMemory(VulkanDevice::device, memory, nullptr);
}
private:
VkDeviceSize alignment = 0;
VkMemoryPropertyFlags memoryPropertyFlags;
VkBufferUsageFlags usageFlags;
};
}

View file

@ -0,0 +1,49 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include <cstdint>
#include <vulkan/vulkan.h>
#include <vulkan/vulkan_wayland.h>
export module Crafter.Graphics:VulkanDevice;
export namespace Crafter {
class VulkanDevice {
public:
inline static VkInstance instance = VK_NULL_HANDLE;
inline static VkDebugUtilsMessengerEXT debugMessenger = VK_NULL_HANDLE;
inline static VkPhysicalDevice physDevice = VK_NULL_HANDLE;
inline static VkDevice device = VK_NULL_HANDLE;
inline static std::uint32_t queueFamilyIndex = 0;
inline static VkQueue queue = VK_NULL_HANDLE;
inline static VkCommandPool commandPool = VK_NULL_HANDLE;
inline static VkSwapchainKHR swapchain = VK_NULL_HANDLE;
inline static PFN_vkCmdDrawMeshTasksEXT vkCmdDrawMeshTasksEXTProc;
inline static PFN_vkCmdBeginRenderingKHR vkCmdBeginRenderingKHRProc;
inline static PFN_vkCmdEndRenderingKHR vkCmdEndRenderingKHRProc;
inline static VkPhysicalDeviceMemoryProperties memoryProperties;
inline static VkFormat depthFormat = VK_FORMAT_UNDEFINED;
static void CreateDevice();
static void CHECK_VK_RESULT(VkResult result);
static std::uint32_t GetMemoryType(std::uint32_t typeBits, VkMemoryPropertyFlags properties);
};
}

View file

@ -0,0 +1,124 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include <cstdint>
#include <vulkan/vulkan.h>
#include <array>
#include "../../lib/VulkanInitializers.hpp"
#include <unordered_map>
export module Crafter.Graphics:VulkanPipeline;
import :VulkanDevice;
import :VulkanShader;
import :WindowWaylandVulkan;
namespace Crafter {
export template <typename MeshShader, typename FragmentShader>
class VulkanPipeline {
private:
template <typename Shader, VkShaderStageFlagBits Flag>
consteval static std::array<VkDescriptorSetLayoutBinding, Shader::descriptorCount> GetDescriptorSet() {
std::array<VkDescriptorSetLayoutBinding, Shader::descriptorCount> set;
for(std::uint32_t i = 0; i < Shader::descriptors.size(); i++) {
set[i] = {Shader::descriptors[i].slot, Shader::descriptors[i].type, 1, Flag, nullptr};
}
return set;
}
public:
inline static VkPipeline pipeline;
inline static VkPipelineLayout pipelineLayout;
inline static VkDescriptorSetLayout descriptorSetLayout[2];
static void CreatePipeline() {
// Layout
constexpr std::array<VkDescriptorSetLayoutBinding, MeshShader::descriptorCount> setLayoutBindingsMesh = GetDescriptorSet<MeshShader, VK_SHADER_STAGE_MESH_BIT_EXT>();
VkDescriptorSetLayoutCreateInfo descriptorLayoutInfoMesh = vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindingsMesh.data(), MeshShader::descriptorCount);
VulkanDevice::CHECK_VK_RESULT(vkCreateDescriptorSetLayout(VulkanDevice::device, &descriptorLayoutInfoMesh, nullptr, &descriptorSetLayout[0]));
constexpr std::array<VkDescriptorSetLayoutBinding, FragmentShader::descriptorCount> setLayoutBindingsFragment = GetDescriptorSet<FragmentShader, VK_SHADER_STAGE_FRAGMENT_BIT>();
VkDescriptorSetLayoutCreateInfo descriptorLayoutInfoFragment = vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindingsFragment.data(), FragmentShader::descriptorCount);
VulkanDevice::CHECK_VK_RESULT(vkCreateDescriptorSetLayout(VulkanDevice::device, &descriptorLayoutInfoFragment, nullptr, &descriptorSetLayout[1]));
// Layout
VkPipelineLayoutCreateInfo pipelineLayoutInfo = vks::initializers::pipelineLayoutCreateInfo(&descriptorSetLayout[0], 2);
VulkanDevice::CHECK_VK_RESULT(vkCreatePipelineLayout(VulkanDevice::device, &pipelineLayoutInfo, nullptr, &pipelineLayout));
// Pipeline
VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vks::initializers::pipelineInputAssemblyStateCreateInfo(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE);
VkPipelineRasterizationStateCreateInfo rasterizationState = vks::initializers::pipelineRasterizationStateCreateInfo(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_CLOCKWISE, 0);
VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE);
VkPipelineColorBlendStateCreateInfo colorBlendState = vks::initializers::pipelineColorBlendStateCreateInfo(1, &blendAttachmentState);
VkPipelineDepthStencilStateCreateInfo depthStencilState = vks::initializers::pipelineDepthStencilStateCreateInfo(VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS_OR_EQUAL);
VkPipelineViewportStateCreateInfo viewportState = vks::initializers::pipelineViewportStateCreateInfo(1, 1, 0);
VkPipelineMultisampleStateCreateInfo multisampleState = vks::initializers::pipelineMultisampleStateCreateInfo(VK_SAMPLE_COUNT_1_BIT, 0);
std::vector<VkDynamicState> dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };
VkPipelineDynamicStateCreateInfo dynamicState = vks::initializers::pipelineDynamicStateCreateInfo(dynamicStateEnables);
std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages;
VkFormat format = VK_FORMAT_R8G8B8A8_UNORM;
VkPipelineRenderingCreateInfoKHR pipeline_create{VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR};
pipeline_create.pNext = VK_NULL_HANDLE;
pipeline_create.colorAttachmentCount = 1;
pipeline_create.pColorAttachmentFormats = &format;
pipeline_create.depthAttachmentFormat = VulkanDevice::depthFormat;
VkGraphicsPipelineCreateInfo pipelineCI = vks::initializers::pipelineCreateInfo(pipelineLayout, VK_NULL_HANDLE, 0);
pipelineCI.pNext = &pipeline_create;
pipelineCI.pRasterizationState = &rasterizationState;
pipelineCI.pColorBlendState = &colorBlendState;
pipelineCI.pMultisampleState = &multisampleState;
pipelineCI.pViewportState = &viewportState;
pipelineCI.pDepthStencilState = &depthStencilState;
pipelineCI.pDynamicState = &dynamicState;
pipelineCI.stageCount = static_cast<uint32_t>(shaderStages.size());
pipelineCI.pStages = shaderStages.data();
// Not using a vertex shader, mesh shading doesn't require vertex input state
pipelineCI.pInputAssemblyState = nullptr;
pipelineCI.pVertexInputState = nullptr;
//Mesh stage of the pipeline
shaderStages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
shaderStages[0].stage = MeshShader::_stage;
shaderStages[0].module = MeshShader::shader;
shaderStages[0].pName = MeshShader::_entrypoint.value;
shaderStages[0].flags = 0;
shaderStages[0].pSpecializationInfo = nullptr;
shaderStages[0].pNext = nullptr;
// Fragment stage of the pipeline
shaderStages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
shaderStages[1].stage = FragmentShader::_stage;
shaderStages[1].module = FragmentShader::shader;
shaderStages[1].pName = FragmentShader::_entrypoint.value;
shaderStages[1].flags = 0;
shaderStages[1].pSpecializationInfo = nullptr;
shaderStages[1].pNext = nullptr;
VulkanDevice::CHECK_VK_RESULT(vkCreateGraphicsPipelines(VulkanDevice::device, VK_NULL_HANDLE, 1, &pipelineCI, nullptr, &pipeline));
}
};
}

View file

@ -0,0 +1,91 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include <iostream>
#include <algorithm>
#include <vulkan/vulkan.h>
#include <fstream>
#include <cstdint>
#include <vector>
#include <array>
export module Crafter.Graphics:VulkanShader;
import :VulkanDevice;
namespace Crafter {
export template<size_t N>
struct StringLiteral {
constexpr StringLiteral(const char (&str)[N]) {
std::copy_n(str, N, value);
}
char value[N];
};
export struct DescriptorBinding {
VkDescriptorType type;
std::uint32_t slot;
};
export template <
StringLiteral path,
StringLiteral entrypoint,
VkShaderStageFlagBits stage,
std::uint32_t DescriptorCount,
const std::array<DescriptorBinding, DescriptorCount> Descriptors
>
class VulkanShader {
public:
inline static VkShaderModule shader;
constexpr static std::uint32_t descriptorCount = DescriptorCount;
constexpr static std::array<DescriptorBinding, DescriptorCount> descriptors = Descriptors;
constexpr static StringLiteral _entrypoint = entrypoint;
constexpr static VkShaderStageFlagBits _stage = stage;
static void CreateShader() {
std::ifstream file(path.value, std::ios::binary);
if (!file) {
std::cerr << "Error: Could not open file " << path.value << std::endl;
}
// Move to the end of the file to determine its size
file.seekg(0, std::ios::end);
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<std::uint32_t> spirv(size / sizeof(std::uint32_t));
// Read the data into the vector
if (!file.read(reinterpret_cast<char*>(spirv.data()), size)) {
std::cerr << "Error: Could not read data from file" << std::endl;
}
file.close();
VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
module_info.codeSize = spirv.size() * sizeof(uint32_t);
module_info.pCode = spirv.data();
VkShaderModule shader_module;
VulkanDevice::CHECK_VK_RESULT(vkCreateShaderModule(VulkanDevice::device, &module_info, nullptr, &shader));
}
};
}

View file

@ -0,0 +1,176 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include <cstdint>
#include <vulkan/vulkan.h>
#include <cstring>
#include <iostream>
export module Crafter.Graphics:VulkanTexture;
import :VulkanDevice;
import :VulkanBuffer;
namespace Crafter {
export template <typename PixelType>
class VulkanTexture {
public:
uint32_t width;
uint32_t height;
VkImage image;
VkDeviceMemory imageMemory;
Buffer<PixelType> buffer;
VkImageView imageView;
VulkanTexture(std::uint32_t width, std::uint32_t height, VkCommandBuffer cmd) : width(width), height(height), buffer(VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, width*height) {
VkImageCreateInfo imageInfo{};
imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
imageInfo.imageType = VK_IMAGE_TYPE_2D;
imageInfo.extent.width = width;
imageInfo.extent.height = height;
imageInfo.extent.depth = 1;
imageInfo.mipLevels = 1;
imageInfo.arrayLayers = 1;
imageInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
imageInfo.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
imageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VulkanDevice::CHECK_VK_RESULT(vkCreateImage(VulkanDevice::device, &imageInfo, nullptr, &image));
VkMemoryRequirements memRequirements;
vkGetImageMemoryRequirements(VulkanDevice::device, image, &memRequirements);
VkMemoryAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = VulkanDevice::GetMemoryType(memRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
VulkanDevice::CHECK_VK_RESULT(vkAllocateMemory(VulkanDevice::device, &allocInfo, nullptr, &imageMemory));
vkBindImageMemory(VulkanDevice::device, image, imageMemory, 0);
VkImageViewCreateInfo viewInfo{};
viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
viewInfo.image = image;
viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
viewInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
viewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
viewInfo.subresourceRange.baseMipLevel = 0;
viewInfo.subresourceRange.levelCount = 1;
viewInfo.subresourceRange.baseArrayLayer = 0;
viewInfo.subresourceRange.layerCount = 1;
VulkanDevice::CHECK_VK_RESULT(vkCreateImageView(VulkanDevice::device, &viewInfo, nullptr, &imageView));
TransitionImageLayout(cmd, buffer, image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
}
VulkanTexture(const char* asset, VkCommandBuffer cmd) : VulkanTexture(reinterpret_cast<const std::uint32_t*>(asset)[0], reinterpret_cast<const std::uint32_t*>(asset)[1], cmd) {
Update(reinterpret_cast<const PixelType*>(reinterpret_cast<const std::uint32_t*>(asset)+2), cmd);
}
void Update(const PixelType* bufferdata, VkCommandBuffer cmd) {
memcpy(buffer.value, bufferdata, height*width*sizeof(PixelType));
TransitionImageLayout(cmd, buffer, image, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
VkBufferImageCopy region{};
region.bufferOffset = 0;
region.bufferRowLength = 0;
region.bufferImageHeight = 0;
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.mipLevel = 0;
region.imageSubresource.baseArrayLayer = 0;
region.imageSubresource.layerCount = 1;
region.imageOffset = {0, 0, 0};
region.imageExtent = { width, height, 1};
vkCmdCopyBufferToImage(
cmd,
buffer.buffer,
image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1,
&region
);
TransitionImageLayout(cmd, buffer, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
}
private:
void TransitionImageLayout(VkCommandBuffer cmd, Buffer<PixelType>& buffer, VkImage image, VkImageLayout oldLayout, VkImageLayout newLayout) {
VkImageMemoryBarrier barrier{};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.oldLayout = oldLayout;
barrier.newLayout = newLayout;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.levelCount = 1;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = 1;
barrier.srcAccessMask = 0;
barrier.dstAccessMask = 0;
VkPipelineStageFlags sourceStage;
VkPipelineStageFlags destinationStage;
if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
barrier.srcAccessMask = 0;
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
} else if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
barrier.srcAccessMask = 0;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
destinationStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
} else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
sourceStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
destinationStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
} else if (oldLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
sourceStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
} else {
throw std::invalid_argument("unsupported layout transition!");
}
vkCmdPipelineBarrier(
cmd,
sourceStage, destinationStage,
0,
0, nullptr,
0, nullptr,
1, &barrier
);
}
};
}

View file

@ -0,0 +1,74 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include <cstdint>
#include <string>
#include <vector>
export module Crafter.Graphics:Window;
import Crafter.Event;
import :UiElement;
import :Types;
export namespace Crafter {
struct ScaleData {
int32_t x;
int32_t y;
int32_t width;
int32_t height;
};
class Window {
public:
Event<MousePoint> onMouseRightClick;
Event<MousePoint> onMouseLeftClick;
Event<MousePoint> onMouseRightHold;
Event<MousePoint> onMouseLeftHold;
Event<MousePoint> onMouseRightRelease;
Event<MousePoint> onMouseLeftRelease;
Event<MouseMoveEvent> onMouseMove;
Event<MouseMoveEvent> onMouseEnter;
Event<MouseMoveEvent> onMouseLeave;
Event<double> onMouseScroll;
Event<void> onClose;
MousePoint currentMousePos;
MousePoint lastMousePos;
MousePoint mouseDelta;
bool mouseLeftHeld = false;
bool mouseRightHeld = false;
bool heldkeys[255] = {};
Event<void> onKeyDown[255];
Event<void> onKeyHold[255];
Event<void> onKeyUp[255];
Event<char> onAnyKeyDown;
Event<char> onAnyKeyHold;
Event<char> onAnyKeyUp;
std::vector<UiElement> elements;
std::string name;
std::uint32_t width;
std::uint32_t height;
float scale = 1;
bool open = true;
Window(std::string name, std::uint32_t width, std::uint32_t height);
ScaleData ScaleElement(const UiElement& element);
};
}

View file

@ -0,0 +1,69 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include <cstdint>
#include <string>
#include <wayland-client.h>
#include "../../lib/xdg-shell-client-protocol.h"
#include "../../lib/wayland-xdg-decoration-unstable-v1-client-protocol.h"
export module Crafter.Graphics:WindowWayland;
import Crafter.Event;
import :UiElement;
import :Types;
import :Window;
export namespace Crafter {
class WindowWayland : public Window {
public:
Pixel_BU8_GU8_RU8_AU8* framebuffer = NULL;
WindowWayland(std::string name, std::uint32_t width, std::uint32_t height);
~WindowWayland();
protected:
bool configured = false;
wl_shm* shm = NULL;
wl_seat* seat = NULL;
xdg_toplevel* xdgToplevel = NULL;
xdg_wm_base* xdgWmBase = NULL;
zxdg_decoration_manager_v1* manager = NULL;
wl_surface* surface = NULL;
wl_buffer* buffer = NULL;
xdg_surface* xdgSurface = NULL;
wl_display* display = NULL;
inline static wl_compositor* compositor = NULL;
static wl_pointer_listener pointer_listener;
static wl_keyboard_listener keyboard_listener;
static wl_seat_listener seat_listener;
static wl_registry_listener registry_listener;
static xdg_surface_listener xdg_surface_listener;
static xdg_toplevel_listener xdg_toplevel_listener;
static void PointerListenerHandleMotion(void* data, wl_pointer* wl_pointer, uint time, wl_fixed_t surface_x, wl_fixed_t surface_y);
static void PointerListenerHandleAxis(void*, wl_pointer*, std::uint32_t, std::uint32_t, wl_fixed_t value);
static void PointerListenerHandleEnter(void* data, wl_pointer* wl_pointer, uint serial, wl_surface* surface, wl_fixed_t surface_x, wl_fixed_t surface_y);
static void PointerListenerHandleLeave(void*, wl_pointer*, std::uint32_t, wl_surface*);
static void xdg_toplevel_handle_close(void* data, xdg_toplevel*);
static void handle_global(void* data, wl_registry* registry, std::uint32_t name, const char* interface, std::uint32_t version);
static void pointer_handle_button(void* data, wl_pointer* pointer, std::uint32_t serial, std::uint32_t time, std::uint32_t button, std::uint32_t state);
static void seat_handle_capabilities(void* data, wl_seat* seat, uint32_t capabilities);
static void xdg_surface_handle_configure(void* data, xdg_surface* xdg_surface, std::uint32_t serial);
};
}

View file

@ -0,0 +1,75 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include <cstdint>
#include <string>
#include <vulkan/vulkan.h>
#include <vulkan/vulkan_wayland.h>
#include <vector>
#include <thread>
export module Crafter.Graphics:WindowWaylandVulkan;
import Crafter.Event;
import :WindowWayland;
namespace Crafter {
struct DepthStencil {
VkImage image;
VkDeviceMemory memory;
VkImageView view;
};
struct Semaphores {
// Swap chain image presentation
VkSemaphore presentComplete;
// Command buffer submission and execution
VkSemaphore renderComplete;
};
export class WindowWaylandVulkan : public WindowWayland {
public:
Event<VkCommandBuffer> onDraw;
WindowWaylandVulkan(std::string name, std::uint32_t width, std::uint32_t height);
~WindowWaylandVulkan();
VkCommandBuffer StartInit();
void FinishInit();
void StartAsync();
void StartSync();
private:
void CreateSwapchain();
VkSurfaceKHR vulkanSurface = VK_NULL_HANDLE;
VkSwapchainKHR swapChain = VK_NULL_HANDLE;
VkFormat colorFormat;
VkColorSpaceKHR colorSpace;
std::vector<VkImage> images;
std::vector<VkImageView> imageViews;
std::thread thread;
std::vector<VkCommandBuffer> drawCmdBuffers;
std::vector<VkFramebuffer> frameBuffers;
VkSubmitInfo submitInfo;
DepthStencil depthStencil;
Semaphores semaphores;
uint32_t currentBuffer = 0;
VkPipelineStageFlags submitPipelineStages = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
VkRenderPass renderPass = VK_NULL_HANDLE;
};
}

View file

@ -0,0 +1,41 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include <cstdint>
#include <string>
#include <thread>
export module Crafter.Graphics:WindowWaylandWayland;
import Crafter.Event;
import :WindowWayland;
export namespace Crafter {
class WindowWaylandWayland : public WindowWayland {
public:
WindowWaylandWayland(std::string name, std::uint32_t width, std::uint32_t height);
~WindowWaylandWayland();
void StartAsync();
void StartSync();
private:
std::thread thread;
};
}

View file

@ -0,0 +1,40 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
export module Crafter.Graphics;
export import :Window;
export import :WindowWayland;
export import :WindowWaylandWayland;
export import :WindowWaylandVulkan;
export import :UiElement;
export import :Types;
export import :VulkanDevice;
export import :VulkanPipeline;
export import :VulkanShader;
export import :Camera;
export import :VulkanBuffer;
export import :VoxelShader;
export import :Mesh;
export import :MeshShader;
export import :VulkanTexture;
export import :TextureShader;
export import :DescriptorSet;
export import :HeightmapShader;

View file

@ -0,0 +1,28 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#version 450
layout(location = 0) out vec4 outFragColor;
void main()
{
outFragColor = vec4(1, 1, 1, 1);
}

View file

@ -0,0 +1,78 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#version 450
layout(location = 0) in vec2 fragUV;
layout(location = 0) out vec4 outColor;
layout(set = 1, binding = 0) uniform sampler2D texSampler;
void main()
{
outColor = texture(texSampler, fragUV);
}
/*
float getFilledAlpha(vec2 uv, vec2 center, float radius, float fillAmount) {
vec2 dir = uv - center;
float dist = length(dir);
// If outside the circle, return 0
if (dist > radius)
return 0.0;
// Normalize direction vector and compute angle
float angle = atan(dir.y, dir.x); // atan returns from -PI to PI
if (angle < 0.0) angle += 2.0 * 3.14159265359; // Convert to 0 to 2PI
float filledAngle = fillAmount * 2.0 * 3.14159265359;
// If the point is within the filled angle, return 1
if (angle <= filledAngle)
return 1.0;
return 0.0;
}
*/
/*
float getFilledAlphaAA(vec2 uv, vec2 center, float radius, float fillAmount, float edgeSoftness) {
vec2 dir = uv - center;
float dist = length(dir);
// If completely outside the circle, return 0
if (dist > radius + edgeSoftness)
return 0.0;
// Normalize direction vector and compute angle
float angle = atan(dir.y, dir.x); // -PI to PI
if (angle < 0.0) angle += 2.0 * 3.14159265359; // Convert to 0 to 2PI
float filledAngle = fillAmount * 2.0 * 3.14159265359;
// Calculate smooth edge for radius
float radiusAlpha = 1.0 - smoothstep(radius, radius + edgeSoftness, dist);
// Calculate smooth edge for angle
float angleAlpha = smoothstep(filledAngle - 0.02, filledAngle + 0.02, angle); // 0.02 rad ~ edge softness
return radiusAlpha * angleAlpha;
}
*/

View file

@ -0,0 +1,29 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#version 450
layout(location = 0) in vec4 inColor;
layout(location = 0) out vec4 outColor;
void main()
{
outColor = inColor;
}

View file

@ -0,0 +1,82 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#version 450
#extension GL_EXT_mesh_shader : require
layout (binding = 0) uniform UBO
{
mat4 modelProjectionView;
uint stride;
float spacing;
uint padding[14];
} ubo;
struct VertexType
{
float height;
float padding[3];
vec4 color;
};
layout (binding = 1) buffer VERTEX
{
VertexType pos[];
} vertex;
layout(local_size_x = 64, local_size_y = 1, local_size_z = 1) in;
layout(triangles, max_vertices = 256, max_primitives = 128) out;
layout (location = 0) out PerVertexData
{
vec4 color;
} outVert[];
void main()
{
SetMeshOutputsEXT(256, 128);
uint linearID = gl_GlobalInvocationID.x;
uint quadX = linearID % ubo.stride;
uint quadZ = linearID / ubo.stride;
VertexType vertex1 = vertex.pos[quadZ * ubo.stride + quadX];
VertexType vertex2 = vertex.pos[quadZ * ubo.stride + quadX + 1];
VertexType vertex3 = vertex.pos[(quadZ+1) * ubo.stride + quadX];
VertexType vertex4 = vertex.pos[(quadZ+1) * ubo.stride + quadX + 1];
uint vertexID = gl_LocalInvocationID.x*4;
gl_MeshVerticesEXT[vertexID].gl_Position = ubo.modelProjectionView * vec4(ubo.spacing*quadX, vertex1.height, ubo.spacing*quadZ, 1); // Top-left
gl_MeshVerticesEXT[vertexID + 1].gl_Position = ubo.modelProjectionView * vec4(ubo.spacing*quadX+ubo.spacing, vertex2.height, ubo.spacing*quadZ, 1); // Top-right
gl_MeshVerticesEXT[vertexID + 2].gl_Position = ubo.modelProjectionView * vec4(ubo.spacing*quadX, vertex3.height, ubo.spacing*quadZ+ubo.spacing, 1); // Bottom-left
gl_MeshVerticesEXT[vertexID + 3].gl_Position = ubo.modelProjectionView * vec4(ubo.spacing*quadX+ubo.spacing, vertex4.height, ubo.spacing*quadZ+ubo.spacing, 1); // Bottom-right
outVert[vertexID].color = vertex1.color;
outVert[vertexID + 1].color = vertex2.color;
outVert[vertexID+ 2].color = vertex3.color;
outVert[vertexID + 3].color = vertex4.color;
uint triangleID = gl_LocalInvocationID.x*2;
gl_PrimitiveTriangleIndicesEXT[triangleID] = uvec3(vertexID+2, vertexID+1, vertexID);
gl_PrimitiveTriangleIndicesEXT[triangleID + 1] = uvec3(vertexID+3, vertexID+1, vertexID+2);
}

View file

@ -0,0 +1,159 @@
/*
* Crafter®.Graphics
* Copyright (C) 2025 Catcrafts®
* Catcrafts.net
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#version 450
#extension GL_EXT_mesh_shader : require
layout (binding = 0) uniform UBO
{
mat4 modelProjectionView;
uint sizeX;
uint sizeY;
uint sizeZ;
} ubo;
struct VoxelType
{
uint type;
};
layout (binding = 1) buffer VOXELS
{
VoxelType voxel[];
} voxels;
layout (location = 0) out PerVertexData
{
vec4 color;
} outVert[];
shared uint writeCounter;
layout(local_size_x = 16, local_size_y = 1, local_size_z = 1) in;
layout(triangles, max_vertices = 128, max_primitives = 192) out;
void main()
{
if (gl_LocalInvocationIndex == 0) {
writeCounter = 0;
}
barrier();
uint type = voxels.voxel[gl_GlobalInvocationID.x].type;
if(type != 0) {
uint old = atomicAdd(writeCounter, 1);
uint z = gl_GlobalInvocationID.x / (ubo.sizeX * ubo.sizeY);
uint y = (gl_GlobalInvocationID.x % (ubo.sizeX * ubo.sizeY)) / ubo.sizeX;
uint x = gl_GlobalInvocationID.x % ubo.sizeX;
float zF = float(z);
float yF = float(y);
float xF = float(x);
uint oldVertexOffset = old*8;
float xC = xF / float((ubo.sizeX) - 1);
float yC = yF / float((ubo.sizeY) - 1);
float zC = zF / float((ubo.sizeZ) - 1);
gl_MeshVerticesEXT[oldVertexOffset + 0].gl_Position = ubo.modelProjectionView * vec4(xF - 0.5, yF - 0.5, zF - 0.5, 1.0);
gl_MeshVerticesEXT[oldVertexOffset + 1].gl_Position = ubo.modelProjectionView * vec4(xF + 0.5, yF - 0.5, zF - 0.5, 1.0);
gl_MeshVerticesEXT[oldVertexOffset + 2].gl_Position = ubo.modelProjectionView * vec4(xF + 0.5, yF + 0.5, zF - 0.5, 1.0);
gl_MeshVerticesEXT[oldVertexOffset + 3].gl_Position = ubo.modelProjectionView * vec4(xF - 0.5, yF + 0.5, zF - 0.5, 1.0);
gl_MeshVerticesEXT[oldVertexOffset + 4].gl_Position = ubo.modelProjectionView * vec4(xF - 0.5, yF - 0.5, zF + 0.5, 1.0);
gl_MeshVerticesEXT[oldVertexOffset + 5].gl_Position = ubo.modelProjectionView * vec4(xF + 0.5, yF - 0.5, zF + 0.5, 1.0);
gl_MeshVerticesEXT[oldVertexOffset + 6].gl_Position = ubo.modelProjectionView * vec4(xF + 0.5, yF + 0.5, zF + 0.5, 1.0);
gl_MeshVerticesEXT[oldVertexOffset + 7].gl_Position = ubo.modelProjectionView * vec4(xF - 0.5, yF + 0.5, zF + 0.5, 1.0);
outVert[oldVertexOffset + 0].color = vec4(xC, yC, zC, 1);
outVert[oldVertexOffset + 1].color = vec4(xC, yC, zC, 1);
outVert[oldVertexOffset + 2].color = vec4(xC, yC, zC, 1);
outVert[oldVertexOffset + 3].color = vec4(xC, yC, zC, 1);
outVert[oldVertexOffset + 4].color = vec4(xC, yC, zC, 1);
outVert[oldVertexOffset + 5].color = vec4(xC, yC, zC, 1);
outVert[oldVertexOffset + 6].color = vec4(xC, yC, zC, 1);
outVert[oldVertexOffset + 7].color = vec4(xC, yC, zC, 1);
uint oldPrimOffset = old*12;
gl_PrimitiveTriangleIndicesEXT[oldPrimOffset + 0] = uvec3(oldVertexOffset + 2, oldVertexOffset + 1, oldVertexOffset + 0);
gl_PrimitiveTriangleIndicesEXT[oldPrimOffset + 1] = uvec3(oldVertexOffset + 0, oldVertexOffset + 3, oldVertexOffset + 2);
gl_PrimitiveTriangleIndicesEXT[oldPrimOffset + 2] = uvec3(oldVertexOffset + 4, oldVertexOffset + 5, oldVertexOffset + 6);
gl_PrimitiveTriangleIndicesEXT[oldPrimOffset + 3] = uvec3(oldVertexOffset + 4, oldVertexOffset + 6, oldVertexOffset + 7);
gl_PrimitiveTriangleIndicesEXT[oldPrimOffset + 4] = uvec3(oldVertexOffset + 0, oldVertexOffset + 1, oldVertexOffset + 5);
gl_PrimitiveTriangleIndicesEXT[oldPrimOffset + 5] = uvec3(oldVertexOffset + 5, oldVertexOffset + 4, oldVertexOffset + 0);
gl_PrimitiveTriangleIndicesEXT[oldPrimOffset + 6] = uvec3(oldVertexOffset + 3, oldVertexOffset + 6, oldVertexOffset + 2);
gl_PrimitiveTriangleIndicesEXT[oldPrimOffset + 7] = uvec3(oldVertexOffset + 3, oldVertexOffset + 7, oldVertexOffset + 6);
gl_PrimitiveTriangleIndicesEXT[oldPrimOffset + 8] = uvec3(oldVertexOffset + 7, oldVertexOffset + 3, oldVertexOffset + 0);
gl_PrimitiveTriangleIndicesEXT[oldPrimOffset + 9] = uvec3(oldVertexOffset + 4, oldVertexOffset + 7, oldVertexOffset + 0);
gl_PrimitiveTriangleIndicesEXT[oldPrimOffset + 10] = uvec3(oldVertexOffset + 1, oldVertexOffset + 2, oldVertexOffset + 6);
gl_PrimitiveTriangleIndicesEXT[oldPrimOffset + 11] = uvec3(oldVertexOffset + 6, oldVertexOffset + 5, oldVertexOffset + 1);
}
barrier();
SetMeshOutputsEXT(writeCounter*8, writeCounter*12);
}
/**
int z = gl_GlobalInvocationID.x / (ubo.sizeX * ubo.sizeY);
int y = (gl_GlobalInvocationID.x % (ubo.sizeX * ubo.sizeY)) / ubo.sizeX;
int x = gl_GlobalInvocationID.x % ubo.sizeX;
// Top (y+1) if within bounds
if (y < ubo.sizeY - 1 && vertex.pos[gl_GlobalInvocationID.x + ubo.sizeX]) {
}
// Bottom (y-1) if within bounds
if (y > 0 && vertex.pos[gl_GlobalInvocationID.x - ubo.sizeX]) {
}
// Left (x-1) if within bounds
if (x > 0 && vertex.pos[gl_GlobalInvocationID.x - 1]) {
}
// Right (x+1) if within bounds
if (x < ubo.sizeX - 1 && vertex.pos[gl_GlobalInvocationID.x + 1]) {
}
// Front (z+1) if within bounds
if (z < ubo.sizeZ - 1 && vertex.pos[gl_GlobalInvocationID.x + ubo.sizeX * ubo.sizeY]) {
}
// Back (z-1) if within bounds
if (z > 0 && vertex.pos[gl_GlobalInvocationID.x - ubo.sizeX * ubo.sizeY]) {
}
**/

View file

@ -0,0 +1,50 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#version 450
#extension GL_EXT_mesh_shader : require
layout (binding = 0) uniform UBO
{
mat4 modelProjectionView;
} ubo;
layout (binding = 1) buffer VERTEX
{
vec4 pos[];
} vertex;
layout (binding = 2) buffer INDEX {
uint index[];
} index;
layout(local_size_x = 64, local_size_y = 1, local_size_z = 1) in;
layout(triangles, max_vertices = 192, max_primitives = 64) out;
void main()
{
SetMeshOutputsEXT(192, 64);
uint triangleID = ((gl_WorkGroupID.x * gl_WorkGroupSize.x) + gl_LocalInvocationIndex.x)*3;
uint localID = gl_LocalInvocationIndex.x*3;
gl_MeshVerticesEXT[localID].gl_Position = ubo.modelProjectionView * vertex.pos[index.index[triangleID]];
gl_MeshVerticesEXT[localID+1].gl_Position = ubo.modelProjectionView * vertex.pos[index.index[triangleID+1]];
gl_MeshVerticesEXT[localID+2].gl_Position = ubo.modelProjectionView * vertex.pos[index.index[triangleID+2]];
gl_PrimitiveTriangleIndicesEXT[gl_LocalInvocationIndex.x] = uvec3(localID, localID+1, localID+2);
}

View file

@ -0,0 +1,65 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#version 450
#extension GL_EXT_mesh_shader : require
layout (binding = 0) uniform UBO
{
mat4 modelProjectionView;
} ubo;
struct VertexType
{
vec4 position;
vec4 color;
};
layout (std140, binding = 1) buffer VERTEX
{
VertexType pos[];
} vertex;
layout (binding = 2) buffer INDEX {
uint index[];
} index;
layout(local_size_x = 64, local_size_y = 1, local_size_z = 1) in;
layout(triangles, max_vertices = 192, max_primitives = 64) out;
layout (location = 0) out PerVertexData
{
vec4 color;
} outVert[];
void main()
{
SetMeshOutputsEXT(192, 64);
uint triangleID = ((gl_WorkGroupID.x * gl_WorkGroupSize.x) + gl_LocalInvocationIndex.x)*3;
uint localID = gl_LocalInvocationIndex.x*3;
gl_MeshVerticesEXT[localID].gl_Position = ubo.modelProjectionView * vertex.pos[index.index[triangleID]].position;
gl_MeshVerticesEXT[localID+1].gl_Position = ubo.modelProjectionView * vertex.pos[index.index[triangleID+1]].position;
gl_MeshVerticesEXT[localID+2].gl_Position = ubo.modelProjectionView * vertex.pos[index.index[triangleID+2]].position;
outVert[localID].color = vertex.pos[index.index[triangleID]].color;
outVert[localID + 1].color = vertex.pos[index.index[triangleID+1]].color;
outVert[localID + 2].color = vertex.pos[index.index[triangleID+2]].color;
gl_PrimitiveTriangleIndicesEXT[gl_LocalInvocationIndex.x] = uvec3(localID, localID+1, localID+2);
}

View file

@ -0,0 +1,66 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#version 450
#extension GL_EXT_mesh_shader : require
layout (binding = 0) uniform UBO
{
mat4 modelProjectionView;
} ubo;
struct VertexType
{
vec4 position;
vec2 uv;
vec2 pad;
};
layout (std140, binding = 1) buffer VERTEX
{
VertexType pos[];
} vertex;
layout (binding = 2) buffer INDEX {
uint index[];
} index;
layout(local_size_x = 64, local_size_y = 1, local_size_z = 1) in;
layout(triangles, max_vertices = 192, max_primitives = 64) out;
layout (location = 0) out PerVertexData
{
vec2 uv;
} outVert[];
void main()
{
SetMeshOutputsEXT(192, 64);
uint triangleID = ((gl_WorkGroupID.x * gl_WorkGroupSize.x) + gl_LocalInvocationIndex.x)*3;
uint localID = gl_LocalInvocationIndex.x*3;
gl_MeshVerticesEXT[localID].gl_Position = ubo.modelProjectionView * vertex.pos[index.index[triangleID]].position;
gl_MeshVerticesEXT[localID+1].gl_Position = ubo.modelProjectionView * vertex.pos[index.index[triangleID+1]].position;
gl_MeshVerticesEXT[localID+2].gl_Position = ubo.modelProjectionView * vertex.pos[index.index[triangleID+2]].position;
outVert[localID].uv = vertex.pos[index.index[triangleID]].uv;
outVert[localID + 1].uv = vertex.pos[index.index[triangleID+1]].uv;
outVert[localID + 2].uv = vertex.pos[index.index[triangleID+2]].uv;
gl_PrimitiveTriangleIndicesEXT[gl_LocalInvocationIndex.x] = uvec3(localID, localID+1, localID+2);
}

View file

@ -0,0 +1,68 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include <cstdint>
#include <vulkan/vulkan.h>
#include <iostream>
#include <format>
module Crafter.Graphics;
import Crafter.Math;
import Crafter.Event;
using namespace Crafter;
Camera::Camera(float fov, float aspectRatio, float near, float far) {
projection = MatrixRowMajor<float, 4, 4, 1>::Perspective(fov, aspectRatio, near, far);
view = MatrixRowMajor<float, 4, 4, 1>::Identity();
}
void Camera::Update() {
projectionView = projection*view;
onUpdate.Invoke();
}
Vector<float, 3> Camera::ToRay(uint32_t x, uint32_t y) {
// // Normalize the screen coordinates
// float mx = (2.0f * x) / sizeX - 1.0f;
// float my = 1.0f - (2.0f * y) / sizeY;
//
// // Construct Ray in Homogeneous Clip Space
// Vector<float, 3> rayOrigin = Vector<float, 3>(mx, my, 0.0f);
// Vector<float, 3> rayEnd = Vector<float, 3>(mx, my, 1.0f);
//
// // Transform Ray to View Space
// MatrixRowMajor<float, 4, 4, 1> invProjection = DirectX::XMMatrixInverse(NULL, projectionMatrix);
// Vector<float, 3> rayOriginView = DirectX::XMVector3TransformCoord(rayOrigin, invProjection);
// Vector<float, 3> rayEndView = DirectX::XMVector3TransformCoord(rayEnd, invProjection);
//
// // Transform Ray to World Space
// DirectX::XMMATRIX viewMatrix = GetViewMatrix(); // Assuming this returns the view matrix
// DirectX::XMMATRIX invView = DirectX::XMMatrixInverse(NULL, viewMatrix);
// Vector<float, 3> rayOriginWorld = DirectX::XMVector3TransformCoord(rayOriginView, invView);
// Vector<float, 3> rayEndWorld = DirectX::XMVector3TransformCoord(rayEndView, invView);
//
// // Compute Ray Direction
// DirectX::XMVECTOR rayDirWorld = DirectX::XMVector3Normalize(DirectX::XMVectorSubtract(rayEndWorld, rayOriginWorld));
//
// return rayDirWorld;
return Vector<float, 3>(0,0,0);
}

View file

@ -0,0 +1,34 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include <cstdint>
module Crafter.Graphics;
using namespace Crafter;
UiElement::UiElement(float anchorX, float anchorY, std::uint32_t bufferWidth, std::uint32_t bufferHeight, std::uint32_t absoluteWidth, std::uint32_t absoluteHeight, float anchorOffsetX, float anchorOffsetY, float z, bool ignoreScaling) : anchorX(anchorX), anchorY(anchorY), bufferWidth(bufferWidth), bufferHeight(bufferHeight), absoluteWidth(absoluteWidth), absoluteHeight(absoluteHeight), anchorOffsetX(anchorOffsetX), anchorOffsetY(anchorOffsetY), z(z), buffer(bufferWidth*bufferHeight), useRelativeSize(false), ignoreScaling(ignoreScaling) {
}
UiElement::UiElement(float anchorX, float anchorY, std::uint32_t bufferWidth, std::uint32_t bufferHeight, float relativeWidth, float relativeHeight, float anchorOffsetX, float anchorOffsetY, float z, bool ignoreScaling) : anchorX(anchorX), anchorY(anchorY), bufferWidth(bufferWidth), bufferHeight(bufferHeight), relativeWidth(relativeWidth), relativeHeight(relativeHeight), anchorOffsetX(anchorOffsetX), anchorOffsetY(anchorOffsetY), z(z), buffer(bufferWidth*bufferHeight), useRelativeSize(true), ignoreScaling(ignoreScaling) {
}

View file

@ -0,0 +1,304 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include <cstdint>
#include <vulkan/vulkan.h>
#include <vulkan/vulkan_wayland.h>
#include <iostream>
#include <exception>
#include <vulkan/vk_enum_string_helper.h>
#include <cstring>
#include <print>
#include <cstdio>
#include "../../lib/VulkanInitializers.hpp"
#define GET_EXTENSION_FUNCTION(_id) ((PFN_##_id)(vkGetInstanceProcAddr(instance, #_id)))
module Crafter.Graphics;
using namespace Crafter;
const char* const instanceExtensionNames[] = {
"VK_EXT_debug_utils",
"VK_KHR_surface",
"VK_KHR_wayland_surface"
};
const char* const deviceExtensionNames[] = {
"VK_KHR_swapchain",
"VK_KHR_spirv_1_4",
"VK_EXT_mesh_shader",
"VK_KHR_shader_float_controls",
"VK_KHR_dynamic_rendering"
};
const char* const layerNames[] = {
"VK_LAYER_KHRONOS_validation"
};
void VulkanDevice::CHECK_VK_RESULT(VkResult result) {
if (result != VK_SUCCESS)
{
throw std::runtime_error(string_VkResult(result));
}
}
VkBool32 onError(VkDebugUtilsMessageSeverityFlagBitsEXT severity, VkDebugUtilsMessageTypeFlagsEXT type, const VkDebugUtilsMessengerCallbackDataEXT* callbackData, void* userData)
{
printf("Vulkan ");
switch (type)
{
case VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT :
printf("general ");
break;
case VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT :
printf("validation ");
break;
case VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT :
printf("performance ");
break;
}
switch (severity)
{
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT :
printf("(verbose): ");
break;
default :
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT :
printf("(info): ");
break;
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT :
printf("(warning): ");
break;
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT :
printf("(error): ");
break;
}
printf("%s\n", callbackData->pMessage);
return 0;
}
void VulkanDevice::CreateDevice() {
VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO};
app.pApplicationName = "";
app.pEngineName = "Crafter.Graphics";
app.apiVersion = VK_MAKE_VERSION(1, 4, 0);
VkInstanceCreateInfo instanceCreateInfo = {};
instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
instanceCreateInfo.pApplicationInfo = &app;
instanceCreateInfo.enabledExtensionCount = sizeof(instanceExtensionNames) / sizeof(const char*);
instanceCreateInfo.ppEnabledExtensionNames = instanceExtensionNames;
size_t foundInstanceLayers = 0;
std::uint32_t instanceLayerCount;
CHECK_VK_RESULT(vkEnumerateInstanceLayerProperties(&instanceLayerCount, NULL));
std::vector<VkLayerProperties> instanceLayerProperties(instanceLayerCount);
CHECK_VK_RESULT(vkEnumerateInstanceLayerProperties(&instanceLayerCount, instanceLayerProperties.data()));
for (uint32_t i = 0; i < instanceLayerCount; i++)
{
for (size_t j = 0; j < sizeof(layerNames) / sizeof(const char*); j++)
{
if (std::strcmp(instanceLayerProperties[i].layerName, layerNames[j]) == 0)
{
foundInstanceLayers++;
}
}
}
if (foundInstanceLayers >= sizeof(layerNames) / sizeof(const char*))
{
instanceCreateInfo.enabledLayerCount = sizeof(layerNames) / sizeof(const char*);
instanceCreateInfo.ppEnabledLayerNames = layerNames;
}
CHECK_VK_RESULT(vkCreateInstance(&instanceCreateInfo, NULL, &instance));
VkDebugUtilsMessengerCreateInfoEXT debugUtilsMessengerCreateInfo = {};
debugUtilsMessengerCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
debugUtilsMessengerCreateInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
debugUtilsMessengerCreateInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
debugUtilsMessengerCreateInfo.pfnUserCallback = onError;
CHECK_VK_RESULT(GET_EXTENSION_FUNCTION(vkCreateDebugUtilsMessengerEXT)(instance, &debugUtilsMessengerCreateInfo, NULL, &debugMessenger));
uint32_t physDeviceCount;
vkEnumeratePhysicalDevices(instance, &physDeviceCount, NULL);
std::vector<VkPhysicalDevice> physDevices(physDeviceCount);
vkEnumeratePhysicalDevices(instance, &physDeviceCount, physDevices.data());
uint32_t bestScore = 0;
for (uint32_t i = 0; i < physDeviceCount; i++)
{
VkPhysicalDevice device = physDevices[i];
VkPhysicalDeviceProperties properties;
vkGetPhysicalDeviceProperties(device, &properties);
uint32_t score;
switch (properties.deviceType)
{
default :
continue;
case VK_PHYSICAL_DEVICE_TYPE_OTHER :
score = 1;
break;
case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU :
score = 4;
break;
case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU :
score = 5;
break;
case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU :
score = 3;
break;
case VK_PHYSICAL_DEVICE_TYPE_CPU :
score = 2;
break;
}
if (score > bestScore)
{
physDevice = device;
bestScore = score;
}
}
uint32_t queueFamilyCount;
vkGetPhysicalDeviceQueueFamilyProperties(physDevice, &queueFamilyCount, NULL);
std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
vkGetPhysicalDeviceQueueFamilyProperties(physDevice, &queueFamilyCount, queueFamilies.data());
for (uint32_t i = 0; i < queueFamilyCount; i++)
{
if (queueFamilies[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)
{
queueFamilyIndex = i;
break;
}
}
float priority = 1;
VkDeviceQueueCreateInfo queueCreateInfo = {};
queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
queueCreateInfo.queueCount = 1;
queueCreateInfo.pQueuePriorities = &priority;
VkPhysicalDeviceDynamicRenderingFeaturesKHR dynamicRenderingFeature = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR};
dynamicRenderingFeature.dynamicRendering = VK_TRUE;
VkPhysicalDeviceMeshShaderFeaturesEXT ext_feature = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT};
ext_feature.meshShader = VK_TRUE;
ext_feature.pNext = &dynamicRenderingFeature;
VkPhysicalDeviceFeatures2 physical_features2 = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2};
physical_features2.pNext = &ext_feature;
VkDeviceCreateInfo deviceCreateInfo = {};
deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
deviceCreateInfo.queueCreateInfoCount = 1;
deviceCreateInfo.pQueueCreateInfos = &queueCreateInfo;
deviceCreateInfo.enabledExtensionCount = sizeof(deviceExtensionNames) / sizeof(const char*);
deviceCreateInfo.ppEnabledExtensionNames = deviceExtensionNames;
deviceCreateInfo.pNext = &physical_features2;
uint32_t deviceLayerCount;
CHECK_VK_RESULT(vkEnumerateDeviceLayerProperties(physDevice, &deviceLayerCount, NULL));
std::vector<VkLayerProperties> deviceLayerProperties(deviceLayerCount);
CHECK_VK_RESULT(vkEnumerateDeviceLayerProperties(physDevice, &deviceLayerCount, deviceLayerProperties.data()));
size_t foundDeviceLayers = 0;
for (uint32_t i = 0; i < deviceLayerCount; i++)
{
for (size_t j = 0; j < sizeof(layerNames) / sizeof(const char*); j++)
{
if (strcmp(deviceLayerProperties[i].layerName, layerNames[j]) == 0)
{
foundDeviceLayers++;
}
}
}
if (foundDeviceLayers >= sizeof(layerNames) / sizeof(const char*))
{
deviceCreateInfo.enabledLayerCount = sizeof(layerNames) / sizeof(const char*);
deviceCreateInfo.ppEnabledLayerNames = layerNames;
}
CHECK_VK_RESULT(vkCreateDevice(physDevice, &deviceCreateInfo, NULL, &device));
vkGetDeviceQueue(device, queueFamilyIndex, 0, &queue);
VkCommandPoolCreateInfo commandPoolcreateInfo = {};
commandPoolcreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
commandPoolcreateInfo.queueFamilyIndex = queueFamilyIndex;
commandPoolcreateInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
CHECK_VK_RESULT(vkCreateCommandPool(device, &commandPoolcreateInfo, NULL, &commandPool));
vkGetPhysicalDeviceMemoryProperties(physDevice, &memoryProperties);
std::vector<VkFormat> formatList = {
VK_FORMAT_D32_SFLOAT,
};
for (auto& format : formatList) {
VkFormatProperties formatProps;
vkGetPhysicalDeviceFormatProperties(physDevice, format, &formatProps);
if (formatProps.optimalTilingFeatures)
{
depthFormat = format;
break;
}
}
vkCmdDrawMeshTasksEXTProc = reinterpret_cast<PFN_vkCmdDrawMeshTasksEXT>(vkGetDeviceProcAddr(device, "vkCmdDrawMeshTasksEXT"));
vkCmdBeginRenderingKHRProc = reinterpret_cast<PFN_vkCmdBeginRenderingKHR>(vkGetInstanceProcAddr(instance, "vkCmdBeginRenderingKHR"));
vkCmdEndRenderingKHRProc = reinterpret_cast<PFN_vkCmdEndRenderingKHR>(vkGetInstanceProcAddr(instance, "vkCmdEndRenderingKHR"));
}
std::uint32_t VulkanDevice::GetMemoryType(uint32_t typeBits, VkMemoryPropertyFlags properties) {
for (uint32_t i = 0; i < memoryProperties.memoryTypeCount; i++)
{
if ((typeBits & 1) == 1)
{
if ((memoryProperties.memoryTypes[i].propertyFlags & properties) == properties)
{
return i;
}
}
typeBits >>= 1;
}
throw std::runtime_error("Could not find a matching memory type");
}

View file

@ -0,0 +1,56 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include <cstdint>
#include <string>
module Crafter.Graphics;
import Crafter.Event;
using namespace Crafter;
Window::Window(std::string name, std::uint32_t width, std::uint32_t height) : name(name), width(width), height(height) {
}
ScaleData Window::ScaleElement(const UiElement& element) {
ScaleData data;
if(element.ignoreScaling) {
if(element.useRelativeSize) {
data.width = element.relativeWidth*width;
data.height = element.relativeHeight*height;
} else {
data.width = element.absoluteWidth;
data.height = element.absoluteHeight;
}
} else {
if(element.useRelativeSize) {
data.width = element.relativeWidth*width*scale;
data.height = element.relativeHeight*height*scale;
} else {
data.width = element.absoluteWidth*scale;
data.height = element.absoluteHeight*scale;
}
}
data.x = (element.anchorX*width)-(element.anchorOffsetX*data.width);
data.y = (element.anchorY*height)-(element.anchorOffsetY*data.height);
return data;
}

View file

@ -0,0 +1,371 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include <errno.h>
#include <fcntl.h>
#include <linux/input.h>
#include <string>
#include <sys/mman.h>
#include <unistd.h>
#include <wayland-cursor.h>
#include <xkbcommon/xkbcommon.h>
#include <iostream>
#include <vulkan/vulkan.h>
#include <vulkan/vulkan_wayland.h>
#include <wayland-client.h>
#include <cstring>
#include "../../lib/xdg-shell-client-protocol.h"
#include "../../lib/wayland-xdg-decoration-unstable-v1-client-protocol.h"
#define _POSIX_C_SOURCE 200809L
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <sys/mman.h>
#include <time.h>
#include <unistd.h>
#include <print>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#include <wayland-client.h>
#include <wayland-client-protocol.h>
#include <linux/input-event-codes.h>
#include <cmath>
#include <xkbcommon/xkbcommon.h>
#include <cstdio>
module Crafter.Graphics;
import Crafter.Event;
using namespace Crafter;
static void xdg_wm_base_handle_ping(void* data, xdg_wm_base* xdg_wm_base, std::uint32_t serial) {
xdg_wm_base_pong(xdg_wm_base, serial);
}
xdg_wm_base_listener xdgWmBaseListener = {
.ping = xdg_wm_base_handle_ping,
};
void WindowWayland::pointer_handle_button(void* data, wl_pointer* pointer, std::uint32_t serial, std::uint32_t time, std::uint32_t button, std::uint32_t state) {
WindowWayland* window = reinterpret_cast<WindowWayland*>(data);
if (button == BTN_LEFT) {
if(state == WL_POINTER_BUTTON_STATE_PRESSED) {
window->mouseLeftHeld = true;
window->onMouseLeftClick.Invoke(window->currentMousePos);
for(UiElement& element : window->elements) {
ScaleData data = window->ScaleElement(element);
if(window->currentMousePos.x >= data.x && window->currentMousePos.x <= data.x+data.width && window->currentMousePos.y > data.y && window->currentMousePos.y < data.y+data.height) {
element.onMouseLeftClick.Invoke({window->currentMousePos.x-data.x, window->currentMousePos.y-data.y});
}
}
} else {
window->mouseLeftHeld = false;
window->onMouseLeftRelease.Invoke(window->currentMousePos);
for(UiElement& element : window->elements) {
ScaleData data = window->ScaleElement(element);
if(window->currentMousePos.x >= data.x && window->currentMousePos.x <= data.x+data.width && window->currentMousePos.y > data.y && window->currentMousePos.y < data.y+data.height) {
element.onMouseLeftRelease.Invoke({window->currentMousePos.x-data.x, window->currentMousePos.y-data.y});
}
}
}
} else if(button == BTN_RIGHT){
if(state == WL_POINTER_BUTTON_STATE_PRESSED) {
window->mouseRightHeld = true;
window->onMouseRightClick.Invoke(window->currentMousePos);
for(UiElement& element : window->elements) {
ScaleData data = window->ScaleElement(element);
if(window->currentMousePos.x >= data.x && window->currentMousePos.x <= data.x+data.width && window->currentMousePos.y > data.y && window->currentMousePos.y < data.y+data.height) {
element.onMouseRightClick.Invoke({window->currentMousePos.x-data.x, window->currentMousePos.y-data.y});
}
}
} else {
window->mouseRightHeld = true;
window->onMouseRightRelease.Invoke(window->currentMousePos);
for(UiElement& element : window->elements) {
ScaleData data = window->ScaleElement(element);
if(window->currentMousePos.x >= data.x && window->currentMousePos.x <= data.x+data.width && window->currentMousePos.y > data.y && window->currentMousePos.y < data.y+data.height) {
element.onMouseRightRelease.Invoke({window->currentMousePos.x-data.x, window->currentMousePos.y-data.y});
}
}
}
}
}
void WindowWayland::PointerListenerHandleMotion(void* data, wl_pointer* wl_pointer, uint time, wl_fixed_t surface_x, wl_fixed_t surface_y) {
WindowWayland* window = reinterpret_cast<WindowWayland*>(data);
MousePoint pos = {wl_fixed_to_double(surface_x), wl_fixed_to_double(surface_y)};
window->lastMousePos = window->currentMousePos;
window->currentMousePos = pos;
window->mouseDelta = {window->currentMousePos.x-window->lastMousePos.x, window->currentMousePos.y-window->lastMousePos.y};
window->onMouseMove.Invoke({window->lastMousePos, window->currentMousePos, window->mouseDelta});
for(UiElement& element : window->elements) {
ScaleData data = window->ScaleElement(element);
if(window->currentMousePos.x >= data.x && window->currentMousePos.x <= data.x+data.width && window->currentMousePos.y > data.y && window->currentMousePos.y < data.y+data.height) {
element.onMouseMove.Invoke({window->currentMousePos.x-data.x, window->currentMousePos.y-data.y});
if(!(window->lastMousePos.x >= data.x && window->lastMousePos.x <= data.x+data.width && window->lastMousePos.y > data.y && window->lastMousePos.y < data.y+data.height)) {
element.onMouseEnter.Invoke({window->currentMousePos.x-data.x, window->currentMousePos.y-data.y});
}
} else if(window->lastMousePos.x >= data.x && window->lastMousePos.x <= data.x+data.width && window->lastMousePos.y > data.y && window->lastMousePos.y < data.y+data.height) {
element.onMouseLeave.Invoke({window->currentMousePos.x-data.x, window->currentMousePos.y-data.y});
}
}
}
void WindowWayland::PointerListenerHandleEnter(void* data, wl_pointer* wl_pointer, uint serial, wl_surface* surface, wl_fixed_t surface_x, wl_fixed_t surface_y) {
WindowWayland* window = reinterpret_cast<WindowWayland*>(data);
window->onMouseEnter.Invoke({window->lastMousePos, window->currentMousePos, window->mouseDelta});
}
void WindowWayland::PointerListenerHandleLeave(void* data, wl_pointer*, std::uint32_t, wl_surface*) {
WindowWayland* window = reinterpret_cast<WindowWayland*>(data);
window->onMouseEnter.Invoke({window->lastMousePos, window->currentMousePos, window->mouseDelta});
}
void WindowWayland::PointerListenerHandleAxis(void*, wl_pointer*, std::uint32_t, std::uint32_t, wl_fixed_t value) {
std::cout << wl_fixed_to_double(value) << std::endl;
}
wl_pointer_listener WindowWayland::pointer_listener = {
.enter = WindowWayland::PointerListenerHandleEnter,
.leave = WindowWayland::PointerListenerHandleLeave,
.motion = WindowWayland::PointerListenerHandleMotion,
.button = WindowWayland::pointer_handle_button,
.axis = WindowWayland::PointerListenerHandleAxis,
};
xkb_keymap* xkb_keymap;
xkb_context* xkb_context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
xkb_state* xkb_state;
void keyboard_keymap(void *data, wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {
if (format != WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1) {
close(fd);
fprintf(stderr, "Unsupported keymap format\n");
return;
}
void *map = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);
if (map == MAP_FAILED) {
close(fd);
perror("mmap");
return;
}
xkb_context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
xkb_keymap = xkb_keymap_new_from_string(xkb_context, (const char *)map, XKB_KEYMAP_FORMAT_TEXT_V1,XKB_KEYMAP_COMPILE_NO_FLAGS);
munmap(map, size);
close(fd);
xkb_state = xkb_state_new(xkb_keymap);
}
void keyboard_enter(void *data, wl_keyboard *keyboard, uint32_t serial, wl_surface *surface, wl_array *keys) {
}
void keyboard_leave(void *data, wl_keyboard *keyboard, uint32_t serial, wl_surface *surface) {
}
void keyboard_key(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key, uint32_t state) {
if (!xkb_state) {
return;
}
WindowWayland* window = reinterpret_cast<WindowWayland*>(data);
xkb_keycode_t keycode = key + 8;
xkb_keysym_t keysym = xkb_state_key_get_one_sym(xkb_state, keycode);
char utf8[8] = {0};
int len = xkb_keysym_to_utf8(keysym, utf8, sizeof(utf8));
if (len != 0) {
char keypress = utf8[0];
if(state == WL_KEYBOARD_KEY_STATE_PRESSED) {
if(window->heldkeys[keypress]) {
window->onKeyHold[keypress].Invoke();
window->onAnyKeyHold.Invoke(keypress);
} else{
window->heldkeys[keypress] = true;
window->onKeyDown[keypress].Invoke();
window->onAnyKeyDown.Invoke(keypress);
}
} else{
window->heldkeys[keypress] = false;
window->onKeyUp[keypress].Invoke();
window->onAnyKeyUp.Invoke(keypress);
}
} else {
// // fallback for keys like Return, Escape, etc.
// char name[64];
// if (xkb_keysym_get_name(keysym, name, sizeof(name)) > 0) {
// printf("Key %s pressed (non-printable or multi-char)\n", name);
// }
}
}
void keyboard_modifiers(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed, uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {
}
void keyboard_repeat_info(void *data, wl_keyboard *keyboard, int32_t rate, int32_t delay) {
}
wl_keyboard_listener WindowWayland::keyboard_listener = {
.keymap = keyboard_keymap,
.enter = keyboard_enter,
.leave = keyboard_leave,
.key = keyboard_key,
.modifiers = keyboard_modifiers,
.repeat_info = keyboard_repeat_info,
};
void WindowWayland::seat_handle_capabilities(void* data, wl_seat* seat, uint32_t capabilities) {
WindowWayland* window = reinterpret_cast<WindowWayland*>(data);
window->seat = seat;
if (capabilities & WL_SEAT_CAPABILITY_POINTER) {
wl_pointer* pointer = wl_seat_get_pointer(seat);
wl_pointer_add_listener(pointer, &pointer_listener, window);
}
if (capabilities & WL_SEAT_CAPABILITY_KEYBOARD) {
wl_keyboard* keyboard = wl_seat_get_keyboard(seat);
wl_keyboard_add_listener(keyboard, &keyboard_listener, window);
}
}
wl_seat_listener WindowWayland::seat_listener = {
.capabilities = seat_handle_capabilities,
};
void WindowWayland::handle_global(void *data, wl_registry *registry, std::uint32_t name, const char *interface, std::uint32_t version) {
WindowWayland* window = reinterpret_cast<WindowWayland*>(data);
if (strcmp(interface, wl_shm_interface.name) == 0) {
window->shm = reinterpret_cast<wl_shm*>(wl_registry_bind(registry, name, &wl_shm_interface, 1));
} else if (strcmp(interface, wl_seat_interface.name) == 0) {
wl_seat* seat = reinterpret_cast<wl_seat*>(wl_registry_bind(registry, name, &wl_seat_interface, 1));
wl_seat_add_listener(seat, &seat_listener, window);
} else if (compositor == NULL && strcmp(interface, wl_compositor_interface.name) == 0) {
compositor = reinterpret_cast<wl_compositor*>(wl_registry_bind(registry, name, &wl_compositor_interface, 1));
} else if (strcmp(interface, xdg_wm_base_interface.name) == 0) {
window->xdgWmBase = reinterpret_cast<xdg_wm_base*>(wl_registry_bind(registry, name, &xdg_wm_base_interface, 1));
xdg_wm_base_add_listener(window->xdgWmBase, &xdgWmBaseListener, NULL);
} else if (strcmp(interface, zxdg_decoration_manager_v1_interface.name) == 0) {
window->manager = reinterpret_cast<zxdg_decoration_manager_v1*>(wl_registry_bind(registry, name, &zxdg_decoration_manager_v1_interface, 1));
}
}
static void handle_global_remove(void* data, wl_registry* registry, uint32_t name) {
}
wl_registry_listener WindowWayland::registry_listener = {
.global = WindowWayland::handle_global,
.global_remove = handle_global_remove,
};
static void noop5(void*, xdg_toplevel*, std::int32_t, std::int32_t, wl_array*){
}
void WindowWayland::xdg_toplevel_handle_close(void* data, xdg_toplevel*) {
WindowWayland* window = reinterpret_cast<WindowWayland*>(data);
window->onClose.Invoke();
window->open = false;
}
xdg_toplevel_listener WindowWayland::xdg_toplevel_listener = {
.configure = noop5,
.close = WindowWayland::xdg_toplevel_handle_close,
};
void WindowWayland::xdg_surface_handle_configure(void* data, xdg_surface* xdg_surface, std::uint32_t serial) {
WindowWayland* window = reinterpret_cast<WindowWayland*>(data);
// The compositor configures our surface, acknowledge the configure event
xdg_surface_ack_configure(xdg_surface, serial);
if (window->configured) {
// If this isn't the first configure event we've received, we already
// have a buffer attached, so no need to do anything. Commit the
// surface to apply the configure acknowledgement.
wl_surface_commit(window->surface);
}
window->configured = true;
}
xdg_surface_listener WindowWayland::xdg_surface_listener = {
.configure = xdg_surface_handle_configure,
};
WindowWayland::WindowWayland(std::string name, std::uint32_t width, std::uint32_t height) : Window(name, width, height) {
// Connect to the Wayland compositor
display = wl_display_connect(NULL);
if (display == NULL) {
std::cerr << "failed to create display" << std::endl;
}
// Obtain the wl_registry and fetch the list of globals
wl_registry* registry = wl_display_get_registry(display);
wl_registry_add_listener(registry, &registry_listener, this);
if (wl_display_roundtrip(display) == -1) {
exit(EXIT_FAILURE);
}
// Check that all globals we require are available
if (shm == NULL || compositor == NULL || xdgWmBase == NULL) {
std::cerr << "no wl_shm, wl_compositor or xdg_wm_base support" << std::endl;
exit(EXIT_FAILURE);
}
// Create a wl_surface, a xdg_surface and a xdg_toplevel
surface = wl_compositor_create_surface(compositor);
xdgSurface = xdg_wm_base_get_xdg_surface(xdgWmBase, surface);
xdgToplevel = xdg_surface_get_toplevel(xdgSurface);
xdg_surface_add_listener(xdgSurface, &xdg_surface_listener, this);
xdg_toplevel_add_listener(xdgToplevel, &xdg_toplevel_listener, this);
wl_surface_commit(surface);
while (wl_display_dispatch(display) != -1 && !configured) {
// This space intentionally left blank
}
wl_surface_commit(surface);
zxdg_toplevel_decoration_v1* decoration = zxdg_decoration_manager_v1_get_toplevel_decoration(manager, xdgToplevel); // toplevel is from xdg_surface_get_toplevel
zxdg_toplevel_decoration_v1_set_mode(decoration, ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
}
WindowWayland::~WindowWayland() {
xdg_toplevel_destroy(xdgToplevel);
xdg_surface_destroy(xdgSurface);
wl_surface_destroy(surface);
wl_buffer_destroy(buffer);
}

View file

@ -0,0 +1,496 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include <cstdint>
#include <string>
#include <vulkan/vulkan.h>
#include <vulkan/vulkan_wayland.h>
#include <vector>
#include <wayland-client.h>
#include <thread>
#include <iostream>
#include <cassert>
#include <exception>
#include "../../lib/VulkanInitializers.hpp"
#include "../../lib/VulkanTransition.hpp"
module Crafter.Graphics;
import Crafter.Event;
using namespace Crafter;
void WindowWaylandVulkan::CreateSwapchain()
{
// Store the current swap chain handle so we can use it later on to ease up recreation
VkSwapchainKHR oldSwapchain = swapChain;
// Get physical device surface properties and formats
VkSurfaceCapabilitiesKHR surfCaps;
VulkanDevice::CHECK_VK_RESULT(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(VulkanDevice::physDevice, vulkanSurface, &surfCaps));
VkExtent2D swapchainExtent = {};
// If width (and height) equals the special value 0xFFFFFFFF, the size of the surface will be set by the swapchain
if (surfCaps.currentExtent.width == (uint32_t)-1)
{
// If the surface size is undefined, the size is set to the size of the images requested
swapchainExtent.width = width;
swapchainExtent.height = height;
}
else
{
// If the surface size is defined, the swap chain size must match
swapchainExtent = surfCaps.currentExtent;
width = surfCaps.currentExtent.width;
height = surfCaps.currentExtent.height;
}
// Select a present mode for the swapchain
uint32_t presentModeCount;
VulkanDevice::CHECK_VK_RESULT(vkGetPhysicalDeviceSurfacePresentModesKHR(VulkanDevice::physDevice, vulkanSurface, &presentModeCount, NULL));
assert(presentModeCount > 0);
std::vector<VkPresentModeKHR> presentModes(presentModeCount);
VulkanDevice::CHECK_VK_RESULT(vkGetPhysicalDeviceSurfacePresentModesKHR(VulkanDevice::physDevice, vulkanSurface, &presentModeCount, presentModes.data()));
// The VK_PRESENT_MODE_FIFO_KHR mode must always be present as per spec
// This mode waits for the vertical blank ("v-sync")
VkPresentModeKHR swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR;
// Determine the number of images
uint32_t desiredNumberOfSwapchainImages = surfCaps.minImageCount + 1;
if ((surfCaps.maxImageCount > 0) && (desiredNumberOfSwapchainImages > surfCaps.maxImageCount))
{
desiredNumberOfSwapchainImages = surfCaps.maxImageCount;
}
// Find the transformation of the surface
VkSurfaceTransformFlagsKHR preTransform;
if (surfCaps.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR)
{
// We prefer a non-rotated transform
preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
}
else
{
preTransform = surfCaps.currentTransform;
}
// Find a supported composite alpha format (not all devices support alpha opaque)
VkCompositeAlphaFlagBitsKHR compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
// Simply select the first composite alpha format available
std::vector<VkCompositeAlphaFlagBitsKHR> compositeAlphaFlags = {
VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR,
VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR,
VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR,
};
for (auto& compositeAlphaFlag : compositeAlphaFlags) {
if (surfCaps.supportedCompositeAlpha & compositeAlphaFlag) {
compositeAlpha = compositeAlphaFlag;
break;
};
}
VkSwapchainCreateInfoKHR swapchainCI = {};
swapchainCI.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
swapchainCI.surface = vulkanSurface;
swapchainCI.minImageCount = desiredNumberOfSwapchainImages;
swapchainCI.imageFormat = colorFormat;
swapchainCI.imageColorSpace = colorSpace;
swapchainCI.imageExtent = { swapchainExtent.width, swapchainExtent.height };
swapchainCI.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
swapchainCI.preTransform = (VkSurfaceTransformFlagBitsKHR)preTransform;
swapchainCI.imageArrayLayers = 1;
swapchainCI.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
swapchainCI.queueFamilyIndexCount = 0;
swapchainCI.presentMode = swapchainPresentMode;
// Setting oldSwapChain to the saved handle of the previous swapchain aids in resource reuse and makes sure that we can still present already acquired images
swapchainCI.oldSwapchain = oldSwapchain;
// Setting clipped to VK_TRUE allows the implementation to discard rendering outside of the surface area
swapchainCI.clipped = VK_TRUE;
swapchainCI.compositeAlpha = compositeAlpha;
// Enable transfer source on swap chain images if supported
if (surfCaps.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT) {
swapchainCI.imageUsage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
}
// Enable transfer destination on swap chain images if supported
if (surfCaps.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_DST_BIT) {
swapchainCI.imageUsage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
}
VulkanDevice::CHECK_VK_RESULT(vkCreateSwapchainKHR(VulkanDevice::device, &swapchainCI, nullptr, &swapChain));
// If an existing swap chain is re-created, destroy the old swap chain and the ressources owned by the application (image views, images are owned by the swap chain)
if (oldSwapchain != VK_NULL_HANDLE) {
for (auto i = 0; i < images.size(); i++) {
vkDestroyImageView(VulkanDevice::device, imageViews[i], nullptr);
}
vkDestroySwapchainKHR(VulkanDevice::device, oldSwapchain, nullptr);
}
uint32_t imageCount{ 0 };
VulkanDevice::CHECK_VK_RESULT(vkGetSwapchainImagesKHR(VulkanDevice::device, swapChain, &imageCount, nullptr));
// Get the swap chain images
images.resize(imageCount);
VulkanDevice::CHECK_VK_RESULT(vkGetSwapchainImagesKHR(VulkanDevice::device, swapChain, &imageCount, images.data()));
// Get the swap chain buffers containing the image and imageview
imageViews.resize(imageCount);
for (auto i = 0; i < images.size(); i++)
{
VkImageViewCreateInfo colorAttachmentView = {};
colorAttachmentView.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
colorAttachmentView.pNext = NULL;
colorAttachmentView.format = colorFormat;
colorAttachmentView.components = {
VK_COMPONENT_SWIZZLE_R,
VK_COMPONENT_SWIZZLE_G,
VK_COMPONENT_SWIZZLE_B,
VK_COMPONENT_SWIZZLE_A
};
colorAttachmentView.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
colorAttachmentView.subresourceRange.baseMipLevel = 0;
colorAttachmentView.subresourceRange.levelCount = 1;
colorAttachmentView.subresourceRange.baseArrayLayer = 0;
colorAttachmentView.subresourceRange.layerCount = 1;
colorAttachmentView.viewType = VK_IMAGE_VIEW_TYPE_2D;
colorAttachmentView.flags = 0;
colorAttachmentView.image = images[i];
VulkanDevice::CHECK_VK_RESULT(vkCreateImageView(VulkanDevice::device, &colorAttachmentView, nullptr, &imageViews[i]));
}
}
WindowWaylandVulkan::WindowWaylandVulkan(std::string name, std::uint32_t width, std::uint32_t height) : WindowWayland(name, width, height) {
VkWaylandSurfaceCreateInfoKHR createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR;
createInfo.display = display;
createInfo.surface = surface;
VulkanDevice::CHECK_VK_RESULT(vkCreateWaylandSurfaceKHR(VulkanDevice::instance, &createInfo, NULL, &vulkanSurface));
// Get list of supported surface formats
std::uint32_t formatCount;
VulkanDevice::CHECK_VK_RESULT(vkGetPhysicalDeviceSurfaceFormatsKHR(VulkanDevice::physDevice, vulkanSurface, &formatCount, NULL));
assert(formatCount > 0);
std::vector<VkSurfaceFormatKHR> surfaceFormats(formatCount);
VulkanDevice::CHECK_VK_RESULT(vkGetPhysicalDeviceSurfaceFormatsKHR(VulkanDevice::physDevice, vulkanSurface, &formatCount, surfaceFormats.data()));
// We want to get a format that best suits our needs, so we try to get one from a set of preferred formats
// Initialize the format to the first one returned by the implementation in case we can't find one of the preffered formats
VkSurfaceFormatKHR selectedFormat = surfaceFormats[0];
std::vector<VkFormat> preferredImageFormats = {
VK_FORMAT_R8G8B8A8_UNORM,
};
for (auto& availableFormat : surfaceFormats) {
if (std::find(preferredImageFormats.begin(), preferredImageFormats.end(), availableFormat.format) != preferredImageFormats.end()) {
selectedFormat = availableFormat;
break;
}
}
colorFormat = selectedFormat.format;
colorSpace = selectedFormat.colorSpace;
CreateSwapchain();
std::array<VkAttachmentDescription, 2> attachments = {};
// Color attachment
attachments[0].format = colorFormat;
attachments[0].samples = VK_SAMPLE_COUNT_1_BIT;
attachments[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachments[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachments[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachments[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachments[0].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
attachments[0].finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
// Depth attachment
attachments[1].format = VulkanDevice::depthFormat;
attachments[1].samples = VK_SAMPLE_COUNT_1_BIT;
attachments[1].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachments[1].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachments[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachments[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachments[1].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
attachments[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkAttachmentReference colorReference = {};
colorReference.attachment = 0;
colorReference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkAttachmentReference depthReference = {};
depthReference.attachment = 1;
depthReference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkSubpassDescription subpassDescription = {};
subpassDescription.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpassDescription.colorAttachmentCount = 1;
subpassDescription.pColorAttachments = &colorReference;
subpassDescription.pDepthStencilAttachment = &depthReference;
subpassDescription.inputAttachmentCount = 0;
subpassDescription.pInputAttachments = nullptr;
subpassDescription.preserveAttachmentCount = 0;
subpassDescription.pPreserveAttachments = nullptr;
subpassDescription.pResolveAttachments = nullptr;
// Subpass dependencies for layout transitions
std::array<VkSubpassDependency, 2> dependencies{};
dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL;
dependencies[0].dstSubpass = 0;
dependencies[0].srcStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
dependencies[0].dstStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
dependencies[0].srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
dependencies[0].dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT;
dependencies[0].dependencyFlags = 0;
dependencies[1].srcSubpass = VK_SUBPASS_EXTERNAL;
dependencies[1].dstSubpass = 0;
dependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependencies[1].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependencies[1].srcAccessMask = 0;
dependencies[1].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT;
dependencies[1].dependencyFlags = 0;
VkRenderPassCreateInfo renderPassInfo = {};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
renderPassInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
renderPassInfo.pAttachments = attachments.data();
renderPassInfo.subpassCount = 1;
renderPassInfo.pSubpasses = &subpassDescription;
renderPassInfo.dependencyCount = static_cast<uint32_t>(dependencies.size());
renderPassInfo.pDependencies = dependencies.data();
VulkanDevice::CHECK_VK_RESULT(vkCreateRenderPass(VulkanDevice::device, &renderPassInfo, nullptr, &renderPass));
VkImageCreateInfo imageCI{};
imageCI.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
imageCI.imageType = VK_IMAGE_TYPE_2D;
imageCI.format = VulkanDevice::depthFormat;
imageCI.extent = { width, height, 1 };
imageCI.mipLevels = 1;
imageCI.arrayLayers = 1;
imageCI.samples = VK_SAMPLE_COUNT_1_BIT;
imageCI.tiling = VK_IMAGE_TILING_OPTIMAL;
imageCI.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
VulkanDevice::CHECK_VK_RESULT(vkCreateImage(VulkanDevice::device, &imageCI, nullptr, &depthStencil.image));
VkMemoryRequirements memReqs{};
vkGetImageMemoryRequirements(VulkanDevice::device, depthStencil.image, &memReqs);
VkMemoryAllocateInfo memAllloc{};
memAllloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
memAllloc.allocationSize = memReqs.size;
memAllloc.memoryTypeIndex = VulkanDevice::GetMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
VulkanDevice::CHECK_VK_RESULT(vkAllocateMemory(VulkanDevice::device, &memAllloc, nullptr, &depthStencil.memory));
VulkanDevice::CHECK_VK_RESULT(vkBindImageMemory(VulkanDevice::device, depthStencil.image, depthStencil.memory, 0));
VkImageViewCreateInfo imageViewCI{};
imageViewCI.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
imageViewCI.viewType = VK_IMAGE_VIEW_TYPE_2D;
imageViewCI.image = depthStencil.image;
imageViewCI.format = VulkanDevice::depthFormat;
imageViewCI.subresourceRange.baseMipLevel = 0;
imageViewCI.subresourceRange.levelCount = 1;
imageViewCI.subresourceRange.baseArrayLayer = 0;
imageViewCI.subresourceRange.layerCount = 1;
imageViewCI.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
VulkanDevice::CHECK_VK_RESULT(vkCreateImageView(VulkanDevice::device, &imageViewCI, nullptr, &depthStencil.view));
// Create frame buffers for every swap chain image
frameBuffers.resize(images.size());
for (uint32_t i = 0; i < frameBuffers.size(); i++)
{
const VkImageView attachments[2] = {
imageViews[i],
depthStencil.view
};
VkFramebufferCreateInfo frameBufferCreateInfo{};
frameBufferCreateInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
frameBufferCreateInfo.renderPass = renderPass;
frameBufferCreateInfo.attachmentCount = 2;
frameBufferCreateInfo.pAttachments = attachments;
frameBufferCreateInfo.width = width;
frameBufferCreateInfo.height = height;
frameBufferCreateInfo.layers = 1;
VulkanDevice::CHECK_VK_RESULT(vkCreateFramebuffer(VulkanDevice::device, &frameBufferCreateInfo, nullptr, &frameBuffers[i]));
}
drawCmdBuffers.resize(images.size());
VkCommandBufferAllocateInfo cmdBufAllocateInfo = vks::initializers::commandBufferAllocateInfo(VulkanDevice::commandPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, static_cast<uint32_t>(drawCmdBuffers.size()));
VulkanDevice::CHECK_VK_RESULT(vkAllocateCommandBuffers(VulkanDevice::device, &cmdBufAllocateInfo, drawCmdBuffers.data()));
VkSemaphoreCreateInfo semaphoreCreateInfo = vks::initializers::semaphoreCreateInfo();
VulkanDevice::CHECK_VK_RESULT(vkCreateSemaphore(VulkanDevice::device, &semaphoreCreateInfo, nullptr, &semaphores.presentComplete));
VulkanDevice::CHECK_VK_RESULT(vkCreateSemaphore(VulkanDevice::device, &semaphoreCreateInfo, nullptr, &semaphores.renderComplete));
// Set up submit info structure
// Semaphores will stay the same during application lifetime
// Command buffer submission info is set by each example
submitInfo = vks::initializers::submitInfo();
submitInfo.pWaitDstStageMask = &submitPipelineStages;
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = &semaphores.presentComplete;
submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = &semaphores.renderComplete;
}
WindowWaylandVulkan::~WindowWaylandVulkan() {
if (swapChain != VK_NULL_HANDLE) {
for (auto i = 0; i < images.size(); i++) {
vkDestroyImageView(VulkanDevice::device, imageViews[i], nullptr);
}
vkDestroySwapchainKHR(VulkanDevice::device, swapChain, nullptr);
}
if (vulkanSurface != VK_NULL_HANDLE) {
vkDestroySurfaceKHR(VulkanDevice::instance, vulkanSurface, nullptr);
}
}
VkCommandBuffer WindowWaylandVulkan::StartInit() {
VkCommandBufferBeginInfo cmdBufInfo = vks::initializers::commandBufferBeginInfo();
VulkanDevice::CHECK_VK_RESULT(vkBeginCommandBuffer(drawCmdBuffers[currentBuffer], &cmdBufInfo));
return drawCmdBuffers[currentBuffer];
}
void WindowWaylandVulkan::FinishInit() {
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer];
VulkanDevice::CHECK_VK_RESULT(vkEndCommandBuffer(drawCmdBuffers[currentBuffer]));
VulkanDevice::CHECK_VK_RESULT(vkQueueSubmit(VulkanDevice::queue, 1, &submitInfo, VK_NULL_HANDLE));
VulkanDevice::CHECK_VK_RESULT(vkQueueWaitIdle(VulkanDevice::queue));
}
void WindowWaylandVulkan::StartAsync() {
thread = std::thread(&WindowWaylandVulkan::StartSync, this);
}
void WindowWaylandVulkan::StartSync() {
while (open && wl_display_dispatch(display) != -1) {
// Acquire the next image from the swap chain
VulkanDevice::CHECK_VK_RESULT(vkAcquireNextImageKHR(VulkanDevice::device, swapChain, UINT64_MAX, semaphores.presentComplete, (VkFence)nullptr, &currentBuffer));
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer];
VkCommandBufferBeginInfo cmdBufInfo = vks::initializers::commandBufferBeginInfo();
VkClearValue clearValues[2];
clearValues[0].color = { };;
clearValues[1].depthStencil = { 1.0f, 0 };
VulkanDevice::CHECK_VK_RESULT(vkBeginCommandBuffer(drawCmdBuffers[currentBuffer], &cmdBufInfo));
VkImageSubresourceRange range{};
range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
range.baseMipLevel = 0;
range.levelCount = VK_REMAINING_MIP_LEVELS;
range.baseArrayLayer = 0;
range.layerCount = VK_REMAINING_ARRAY_LAYERS;
VkImageSubresourceRange depth_range{range};
depth_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
image_layout_transition(drawCmdBuffers[currentBuffer],
images[currentBuffer],
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
0,
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
range);
image_layout_transition(drawCmdBuffers[currentBuffer],
depthStencil.image,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL,
depth_range);
VkRenderingAttachmentInfoKHR color_attachment_info = {VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR, VK_NULL_HANDLE};
color_attachment_info.imageView = imageViews[currentBuffer];
color_attachment_info.imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
color_attachment_info.resolveMode = VK_RESOLVE_MODE_NONE;
color_attachment_info.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
color_attachment_info.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
color_attachment_info.clearValue = { 0.0f, 0.0f, 0.2f, 1.0f };
VkRenderingAttachmentInfoKHR depth_attachment_info = {VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR, VK_NULL_HANDLE};
depth_attachment_info.imageView = depthStencil.view;
depth_attachment_info.imageLayout = VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL;
depth_attachment_info.resolveMode = VK_RESOLVE_MODE_NONE;
depth_attachment_info.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
depth_attachment_info.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
depth_attachment_info.clearValue = { 1.0f, 0 };
VkRenderingInfo render_info = {VK_STRUCTURE_TYPE_RENDERING_INFO_KHR,VK_NULL_HANDLE,0};
render_info.renderArea = VkRect2D{VkOffset2D{}, VkExtent2D{width, height}};
render_info.viewMask = 0;
render_info.layerCount = 1;
render_info.colorAttachmentCount = 1;
render_info.pColorAttachments = &color_attachment_info;
render_info.pDepthAttachment = &depth_attachment_info;
render_info.pStencilAttachment = VK_NULL_HANDLE;
VulkanDevice::vkCmdBeginRenderingKHRProc(drawCmdBuffers[currentBuffer], &render_info);
VkViewport viewport = vks::initializers::viewport((float)width, (float)height, 0.0f, 1.0f);
vkCmdSetViewport(drawCmdBuffers[currentBuffer], 0, 1, &viewport);
VkRect2D scissor = vks::initializers::rect2D(width, height, 0, 0);
vkCmdSetScissor(drawCmdBuffers[currentBuffer], 0, 1, &scissor);
onDraw.Invoke(drawCmdBuffers[currentBuffer]);
mouseDelta = {0, 0};
VulkanDevice::vkCmdEndRenderingKHRProc(drawCmdBuffers[currentBuffer]);
image_layout_transition(drawCmdBuffers[currentBuffer],
images[currentBuffer],
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
range
);
VulkanDevice::CHECK_VK_RESULT(vkEndCommandBuffer(drawCmdBuffers[currentBuffer]));
VulkanDevice::CHECK_VK_RESULT(vkQueueSubmit(VulkanDevice::queue, 1, &submitInfo, VK_NULL_HANDLE));
VkPresentInfoKHR presentInfo = {};
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
presentInfo.pNext = NULL;
presentInfo.swapchainCount = 1;
presentInfo.pSwapchains = &swapChain;
presentInfo.pImageIndices = &currentBuffer;
// Check if a wait semaphore has been specified to wait for before presenting the image
if (semaphores.renderComplete != VK_NULL_HANDLE)
{
presentInfo.pWaitSemaphores = &semaphores.renderComplete;
presentInfo.waitSemaphoreCount = 1;
}
VulkanDevice::CHECK_VK_RESULT(vkQueuePresentKHR(VulkanDevice::queue, &presentInfo));
VulkanDevice::CHECK_VK_RESULT(vkQueueWaitIdle(VulkanDevice::queue));
}
}

View file

@ -0,0 +1,181 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include <errno.h>
#include <fcntl.h>
#include <linux/input.h>
#include <string>
#include <sys/mman.h>
#include <unistd.h>
#include <wayland-cursor.h>
#include <xkbcommon/xkbcommon.h>
#include <iostream>
#include <vulkan/vulkan.h>
#include <vulkan/vulkan_wayland.h>
#include <wayland-client.h>
#include <cstring>
#include "../../lib/xdg-shell-client-protocol.h"
#include "../../lib/wayland-xdg-decoration-unstable-v1-client-protocol.h"
#define _POSIX_C_SOURCE 200809L
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <sys/mman.h>
#include <time.h>
#include <unistd.h>
#include <print>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#include <wayland-client.h>
#include <wayland-client-protocol.h>
#include <linux/input-event-codes.h>
#include <cmath>
#include <thread>
module Crafter.Graphics;
import Crafter.Event;
using namespace Crafter;
static void randname(char *buf) {
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
long r = ts.tv_nsec;
for (int i = 0; i < 6; ++i) {
buf[i] = 'A'+(r&15)+(r&16)*2;
r >>= 5;
}
}
static int anonymous_shm_open(void) {
char name[] = "/hello-wayland-XXXXXX";
int retries = 100;
do {
randname(name + strlen(name) - 6);
--retries;
// shm_open guarantees that O_CLOEXEC is set
int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0600);
if (fd >= 0) {
shm_unlink(name);
return fd;
}
} while (retries > 0 && errno == EEXIST);
return -1;
}
int create_shm_file(off_t size) {
int fd = anonymous_shm_open();
if (fd < 0) {
return fd;
}
if (ftruncate(fd, size) < 0) {
close(fd);
return -1;
}
return fd;
}
void ScaleBitmapR8G8B8(Pixel_BU8_GU8_RU8_AU8* dst, const Pixel_BU8_GU8_RU8_AU8* src, std::uint32_t srcWidth, std::uint32_t srcHeight, std::uint32_t dstWidth, std::uint32_t dstHeight) {
for (std::uint32_t y = 0; y < dstHeight; y++) {
std::uint32_t srcY = y * srcHeight / dstHeight;
for (std::uint32_t x = 0; x < dstWidth; x++) {
std::uint32_t srcX = x * srcWidth / dstWidth;
const Pixel_BU8_GU8_RU8_AU8* srcPixel = src + (srcY * srcWidth + srcX);
Pixel_BU8_GU8_RU8_AU8* dstPixel = dst + (y * dstWidth + x);
dstPixel[0] = srcPixel[0];
}
}
}
WindowWaylandWayland::WindowWaylandWayland(std::string name, std::uint32_t width, std::uint32_t height) : WindowWayland(name, width, height) {
// Create a wl_buffer, attach it to the surface and commit the surface
int stride = width * 4;
int size = stride * height;
// Allocate a shared memory file with the right size
int fd = create_shm_file(size);
if (fd < 0) {
fprintf(stderr, "creating a buffer file for %d B failed: %m\n", size);
}
// Map the shared memory file
framebuffer = reinterpret_cast<Pixel_BU8_GU8_RU8_AU8*>(mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0));
if (framebuffer == MAP_FAILED) {
fprintf(stderr, "mmap failed: %m\n");
close(fd);
}
// Create a wl_buffer from our shared memory file descriptor
wl_shm_pool *pool = wl_shm_create_pool(shm, fd, size);
buffer = wl_shm_pool_create_buffer(pool, 0, width, height, stride, WL_SHM_FORMAT_ARGB8888);
wl_shm_pool_destroy(pool);
// Now that we've mapped the file and created the wl_buffer, we no longer
// need to keep file descriptor opened
close(fd);
if (buffer == NULL) {
exit(EXIT_FAILURE);
}
wl_surface_attach(surface, buffer, 0, 0);
wl_surface_commit(surface);
}
WindowWaylandWayland::~WindowWaylandWayland() {
open = false;
thread.join();
}
void WindowWaylandWayland::StartAsync() {
thread = std::thread(&WindowWaylandWayland::StartSync, this);
}
void WindowWaylandWayland::StartSync() {
while (open && wl_display_dispatch(display) != -1) {
wl_surface_attach(surface, buffer, 0, 0);
for(const UiElement& element : elements) {
ScaleData data = ScaleElement(element);
std::vector<Pixel_BU8_GU8_RU8_AU8> scaled(data.width*data.height);
ScaleBitmapR8G8B8(scaled.data(), element.buffer.data(), element.bufferWidth, element.bufferHeight, data.width, data.height);
for(std::int32_t x = data.x; x-data.x < data.width; x++) {
for(std::int32_t y = data.y; y-data.y < data.height; y++) {
if(x > 0 && x < width && y > 0 && y < height) {
framebuffer[y*width+x] = scaled[(y-data.y)*data.width+(x-data.x)];
}
}
}
wl_surface_damage(surface, data.x, data.y, data.width, data.height);
}
wl_surface_commit(surface);
}
}

71
src/source/main.cpp Normal file
View file

@ -0,0 +1,71 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <iostream>
#include <exception>
#include <thread>
#include <cstdlib>
#include <vulkan/vulkan.h>
#include "../../lib/VulkanInitializers.hpp"
import Crafter.Graphics;
import Crafter.Asset;
import Crafter.Event;
import Crafter.Math;
using namespace Crafter;
typedef VulkanShader<"MeshShaderMixedVoxelGrid.spirv", "main", VK_SHADER_STAGE_MESH_BIT_EXT, 2, {{{VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0}, {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}}}> MeshVulkanShader;
typedef VulkanShader<"FragmentShaderVertexColor.spirv", "main", VK_SHADER_STAGE_FRAGMENT_BIT, 0, {}> FragmentShader;
typedef VulkanPipeline<MeshVulkanShader, FragmentShader> Pipeline;
int main() {
VulkanDevice::CreateDevice();
MeshVulkanShader::CreateShader();
FragmentShader::CreateShader();
Pipeline::CreatePipeline();
WindowWaylandVulkan window("Crafter.Graphics", 1280, 720);
Camera camera(1.57079633, 1280.0f / 720.0f, 0.01, 512);
camera.view = MatrixRowMajor<float, 4, 4, 1>::Translation(0, 0, 10);
camera.Update();
VkCommandBuffer cmd = window.StartInit();
DescriptorSet<MeshVulkanShader, FragmentShader> descriptors;
VoxelShader<uint> meshShader(1, 4, 4, &camera);
for(uint32_t i = 0; i < 16; i++) {
meshShader.grid.value[i] = 1;
}
meshShader.WriteDescriptors(descriptors.set[0]);
meshShader.Update();
window.FinishInit();
EventListener<VkCommandBuffer> listener(&window.onDraw, [&descriptors, &meshShader](VkCommandBuffer cmd){
vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, Pipeline::pipelineLayout, 0, 2, &descriptors.set[0], 0, NULL);
vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, Pipeline::pipeline);
VulkanDevice::vkCmdDrawMeshTasksEXTProc(cmd, meshShader.threadCount, 1, 1);
});
window.Start();
while(true) {
}
}