Rework tracing system and enum creators

- Rework tracing system, now using "{}" for formatting instead of the
  standard %s,%d,%f formatting that C++ uses.
- Rework enums creators to not take in namespace
- Fix single use CommandBuffers sometimes failing due to indexing them
  with the current frame in flight
- Add DropEvent to Window
This commit is contained in:
Thraix
2026-05-03 12:40:47 +02:00
parent 9d5a5314a7
commit 9a3b3aa13c
48 changed files with 476 additions and 277 deletions
+3 -2
View File
@@ -3,6 +3,7 @@
#include <fstream>
#include "copium/util/FileSystem.h"
#include "copium/util/Trace.h"
namespace Copium
{
@@ -30,7 +31,7 @@ namespace Copium
Load(metaFile, assetType);
return;
}
CP_WARN("Unknown Asset type in file: %s", metaFile.GetFilePath().c_str());
CP_WARN("Unknown Asset type in file: {}", metaFile.GetFilePath());
}
const std::string& AssetFile::GetPath() const
@@ -48,7 +49,7 @@ namespace Copium
MetaFileClass& metaClass = metaFile.GetMetaClass(className);
if (!metaClass.HasValue("uuid"))
{
CP_WARN("Asset (%s) has no UUID assigned, generating new one", path.c_str());
CP_WARN("Asset ({}) has no UUID assigned, generating new one", path);
metaClass.AddValue("uuid", Uuid{}.ToString());
std::fstream file{path};
file << metaFile;
+15 -16
View File
@@ -3,8 +3,8 @@
#include <filesystem>
#include <fstream>
#include "copium/util/Common.h"
#include "copium/util/MetaFile.h"
#include "copium/util/Trace.h"
namespace Copium
{
@@ -34,12 +34,12 @@ namespace Copium
.c_str();
try
{
CP_DEBUG("Registering Asset: %s", assetPath.c_str());
CP_DEBUG("Registering Asset: {}", assetPath);
cachedAssetFiles.emplace_back(assetPath);
}
catch (RuntimeException& exception)
{
CP_ERR("Failed to register Asset: %s", assetPath.c_str());
CP_ERR("Failed to register Asset: {}", assetPath);
}
}
}
@@ -68,7 +68,7 @@ namespace Copium
Asset& AssetManager::LoadAsset(const std::string& assetPath)
{
CP_DEBUG("Loading Asset: %s", assetPath.c_str());
CP_DEBUG("Loading Asset: {}", assetPath);
for (auto& dir : assetDirs)
{
@@ -80,12 +80,12 @@ namespace Copium
return LoadAssetFromPath(path);
}
CP_ABORT("Unknown Asset: %s", assetPath.c_str());
CP_ABORT("Unknown Asset: {}", assetPath);
}
Asset& AssetManager::LoadAsset(const Uuid& uuid)
{
CP_DEBUG("Loading uuid Asset: %s", uuid.ToString().c_str());
CP_DEBUG("Loading uuid Asset: {}", uuid);
for (auto&& assetFile : cachedAssetFiles)
{
if (assetFile.NeedReload())
@@ -96,16 +96,16 @@ namespace Copium
return LoadAssetFromPath(assetFile.GetPath());
}
CP_ABORT("Asset not found with uuid=%s", uuid.ToString().c_str());
CP_ABORT("Asset not found with uuid={}", uuid);
// TODO: Reload the assetCache to see if a new file has appeared with that uuid
}
AssetId AssetManager::DuplicateAsset(AssetId id)
{
auto it = assets.find(id);
CP_ASSERT(it != assets.end(), "Failed to find asset with id=%d", id);
CP_ASSERT(it != assets.end(), "Failed to find asset with id={}", id);
CP_DEBUG("Duplicating asset: %s", it->second->GetName().c_str());
CP_DEBUG("Duplicating asset: {}", it->second->GetName());
it->second->metaData.loadCount++;
return id;
}
@@ -118,8 +118,7 @@ namespace Copium
CP_WARN("Asset not loaded");
return;
}
CP_DEBUG(
"Unloading Asset: %s (%d instances left)", it->second->GetName().c_str(), it->second->metaData.loadCount - 1);
CP_DEBUG("Unloading Asset: {} ({} instances left)", it->second->GetName(), it->second->metaData.loadCount - 1);
it->second->metaData.loadCount--;
if (it->second->metaData.loadCount > 0)
@@ -141,7 +140,7 @@ namespace Copium
{
if (assets.empty())
return;
CP_WARN("Performing auto clean up of %d non unloaded assets", assets.size());
CP_WARN("Performing auto clean up of {} non unloaded assets", assets.size());
while (!assets.empty())
{
UnloadAsset(assets.begin()->second->GetId());
@@ -152,10 +151,10 @@ namespace Copium
Asset& AssetManager::RegisterRuntimeAsset(const std::string& name, const Uuid& uuid, std::unique_ptr<Asset>&& asset)
{
CP_DEBUG("Registering Runtime Asset: %s", name.c_str());
CP_DEBUG("Registering Runtime Asset: {}", name);
auto it = nameToAssetCache.find(name);
CP_ASSERT(it == nameToAssetCache.end(), "Asset already exists: %s", name.c_str());
CP_ASSERT(it == nameToAssetCache.end(), "Asset already exists: {}", name);
AssetId id = runtimeAssetId++;
Asset* asset2 = assets.emplace(id, std::move(asset)).first->second.get();
@@ -169,7 +168,7 @@ namespace Copium
Asset& AssetManager::LoadAssetFromPath(const std::string& filepath)
{
CP_DEBUG("Loading Asset: %s", filepath.c_str());
CP_DEBUG("Loading Asset: {}", filepath);
auto it = pathToAssetCache.find(filepath);
if (it != pathToAssetCache.end())
{
@@ -184,6 +183,6 @@ namespace Copium
if (metaFile.HasMetaClass(assetType.first))
return assetType.second(metaFile, assetType.first);
}
CP_ABORT("Unknown Asset type: %s", filepath.c_str());
CP_ABORT("Unknown Asset type: {}", filepath);
}
}
+3 -2
View File
@@ -2,11 +2,12 @@
#include <functional>
#include <map>
#include <memory>
#include <vector>
#include "copium/asset/Asset.h"
#include "copium/asset/AssetFile.h"
#include "copium/util/Common.h"
#include "copium/util/Trace.h"
namespace Copium
{
@@ -42,7 +43,7 @@ namespace Copium
static void RegisterAssetType(const std::string& assetType)
{
CP_ASSERT(assetTypes.emplace(assetType, &AssetManager::CreateAsset<AssetType>).second,
"Asset type already exists: %s",
"Asset type already exists: {}",
assetType.c_str());
AssetFile::RegisterAssetType(assetType);
}
@@ -1,6 +1,7 @@
#include "copium/buffer/CommandBuffer.h"
#include "copium/core/Vulkan.h"
#include "copium/util/Trace.h"
namespace Copium
{
@@ -16,7 +17,7 @@ namespace Copium
commandBuffers.resize(SwapChain::MAX_FRAMES_IN_FLIGHT);
break;
default:
CP_ABORT("Unreachable switch case: %s", ToString(type).c_str());
CP_ABORT("Unreachable switch case: {}", type);
}
VkCommandBufferAllocateInfo allocateInfo{};
@@ -49,33 +50,46 @@ namespace Copium
beginInfo.flags = 0;
beginInfo.pInheritanceInfo = nullptr;
int index = Vulkan::GetSwapChain().GetFlightIndex();
switch (type)
{
case CommandBufferType::SingleUse:
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
index = 0;
break;
case CommandBufferType::Dynamic:
break;
default:
CP_ABORT("Unreachable switch case: %s", ToString(type).c_str());
CP_ABORT("Unreachable switch case: {}", type);
}
vkResetCommandBuffer(commandBuffers[Vulkan::GetSwapChain().GetFlightIndex()], 0);
CP_VK_ASSERT(vkBeginCommandBuffer(commandBuffers[Vulkan::GetSwapChain().GetFlightIndex()], &beginInfo),
"Failed to begin command buffer");
vkResetCommandBuffer(commandBuffers[index], 0);
CP_VK_ASSERT(vkBeginCommandBuffer(commandBuffers[index], &beginInfo), "Failed to begin command buffer");
}
void CommandBuffer::End()
{
vkEndCommandBuffer(commandBuffers[Vulkan::GetSwapChain().GetFlightIndex()]);
int index = Vulkan::GetSwapChain().GetFlightIndex();
if (type == CommandBufferType::SingleUse)
{
index = 0;
}
vkEndCommandBuffer(commandBuffers[index]);
}
void CommandBuffer::Submit()
{
int index = Vulkan::GetSwapChain().GetFlightIndex();
if (type == CommandBufferType::SingleUse)
{
index = 0;
}
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffers[Vulkan::GetSwapChain().GetFlightIndex()];
submitInfo.pCommandBuffers = &commandBuffers[index];
vkQueueSubmit(Vulkan::GetDevice().GetGraphicsQueue(), 1, &submitInfo, VK_NULL_HANDLE);
// TODO: if singleUse?
@@ -84,6 +98,11 @@ namespace Copium
CommandBuffer::operator VkCommandBuffer() const
{
return commandBuffers[Vulkan::GetSwapChain().GetFlightIndex()];
int index = Vulkan::GetSwapChain().GetFlightIndex();
if (type == CommandBufferType::SingleUse)
{
index = 0;
}
return commandBuffers[index];
}
}
}
@@ -5,11 +5,10 @@
#include "copium/util/Common.h"
#include "copium/util/Enum.h"
#define CP_COMMAND_BUFFER_TYPE_ENUMS SingleUse, Dynamic
CP_ENUM_CREATOR(Copium, CommandBufferType, CP_COMMAND_BUFFER_TYPE_ENUMS);
namespace Copium
{
CP_ENUM_CREATOR(CommandBufferType, SingleUse, Dynamic);
class CommandBuffer
{
CP_DELETE_COPY_AND_MOVE_CTOR(CommandBuffer);
@@ -1,6 +1,5 @@
#include "copium/buffer/Framebuffer.h"
#include "copium/asset/AssetManager.h"
#include "copium/buffer/CommandBuffer.h"
#include "copium/core/Vulkan.h"
#include "copium/sampler/Image.h"
@@ -15,8 +14,8 @@ namespace Copium
width = attachment.GetWidth();
height = attachment.GetHeight();
CP_ASSERT(width > 0, "Width of framebuffer is less than 1: %d", width);
CP_ASSERT(height > 0, "Height of framebuffer is less than 1: %d", height);
CP_ASSERT(width > 0, "Width of framebuffer is less than 1: {}", width);
CP_ASSERT(height > 0, "Height of framebuffer is less than 1: {}", height);
InitializeDepthBuffer();
InitializeRenderPass();
@@ -27,8 +26,8 @@ namespace Copium
: width{width},
height{height}
{
CP_ASSERT(width > 0, "Width of framebuffer is less than 1: %d", width);
CP_ASSERT(height > 0, "Height of framebuffer is less than 1: %d", height);
CP_ASSERT(width > 0, "Width of framebuffer is less than 1: {}", width);
CP_ASSERT(height > 0, "Height of framebuffer is less than 1: {}", height);
InitializeImage(samplerCreator);
InitializeDepthBuffer();
@@ -51,8 +50,8 @@ namespace Copium
void Framebuffer::Resize(int width, int height)
{
CP_ASSERT(width > 0, "Width of framebuffer is less than 1: %d", width);
CP_ASSERT(height > 0, "Height of framebuffer is less than 1: %d", height);
CP_ASSERT(width > 0, "Width of framebuffer is less than 1: {}", width);
CP_ASSERT(height > 0, "Height of framebuffer is less than 1: {}", height);
Vulkan::GetDevice().WaitIdle();
this->width = width;
@@ -2,6 +2,8 @@
#include <vulkan/vulkan.hpp>
#include "copium/util/Trace.h"
namespace Copium
{
IndexBuffer::IndexBuffer(int indexCount)
+1 -1
View File
@@ -20,4 +20,4 @@ namespace Copium
void Draw(const CommandBuffer& commandBuffer);
void Draw(const CommandBuffer& commandBuffer, int indices);
};
}
}
@@ -25,7 +25,7 @@ namespace Copium
void UniformBuffer::Set(const std::string& str, const glm::mat3& data)
{
CP_ASSERT(binding.GetUniformType(str) == UniformType::Mat3, "Uniform type missmatch = %s", str.c_str());
CP_ASSERT(binding.GetUniformType(str) == UniformType::Mat3, "Uniform type missmatch = {}", str);
uint32_t offset = binding.GetUniformOffset(str);
// memcpy(buffer.data() + offset, &data[0], sizeof(glm::vec3));
// memcpy(buffer.data() + offset + 16, &data[1], sizeof(glm::vec3));
@@ -36,42 +36,42 @@ namespace Copium
void UniformBuffer::Set(const std::string& str, const glm::mat4& data)
{
CP_ASSERT(binding.GetUniformType(str) == UniformType::Mat4, "Uniform type missmatch = %s", str.c_str());
CP_ASSERT(binding.GetUniformType(str) == UniformType::Mat4, "Uniform type missmatch = {}", str);
uint32_t offset = binding.GetUniformOffset(str);
memcpy(buffer.data() + offset, &data, sizeof(glm::mat4));
}
void UniformBuffer::Set(const std::string& str, const glm::vec2& data)
{
CP_ASSERT(binding.GetUniformType(str) == UniformType::Vec2, "Uniform type missmatch = %s", str.c_str());
CP_ASSERT(binding.GetUniformType(str) == UniformType::Vec2, "Uniform type missmatch = {}", str);
uint32_t offset = binding.GetUniformOffset(str);
memcpy(buffer.data() + offset, &data, sizeof(glm::vec2));
}
void UniformBuffer::Set(const std::string& str, const glm::vec3& data)
{
CP_ASSERT(binding.GetUniformType(str) == UniformType::Vec3, "Uniform type missmatch = %s", str.c_str());
CP_ASSERT(binding.GetUniformType(str) == UniformType::Vec3, "Uniform type missmatch = {}", str);
uint32_t offset = binding.GetUniformOffset(str);
memcpy(buffer.data() + offset, &data, sizeof(glm::vec3));
}
void UniformBuffer::Set(const std::string& str, const glm::vec4& data)
{
CP_ASSERT(binding.GetUniformType(str) == UniformType::Vec4, "Uniform type missmatch = %s", str.c_str());
CP_ASSERT(binding.GetUniformType(str) == UniformType::Vec4, "Uniform type missmatch = {}", str);
uint32_t offset = binding.GetUniformOffset(str);
memcpy(buffer.data() + offset, &data, sizeof(glm::vec4));
}
void UniformBuffer::Set(const std::string& str, float data)
{
CP_ASSERT(binding.GetUniformType(str) == UniformType::Float, "Uniform type missmatch = %s", str.c_str());
CP_ASSERT(binding.GetUniformType(str) == UniformType::Float, "Uniform type missmatch = {}", str);
uint32_t offset = binding.GetUniformOffset(str);
memcpy(buffer.data() + offset, &data, sizeof(float));
}
void UniformBuffer::Set(const std::string& str, int data)
{
CP_ASSERT(binding.GetUniformType(str) == UniformType::Int, "Uniform type missmatch = %s", str.c_str());
CP_ASSERT(binding.GetUniformType(str) == UniformType::Int, "Uniform type missmatch = {}", str);
uint32_t offset = binding.GetUniformOffset(str);
memcpy(buffer.data() + offset, &data, sizeof(int));
}
@@ -1,6 +1,7 @@
#include "copium/core/DebugMessenger.h"
#include "copium/core/Instance.h"
#include "copium/util/Trace.h"
namespace Copium
{
@@ -64,9 +65,9 @@ namespace Copium
if (messageSeverity >= VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT)
{
if (messageSeverity >= VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT)
CP_ABORT("%s", pCallbackData->pMessage);
CP_ABORT("{}", pCallbackData->pMessage);
else
CP_WARN("%s", pCallbackData->pMessage);
CP_WARN("{}", pCallbackData->pMessage);
}
return VK_FALSE;
}
+2 -2
View File
@@ -111,7 +111,7 @@ namespace Copium
{
VkPhysicalDeviceProperties deviceProperties;
vkGetPhysicalDeviceProperties(device, &deviceProperties);
CP_INFO_CONT("\t%s", deviceProperties.deviceName);
CP_INFO_CONT("\t{}", deviceProperties.deviceName);
devicePriorities.emplace_back(device, GetPhysicalDevicePriority(device));
}
@@ -125,7 +125,7 @@ namespace Copium
VkPhysicalDeviceProperties deviceProperties;
vkGetPhysicalDeviceProperties(it->first, &deviceProperties);
physicalDevice = it->first;
CP_INFO("Selecting device: %s", deviceProperties.deviceName);
CP_INFO("Selecting device: {}", deviceProperties.deviceName);
}
void Device::InitializeLogicalDevice()
+4 -4
View File
@@ -1,8 +1,8 @@
#include "Instance.h"
#include "copium/core/Instance.h"
#include <GLFW/glfw3.h>
#include "copium/util/Common.h"
#include "copium/util/Trace.h"
namespace Copium
{
@@ -43,7 +43,7 @@ namespace Copium
CP_INFO("Supported Extensions:");
for (auto&& extension : extensions)
{
CP_INFO_CONT("\t%s", extension.extensionName);
CP_INFO_CONT("\t{}", extension.extensionName);
}
std::vector<const char*> layers{};
@@ -89,7 +89,7 @@ namespace Copium
CP_INFO("Supported Layers:");
for (auto&& availableLayer : availableLayers)
{
CP_INFO_CONT("\t%s", availableLayer.layerName);
CP_INFO_CONT("\t{}", availableLayer.layerName);
}
for (auto&& layer : layers)
+2
View File
@@ -1,5 +1,7 @@
#pragma once
#include <memory>
#include "copium/core/DebugMessenger.h"
namespace Copium
+1
View File
@@ -3,6 +3,7 @@
#include <GLFW/glfw3.h>
#include <vulkan/vulkan.h>
#include <memory>
#include <vector>
#include "copium/buffer/CommandBuffer.h"
+3 -3
View File
@@ -31,7 +31,7 @@ namespace Copium
device = std::make_unique<Device>();
swapChain = std::make_unique<SwapChain>();
imGuiInstance = std::make_unique<ImGuiInstance>();
CP_INFO("Initialized Vulkan in %f seconds", timer.Elapsed());
CP_INFO("Initialized Vulkan in {} seconds", timer.Elapsed());
timer.Start();
AssetManager::RegisterAssetType<Texture2D>("Texture2D");
@@ -48,7 +48,7 @@ namespace Copium
"empty_texture2d", std::make_unique<Texture2D>(std::vector<uint8_t>{255, 0, 255, 255}, 1, 1, SamplerCreator{})};
whiteTexture2D = AssetHandle<Texture2D>{
"white_texture2d", std::make_unique<Texture2D>(std::vector<uint8_t>{255, 255, 255, 255}, 1, 1, SamplerCreator{})};
CP_INFO("Initialized AssetManager in %f seconds", timer.Elapsed());
CP_INFO("Initialized AssetManager in {} seconds", timer.Elapsed());
}
void Vulkan::Destroy()
@@ -108,6 +108,6 @@ namespace Copium
void Vulkan::glfw_error_callback(int error, const char* description)
{
CP_ABORT("GLFW Error %d: %s\n", error, description);
CP_ABORT("GLFW Error {}: {}\n", error, description);
}
}
+13 -1
View File
@@ -3,6 +3,7 @@
#include <GLFW/glfw3.h>
#include "copium/core/Vulkan.h"
#include "copium/event/DropEvent.h"
#include "copium/event/EventDispatcher.h"
#include "copium/event/Input.h"
#include "copium/event/KeyPressEvent.h"
@@ -101,7 +102,7 @@ namespace Copium
break;
}
default:
CP_ABORT("Unreachable switch case: %s", ToString(mode).c_str());
CP_ABORT("Unreachable switch case: {}", mode);
}
CP_ASSERT(window, "Failed to initialize glfw window");
@@ -113,6 +114,7 @@ namespace Copium
glfwSetCursorPosCallback(window, MouseMoveCallback);
glfwSetWindowFocusCallback(window, WindowFocusCallback);
glfwSetScrollCallback(window, MouseScrollCallback);
glfwSetDropCallback(window, DropCallback);
}
void Window::InitializeSurface()
@@ -192,4 +194,14 @@ namespace Copium
{
EventDispatcher::QueueEvent(MouseScrollEvent{(int)xoffset, (int)yoffset});
}
void Window::DropCallback(GLFWwindow* window, int pathCount, const char* paths[])
{
std::vector<std::string> filePaths;
for (int i = 0; i < pathCount; i++)
{
filePaths.emplace_back(paths[i]);
}
EventDispatcher::QueueEvent(DropEvent{filePaths});
}
}
+4 -3
View File
@@ -5,14 +5,14 @@
#include "copium/util/Common.h"
#include "copium/util/Enum.h"
#define CP_WINDOW_MODE_ENUMS Fullscreen, BorderlessWindowed, Windowed
CP_ENUM_CREATOR(Copium, WindowMode, CP_WINDOW_MODE_ENUMS);
#define CP_WINDOW_MODE_ENUMS
struct GLFWwindow;
namespace Copium
{
CP_ENUM_CREATOR(WindowMode, Fullscreen, BorderlessWindowed, Windowed);
class Window final
{
CP_DELETE_COPY_AND_MOVE_CTOR(Window);
@@ -48,5 +48,6 @@ namespace Copium
static void MouseMoveCallback(GLFWwindow* window, double xpos, double ypos);
static void WindowFocusCallback(GLFWwindow* window, int focused);
static void MouseScrollCallback(GLFWwindow* window, double xoffset, double yoffset);
static void DropCallback(GLFWwindow* window, int path_count, const char* paths[]);
};
}
+7 -7
View File
@@ -6,7 +6,7 @@
#include "copium/ecs/ComponentPoolBase.h"
#include "copium/ecs/Config.h"
#include "copium/ecs/EntitySet.h"
#include "copium/util/Common.h"
#include "copium/util/Trace.h"
namespace Copium
{
@@ -68,8 +68,8 @@ namespace Copium
return;
CP_ASSERT(queueOperationOrder.size() == addQueue.size() + removeQueue.size(),
"queueOperationOrder size=%zu doesn't match the sum of the addQueue size=%zu and removeQueue size=%zu, "
"which is %zu",
"queueOperationOrder size={} doesn't match the sum of the addQueue size={} and removeQueue size={}, "
"which is {}",
queueOperationOrder.size(),
addQueue.size(),
removeQueue.size(),
@@ -152,14 +152,14 @@ namespace Copium
void CommitAddComponent(int queueIndex)
{
CP_ASSERT(
queueIndex < addQueue.size(), "queueIndex=%d is greater than the addQueueSize=%d", queueIndex, addQueue.size());
queueIndex < addQueue.size(), "queueIndex={} is greater than the addQueueSize={}", queueIndex, addQueue.size());
const auto& [entity, component] = addQueue[queueIndex];
// TODO: Debugging errors caused by this assert might be a bit difficult, since there wont be any stacktrace for
// where the component was added. Might want to validate this in AddComponent somehow (like looping through
// the queued changes and work out if the component already exists)
CP_ASSERT(Find(entity) == Size(),
"Component already exists in entity (entity=%u, Component=%s)",
"Component already exists in entity (entity={}, Component={})",
entity,
typeid(Component).name());
@@ -172,7 +172,7 @@ namespace Copium
void CommitRemoveComponent(int queueIndex)
{
CP_ASSERT(queueIndex < removeQueue.size(),
"queueIndex=%d is greater than the removeQueueSize=%d",
"queueIndex={} is greater than the removeQueueSize={}",
queueIndex,
removeQueue.size());
@@ -183,7 +183,7 @@ namespace Copium
// TODO: Debugging warnings caused by this might be a bit difficult, since there wont be any stacktrace for
// where the component was added. Might want to validate this in AddComponent somehow (like looping
// through the queued changes and work out if the component already exists)
CP_WARN("Entity did not contain component (entity=%u, Component=%s)", entity, typeid(Component).name());
CP_WARN("Entity did not contain component (entity={}, Component={})", entity, typeid(Component).name());
return;
}
+3 -3
View File
@@ -1,6 +1,6 @@
#include "copium/ecs/ECSManager.h"
#include "copium/util/Common.h"
#include "copium/util/Trace.h"
namespace Copium
{
@@ -30,7 +30,7 @@ namespace Copium
void ECSManager::UpdateSystems(const Uuid& systemPoolId)
{
auto it = systemPools.find(systemPoolId);
CP_ASSERT(it != systemPools.end(), "SystemPool doesn't exist with Uuid=%s", systemPoolId.ToString().c_str());
CP_ASSERT(it != systemPools.end(), "SystemPool doesn't exist with Uuid={}", systemPoolId);
it->second->CommitSignals();
CommitEntityUpdates();
it->second->CommitUpdates();
@@ -60,7 +60,7 @@ namespace Copium
void ECSManager::DestroyEntity(EntityId entity)
{
auto it = entities.find(entity);
CP_ASSERT(it != entities.end(), "Entity does not exist in ECSManager (entity=%u)", entity);
CP_ASSERT(it != entities.end(), "Entity does not exist in ECSManager (entity={})", entity);
if (entity == currentEntityId - 1)
{
currentEntityId--;
+8 -6
View File
@@ -2,6 +2,7 @@
#include <functional>
#include <map>
#include <memory>
#include <set>
#include <typeindex>
#include <unordered_set>
@@ -12,6 +13,7 @@
#include "copium/ecs/SystemPool.h"
#include "copium/util/Common.h"
#include "copium/util/GenericType.h"
#include "copium/util/Trace.h"
#include "copium/util/Uuid.h"
namespace Copium
@@ -50,7 +52,7 @@ namespace Copium
void RemoveSystem(const Uuid& systemPoolId)
{
auto it = systemPools.find(systemPoolId);
CP_ASSERT(it != systemPools.end(), "SystemPool doesn't exist with Uuid=%s", systemPoolId.ToString().c_str());
CP_ASSERT(it != systemPools.end(), "SystemPool doesn't exist with Uuid={}", systemPoolId);
it->second->RemoveSystem(typeid(SystemClass));
@@ -146,7 +148,7 @@ namespace Copium
auto pool = GetComponentPoolAssure<Component>();
Component* component = pool->FindComponent(entity);
CP_ASSERT(
component, "Entity did not contain component (entity=%u, Component=%s)", entity, typeid(Component).name());
component, "Entity did not contain component (entity={}, Component={})", entity, typeid(Component).name());
return *component;
}
@@ -258,7 +260,7 @@ namespace Copium
void AddGlobalData(const Args&... args)
{
auto it = globalDatas.find(typeid(T));
CP_ASSERT(!HasGlobalData<T>(), "Global with typeid=%s already exists. Do nothing", typeid(T).name());
CP_ASSERT(!HasGlobalData<T>(), "Global with typeid={} already exists. Do nothing", typeid(T).name());
globalDatas.emplace(typeid(T), GenericType::Create<T>(args...));
}
@@ -267,7 +269,7 @@ namespace Copium
T& GetGlobalData()
{
auto it = globalDatas.find(typeid(T));
CP_ASSERT(it != globalDatas.end(), "Global with typeid=%s doesn't exist");
CP_ASSERT(it != globalDatas.end(), "Global with typeid={} doesn't exist");
return it->second.Get<T>();
}
@@ -282,7 +284,7 @@ namespace Copium
void RemoveGlobalData()
{
auto it = globalDatas.find(typeid(T));
CP_ASSERT("Global with typeid=%s doesn't exist. Do nothing", typeid(T).name());
CP_ASSERT("Global with typeid={} doesn't exist. Do nothing", typeid(T).name());
globalDatas.erase(it);
}
@@ -299,7 +301,7 @@ namespace Copium
{
auto it = componentPools.find(GetComponentId<Component>());
CP_ASSERT(it != componentPools.end(),
"Component has not been added to an entity (Component=%s)",
"Component has not been added to an entity (Component={})",
typeid(Component).name());
return static_cast<ComponentPool<std::remove_const_t<Component>>*>(it->second);
}
+11 -11
View File
@@ -41,8 +41,8 @@ namespace Copium
return;
CP_ASSERT(queueOperationOrder.size() == addQueue.size() + removeQueue.size(),
"queueOperationOrder size=%zu doesn't match the sum of the addQueue size=%zu and removeQueue size=%zu, "
"which is %zu",
"queueOperationOrder size={} doesn't match the sum of the addQueue size={} and removeQueue size={}, "
"which is {}",
queueOperationOrder.size(),
addQueue.size(),
removeQueue.size(),
@@ -116,9 +116,9 @@ namespace Copium
void SystemPool::MoveSystemAfter(const std::type_index& systemId, const std::type_index& afterSystemId)
{
auto it1 = systems.find(systemId);
CP_ASSERT(it1 != systems.end(), "System with typeid=%s does not exist in SystemPool", systemId.name());
CP_ASSERT(it1 != systems.end(), "System with typeid={} does not exist in SystemPool", systemId.name());
auto it2 = systems.find(afterSystemId);
CP_ASSERT(it2 != systems.end(), "System with typeid=%s does not exist in SystemPool", afterSystemId.name());
CP_ASSERT(it2 != systems.end(), "System with typeid={} does not exist in SystemPool", afterSystemId.name());
auto itSystemId = std::find(systemOrder.rbegin(), systemOrder.rend(), it1->second);
auto itAfterSystemId = std::find(systemOrder.rbegin(), systemOrder.rend(), it2->second);
@@ -128,9 +128,9 @@ namespace Copium
void SystemPool::MoveSystemBefore(const std::type_index& systemId, const std::type_index& beforeSystemId)
{
auto it1 = systems.find(systemId);
CP_ASSERT(it1 != systems.end(), "System with typeid=%s does not exist in SystemPool", systemId.name());
CP_ASSERT(it1 != systems.end(), "System with typeid={} does not exist in SystemPool", systemId.name());
auto it2 = systems.find(beforeSystemId);
CP_ASSERT(it2 != systems.end(), "System with typeid=%s does not exist in SystemPool", beforeSystemId.name());
CP_ASSERT(it2 != systems.end(), "System with typeid={} does not exist in SystemPool", beforeSystemId.name());
auto itSystemId = std::find(systemOrder.rbegin(), systemOrder.rend(), it1->second);
auto itBeforeSystemId = std::find(systemOrder.rbegin(), systemOrder.rend(), it2->second);
@@ -141,10 +141,10 @@ namespace Copium
void SystemPool::CommitAddSystem(int queueIndex)
{
CP_ASSERT(
queueIndex < addQueue.size(), "queueIndex=%d is greater than the addQueueSize=%d", queueIndex, addQueue.size());
queueIndex < addQueue.size(), "queueIndex={} is greater than the addQueueSize={}", queueIndex, addQueue.size());
auto& [systemId, system, ordering] = addQueue[queueIndex];
CP_ASSERT(systems.find(systemId) == systems.end(), "System with typeid=%s already exists in SystemPool");
CP_ASSERT(systems.find(systemId) == systems.end(), "System with typeid={} already exists in SystemPool");
systems.emplace(systemId, system);
systemOrder.emplace_back(system);
@@ -154,16 +154,16 @@ namespace Copium
void SystemPool::CommitRemoveSystem(int queueIndex)
{
CP_ASSERT(queueIndex < removeQueue.size(),
"queueIndex=%d is greater than the removeQueueSize=%d",
"queueIndex={} is greater than the removeQueueSize={}",
queueIndex,
removeQueue.size());
const auto& systemId = removeQueue[queueIndex];
auto it = systems.find(systemId);
CP_ASSERT(it != systems.end(), "System with typeid=%s does not exist in SystemPool", systemId.name());
CP_ASSERT(it != systems.end(), "System with typeid={} does not exist in SystemPool", systemId.name());
auto itOrder = std::find(systemOrder.begin(), systemOrder.end(), it->second);
CP_ASSERT(itOrder != systemOrder.end(), "System with typeid=%s does not exist in systemOrder", systemId.name());
CP_ASSERT(itOrder != systemOrder.end(), "System with typeid={} does not exist in systemOrder", systemId.name());
delete it->second;
systems.erase(it);
@@ -0,0 +1,15 @@
#include "copium/event/DropEvent.h"
namespace Copium
{
DropEvent::DropEvent(const std::vector<std::string>& filePaths)
: Event{EventType::Drop},
filePaths{filePaths}
{
}
const std::vector<std::string>& DropEvent::GetFilePaths() const
{
return filePaths;
}
}
+17
View File
@@ -0,0 +1,17 @@
#pragma once
#include "copium/event/Event.h"
namespace Copium
{
class DropEvent : public Event
{
private:
std::vector<std::string> filePaths;
public:
DropEvent(const std::vector<std::string>& filePaths);
const std::vector<std::string>& GetFilePaths() const;
};
}
@@ -1,6 +1,6 @@
#include "copium/event/EventDispatcher.h"
#include "copium/util/Common.h"
#include "copium/util/Trace.h"
namespace Copium
{
@@ -35,7 +35,7 @@ namespace Copium
focusedEventHandler = eventHandler;
return;
default:
CP_ABORT("Unreachable switch case: %s", ToString(result).c_str());
CP_ABORT("Unreachable switch case: {}", result);
}
}
}
+4 -3
View File
@@ -2,6 +2,7 @@
#include "copium/util/Enum.h"
#define CP_EVENT_RESULT_ENUMS Continue, Handled, Focus
CP_ENUM_CREATOR(Copium, EventResult, CP_EVENT_RESULT_ENUMS);
namespace Copium
{
CP_ENUM_CREATOR(EventResult, Continue, Handled, Focus);
}
+14 -4
View File
@@ -2,7 +2,17 @@
#include "copium/util/Enum.h"
#define CP_EVENT_TYPE_ENUMS \
MouseMove, MousePress, MouseRelease, MouseScroll, KeyPress, KeyRelease, WindowResize, WindowFocus, ViewportResize
CP_ENUM_CREATOR(Copium, EventType, CP_EVENT_TYPE_ENUMS);
namespace Copium
{
CP_ENUM_CREATOR(EventType,
MouseMove,
MousePress,
MouseRelease,
MouseScroll,
KeyPress,
KeyRelease,
WindowResize,
WindowFocus,
ViewportResize,
Drop);
}
+11 -11
View File
@@ -4,7 +4,7 @@
#include "copium/core/Vulkan.h"
#include "copium/event/InputCode.h"
#include "copium/util/Common.h"
#include "copium/util/Trace.h"
namespace Copium
{
@@ -17,49 +17,49 @@ namespace Copium
bool Input::IsKeyPressed(int keyCode)
{
CP_ASSERT(keyCode >= 0 && keyCode < MAX_NUM_KEYS, "KeyCode is out of range %d", keyCode);
CP_ASSERT(keyCode >= 0 && keyCode < MAX_NUM_KEYS, "KeyCode is out of range {}", keyCode);
return keyEventList[keyCode] && keyDownList[keyCode];
}
bool Input::IsKeyReleased(int keyCode)
{
CP_ASSERT(keyCode >= 0 && keyCode < MAX_NUM_KEYS, "KeyCode is out of range %d", keyCode);
CP_ASSERT(keyCode >= 0 && keyCode < MAX_NUM_KEYS, "KeyCode is out of range {}", keyCode);
return keyEventList[keyCode] && !keyDownList[keyCode];
}
bool Input::IsKeyDown(int keyCode)
{
CP_ASSERT(keyCode >= 0 && keyCode < MAX_NUM_KEYS, "KeyCode is out of range %d", keyCode);
CP_ASSERT(keyCode >= 0 && keyCode < MAX_NUM_KEYS, "KeyCode is out of range {}", keyCode);
return keyDownList[keyCode];
}
bool Input::IsKeyUp(int keyCode)
{
CP_ASSERT(keyCode >= 0 && keyCode < MAX_NUM_KEYS, "KeyCode is out of range %d", keyCode);
CP_ASSERT(keyCode >= 0 && keyCode < MAX_NUM_KEYS, "KeyCode is out of range {}", keyCode);
return !keyDownList[keyCode];
}
bool Input::IsMousePressed(int button)
{
CP_ASSERT(button >= 0 && button < MAX_NUM_MOUSE_BUTTONS, "button is out of range %d", button);
CP_ASSERT(button >= 0 && button < MAX_NUM_MOUSE_BUTTONS, "button is out of range {}", button);
return mouseEventList[button] && mouseDownList[button];
}
bool Input::IsMouseReleased(int button)
{
CP_ASSERT(button >= 0 && button < MAX_NUM_MOUSE_BUTTONS, "button is out of range %d", button);
CP_ASSERT(button >= 0 && button < MAX_NUM_MOUSE_BUTTONS, "button is out of range {}", button);
return mouseEventList[button] && !mouseDownList[button];
}
bool Input::IsMouseDown(int button)
{
CP_ASSERT(button >= 0 && button < MAX_NUM_MOUSE_BUTTONS, "button is out of range %d", button);
CP_ASSERT(button >= 0 && button < MAX_NUM_MOUSE_BUTTONS, "button is out of range {}", button);
return mouseDownList[button];
}
bool Input::IsMouseUp(int button)
{
CP_ASSERT(button >= 0 && button < MAX_NUM_MOUSE_BUTTONS, "button is out of range %d", button);
CP_ASSERT(button >= 0 && button < MAX_NUM_MOUSE_BUTTONS, "button is out of range {}", button);
return !mouseDownList[button];
}
@@ -81,14 +81,14 @@ namespace Copium
void Input::OnKey(int keyCode, bool pressed)
{
CP_ASSERT(keyCode >= 0 && keyCode < MAX_NUM_KEYS, "KeyCode is out of range %d", keyCode);
CP_ASSERT(keyCode >= 0 && keyCode < MAX_NUM_KEYS, "KeyCode is out of range {}", keyCode);
keyDownList[keyCode] = pressed;
keyEventList[keyCode] = true;
}
void Input::OnMouse(int button, bool pressed)
{
CP_ASSERT(button >= 0 && button < MAX_NUM_MOUSE_BUTTONS, "button is out of range %d", button);
CP_ASSERT(button >= 0 && button < MAX_NUM_MOUSE_BUTTONS, "button is out of range {}", button);
mouseDownList[button] = pressed;
mouseEventList[button] = true;
}
@@ -1,5 +1,6 @@
#include "copium/pipeline/DescriptorPool.h"
#include "copium/core/SwapChain.h"
#include "copium/core/Vulkan.h"
namespace Copium
@@ -43,8 +44,8 @@ namespace Copium
std::vector<VkDescriptorSet> DescriptorPool::AllocateDescriptorSets(VkDescriptorSetLayout descriptorSetLayout)
{
std::vector<VkDescriptorSet> descriptorSets{SwapChain::MAX_FRAMES_IN_FLIGHT};
std::vector<VkDescriptorSetLayout> layouts{SwapChain::MAX_FRAMES_IN_FLIGHT, descriptorSetLayout};
std::vector<VkDescriptorSet> descriptorSets{(size_t)SwapChain::MAX_FRAMES_IN_FLIGHT};
std::vector<VkDescriptorSetLayout> layouts{(size_t)SwapChain::MAX_FRAMES_IN_FLIGHT, descriptorSetLayout};
VkDescriptorSetAllocateInfo allocateInfo{};
allocateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocateInfo.descriptorPool = descriptorPool;
@@ -110,7 +110,7 @@ namespace Copium
UniformBuffer& DescriptorSet::GetUniformBuffer(const std::string& uniformBuffer)
{
auto it = uniformBuffers.find(uniformBuffer);
CP_ASSERT(it != uniformBuffers.end(), "UniformBuffer not found = %s", uniformBuffer.c_str());
CP_ASSERT(it != uniformBuffers.end(), "UniformBuffer not found = {}", uniformBuffer);
return *it->second;
}
@@ -2,6 +2,7 @@
#include <glm/glm.hpp>
#include <map>
#include <memory>
#include <set>
#include <vector>
#include <vulkan/vulkan.hpp>
@@ -1,6 +1,6 @@
#include "copium/pipeline/PipelineCreator.h"
#include "copium/util/Common.h"
#include "copium/util/Trace.h"
namespace Copium
{
+7 -7
View File
@@ -27,7 +27,7 @@ namespace Copium
fragShaderModule = InitializeShaderModule(FileSystem::ReadFile(fragmentInput));
break;
default:
CP_ASSERT(false, "Unreachable switch case: %s", ToString(type).c_str());
CP_ASSERT(false, "Unreachable switch case: {}", type);
}
shaderStages.resize(2);
@@ -85,7 +85,7 @@ namespace Copium
{
if (FileSystem::DateModified(filename) < FileSystem::DateModified(spvFilename))
{
CP_DEBUG("Loading cached shader file: %s", filename.c_str());
CP_DEBUG("Loading cached shader file: {}", filename);
std::vector<uint32_t> data = FileSystem::ReadFile32(spvFilename);
return InitializeShaderModule(data.data(), data.size() * sizeof(uint32_t));
}
@@ -95,7 +95,7 @@ namespace Copium
{
CP_WARN("Cached shader file is invalid, recreating it");
}
CP_DEBUG("Compiling shader file: %s", filename.c_str());
CP_DEBUG("Compiling shader file: {}", filename);
shaderc::Compiler compiler;
shaderc::CompileOptions options;
@@ -105,9 +105,9 @@ namespace Copium
shaderc::SpvCompilationResult result =
compiler.CompileGlslToSpv(glslCode.data(), glslCode.size(), type, filename.c_str(), options);
CP_ASSERT(result.GetCompilationStatus() == shaderc_compilation_status_success,
"Failed to compile shader: %s\n%s",
filename.c_str(),
result.GetErrorMessage().c_str());
"Failed to compile shader: {}\n{}",
filename,
result.GetErrorMessage());
std::vector<uint32_t> data{result.cbegin(), result.cend()};
FileSystem::WriteFile(spvFilename, (const char*)data.data(), data.size() * sizeof(uint32_t));
@@ -123,7 +123,7 @@ namespace Copium
shaderc::SpvCompilationResult result = compiler.CompileGlslToSpv(code.data(), type, "inline_shader_code", options);
CP_ASSERT(result.GetCompilationStatus() == shaderc_compilation_status_success,
"Failed to compile inline shader code: %s",
"Failed to compile inline shader code: {}",
result.GetErrorMessage());
std::vector<uint32_t> data{result.cbegin(), result.cend()};
+2 -3
View File
@@ -6,11 +6,10 @@
#include "copium/util/Common.h"
#include "copium/util/Enum.h"
#define CP_SHADER_READ_TYPE_ENUMS GlslFile, GlslCode, SpvFile, SpvCode
CP_ENUM_CREATOR(Copium, ShaderReadType, CP_SHADER_READ_TYPE_ENUMS);
namespace Copium
{
CP_ENUM_CREATOR(ShaderReadType, GlslFile, GlslCode, SpvFile, SpvCode);
class Shader final
{
CP_DELETE_COPY_AND_MOVE_CTOR(Shader);
@@ -1,6 +1,6 @@
#include "copium/pipeline/ShaderBinding.h"
#include "copium/util/Common.h"
#include "copium/util/Trace.h"
namespace Copium
{
@@ -21,7 +21,7 @@ namespace Copium
return offset;
offset += GetUniformTypeOffset(uniformElem.first);
}
CP_ABORT("Uniform not found=%s", uniform.c_str());
CP_ABORT("Uniform not found={}", uniform);
}
uint32_t ShaderBinding::GetUniformSize(const std::string& uniform) const
@@ -31,7 +31,7 @@ namespace Copium
if (uniformElem.second == uniform)
return GetUniformTypeSize(uniformElem.first);
}
CP_ABORT("Uniform not found=%s", uniform.c_str());
CP_ABORT("Uniform not found={}", uniform);
}
UniformType ShaderBinding::GetUniformType(const std::string& uniform) const
@@ -41,7 +41,7 @@ namespace Copium
if (uniformElem.second == uniform)
return uniformElem.first;
}
CP_ABORT("Uniform not found=%s", uniform.c_str());
CP_ABORT("Uniform not found={}", uniform);
}
uint32_t ShaderBinding::GetUniformBufferSize() const
@@ -79,7 +79,7 @@ namespace Copium
case UniformType::Float:
return 4; // float
default:
CP_ABORT("Unhandled switch case: %s", ToString(type).c_str());
CP_ABORT("Unhandled switch case: {}", type);
}
}
@@ -102,7 +102,7 @@ namespace Copium
case UniformType::Float:
return 16; // alignas(16) glm::vec2
default:
CP_ABORT("Unhandled switch case", ToString(type).c_str());
CP_ABORT("Unhandled switch case", type);
}
}
}
@@ -6,16 +6,12 @@
#include "copium/util/Enum.h"
#define CP_BINDING_TYPE_ENUMS Sampler2D, UniformBuffer
#define CP_SHADER_TYPE_ENUMS Vertex, Fragment
#define CP_UNIFORM_TYPE_ENUMS Mat3, Mat4, Vec2, Vec3, Vec4, Float, Int
CP_ENUM_CREATOR(Copium, BindingType, CP_BINDING_TYPE_ENUMS);
CP_ENUM_CREATOR(Copium, ShaderType, CP_SHADER_TYPE_ENUMS);
CP_ENUM_CREATOR(Copium, UniformType, CP_UNIFORM_TYPE_ENUMS);
namespace Copium
{
CP_ENUM_CREATOR(BindingType, Sampler2D, UniformBuffer);
CP_ENUM_CREATOR(ShaderType, Vertex, Fragment);
CP_ENUM_CREATOR(UniformType, Mat3, Mat4, Vec2, Vec3, Vec4, Float, Int);
struct ShaderBinding
{
std::string name;
@@ -3,6 +3,7 @@
#include <string_view>
#include "copium/util/FileSystem.h"
#include "copium/util/Trace.h"
namespace Copium
{
@@ -143,7 +144,7 @@ namespace Copium
else if (type == "int")
binding.uniforms.emplace_back(UniformType::Int, std::string(name));
else
CP_ABORT("Unsupported uniform type=%s", std::string(type).c_str());
CP_ABORT("Unsupported uniform type={}", type);
ParseWhitespace(str, index);
index++; // ";"
ParseWhitespace(str, index);
@@ -151,4 +152,4 @@ namespace Copium
if (index < str.size())
index++; // go past "}"
}
}
}
@@ -1,6 +1,6 @@
#include "copium/pipeline/VertexDescriptor.h"
#include "copium/util/Common.h"
#include "copium/util/Trace.h"
namespace Copium
{
+2 -2
View File
@@ -15,7 +15,7 @@ namespace Copium
CP_ASSERT(ft, "Failed to initialize FreeType"); // TODO: Move to Vulkan singleton class?
std::string fontPath = metaFile.GetMetaClass("Font").GetValue("filepath");
msdfgen::FontHandle* font = msdfgen::loadFont(ft, fontPath.c_str());
CP_ASSERT(font, "Failed to initialize font: %s", fontPath.c_str());
CP_ASSERT(font, "Failed to initialize font: {}", fontPath);
std::vector<msdf_atlas::GlyphGeometry> glyphs;
msdf_atlas::FontGeometry fontGeometry(&glyphs);
@@ -101,7 +101,7 @@ namespace Copium
const Glyph& Font::GetGlyph(char c) const
{
CP_ASSERT(glyphs.find(c) != glyphs.end(), "Glyph not found: %c", c);
CP_ASSERT(glyphs.find(c) != glyphs.end(), "Glyph not found: {}", c);
return glyphs.find(c)->second;
}
+1 -1
View File
@@ -31,4 +31,4 @@ namespace Copium
VkImageTiling tiling,
VkFormatFeatureFlags features);
};
}
}
@@ -1,6 +1,6 @@
#include "copium/sampler/SamplerCreator.h"
#include "copium/util/Common.h"
#include "copium/util/Trace.h"
namespace Copium
{
@@ -34,7 +34,7 @@ namespace Copium
else if (str == "linear")
return VK_FILTER_LINEAR;
else
CP_ABORT("Invalid texture filtering: %s", str.c_str());
CP_ABORT("Invalid texture filtering: {}", str);
}
VkSamplerAddressMode SamplerCreator::GetAddressModeFromString(const std::string& str) const
@@ -44,6 +44,6 @@ namespace Copium
else if (str == "repeat")
return VK_SAMPLER_ADDRESS_MODE_REPEAT;
else
CP_ABORT("Invalid texture address mode: %s", str.c_str());
CP_ABORT("Invalid texture address mode: {}", str);
}
}
@@ -12,7 +12,7 @@ namespace Copium
: Sampler{metaFile.GetMetaClass("Texture2D")}
{
const std::string& filepath = metaFile.GetMetaClass("Texture2D").GetValue("filepath");
CP_DEBUG("Loading texture file: %s", filepath.c_str());
CP_DEBUG("Loading texture file: {}", filepath);
InitializeTextureImageFromFile(filepath);
}
@@ -25,7 +25,7 @@ namespace Copium
height{height}
{
CP_ASSERT(rgbaData.size() == width * height * 4,
"rgbaData has invalid size, should be equal to width * height * 4 (%d) actually is %d",
"rgbaData has invalid size, should be equal to width * height * 4 ({}) actually is {}",
width * height * 4,
rgbaData.size());
InitializeTextureImageFromData(rgbaData.data(), width, height);
-93
View File
@@ -1,101 +1,8 @@
#pragma once
#include <iomanip>
#include <iostream>
#include <memory>
#include "copium/util/RuntimeException.h"
#include "copium/util/VulkanException.h"
#define CP_TERM_RED "\x1B[31m"
#define CP_TERM_GREEN "\x1B[32m"
#define CP_TERM_YELLOW "\x1B[33m"
#define CP_TERM_GRAY "\x1B[90m"
#define CP_TERM_CLEAR "\033[0m"
#define CP_DEBUG(...) \
std::cout << CP_TERM_GRAY << "[DBG] " << __func__ << " : " << Copium::String::Format(__VA_ARGS__) << CP_TERM_CLEAR \
<< std::endl
#define CP_INFO(...) std::cout << "[INF] " << __func__ << " : " << Copium::String::Format(__VA_ARGS__) << std::endl
#define CP_WARN(...) \
std::cout << CP_TERM_YELLOW << "[WRN] " << __func__ << " : " << Copium::String::Format(__VA_ARGS__) << CP_TERM_CLEAR \
<< std::endl
#define CP_ERR(...) \
std::cout << CP_TERM_RED << "[ERR] " << __func__ << " : " << Copium::String::Format(__VA_ARGS__) << CP_TERM_CLEAR \
<< std::endl
// Continue traces, will not print the [XXX] tag before the log
#define CP_DEBUG_CONT(...) \
std::cout << CP_TERM_GRAY << " " << std::setfill(' ') << std::setw(sizeof(__func__)) << " " \
<< Copium::String::Format(__VA_ARGS__) << CP_TERM_CLEAR << std::endl
#define CP_INFO_CONT(...) \
std::cout << " " << std::setfill(' ') << std::setw(sizeof(__func__)) << " " \
<< Copium::String::Format(__VA_ARGS__) << std::endl
#define CP_WARN_CONT(...) \
std::cout << CP_TERM_YELLOW << " " << std::setfill(' ') << std::setw(sizeof(__func__)) << " " \
<< Copium::String::Format(__VA_ARGS__) << CP_TERM_CLEAR << std::endl
#define CP_ERR_CONT(...) \
std::cout << CP_TERM_RED << " " << std::setfill(' ') << std::setw(sizeof(__func__)) << " " \
<< Copium::String::Format(__VA_ARGS__) << CP_TERM_CLEAR << std::endl
#define CP_ABORT(...) \
do \
{ \
CP_ERR("Aborted at %s:%d", __FILE__, __LINE__); \
CP_ERR_CONT(__VA_ARGS__); \
throw Copium::RuntimeException(Copium::String::Format(__VA_ARGS__)); \
} while (false)
#define CP_ASSERT(Function, ...) \
do \
{ \
if (!(Function)) \
{ \
CP_ERR("Assertion failed at %s:%d", __FILE__, __LINE__); \
CP_ERR_CONT("%s : %s", #Function, Copium::String::Format(__VA_ARGS__).c_str()); \
throw Copium::RuntimeException(Copium::String::Format(__VA_ARGS__)); \
} \
} while (false)
#define CP_VK_ASSERT(Function, ...) \
do \
{ \
if (Function != VK_SUCCESS) \
{ \
CP_ERR("Assertion failed at %s:%d", __FILE__, __LINE__); \
CP_ERR_CONT("%s : %s", #Function, Copium::String::Format(__VA_ARGS__).c_str()); \
throw Copium::VulkanException(Copium::String::Format(__VA_ARGS__)); \
} \
} while (false)
#define CP_UNIMPLEMENTED() CP_WARN("%s is unimplemented", __FUNCTION__)
#define CP_ABORT_UNIMPLEMENTED() CP_ABORT("%s is unimplemented", __FUNCTION__)
#define CP_STATIC_CLASS(ClassName) ClassName() = delete
#define CP_DELETE_COPY_AND_MOVE_CTOR(ClassName) \
ClassName(ClassName&&) = delete; \
ClassName(const ClassName&) = delete; \
ClassName& operator=(ClassName&&) = delete; \
ClassName& operator=(const ClassName&) = delete
namespace Copium
{
class String
{
CP_STATIC_CLASS(String);
public:
static std::string Format(const std::string& format)
{
return format;
}
template <typename... Args>
static std::string Format(const std::string& format, Args... args)
{
int size = std::snprintf(nullptr, 0, format.c_str(), args...) + 1;
CP_ASSERT(size > 0, "Error during formatting");
std::unique_ptr<char[]> buf(new char[size]);
std::snprintf(buf.get(), size, format.c_str(), args...);
return std::string(buf.get(), buf.get() + size - 1);
}
};
}
+14 -17
View File
@@ -6,23 +6,20 @@
#define CP_STRINGIFY(x) #x
#define CP_TO_STRING(x) CP_STRINGIFY(x)
#define CP_ENUM_CREATOR(NameSpace, EnumName, EnumList) \
namespace NameSpace \
{ \
enum class EnumName \
{ \
EnumList \
}; \
static const std::string& ToString(EnumName enumName) \
{ \
static std::vector<std::string> enumNames = Copium::EnumPrinter::GetEnumNames(CP_TO_STRING(#EnumList)); \
return enumNames[(int)enumName]; \
} \
\
static std::ostream& operator<<(std::ostream& ostream, EnumName enumName) \
{ \
return ostream << ToString(enumName); \
} \
#define CP_ENUM_CREATOR(EnumName, ...) \
enum class EnumName \
{ \
__VA_ARGS__ \
}; \
static const std::string& ToString(EnumName enumName) \
{ \
static std::vector<std::string> enumNames = Copium::EnumPrinter::GetEnumNames(CP_TO_STRING(#__VA_ARGS__)); \
return enumNames[(int)enumName]; \
} \
\
static std::ostream& operator<<(std::ostream& ostream, EnumName enumName) \
{ \
return ostream << ToString(enumName); \
}
namespace Copium
+8 -6
View File
@@ -6,12 +6,14 @@
#include <filesystem>
#include <fstream>
#include "copium/util/Trace.h"
namespace Copium
{
std::vector<char> FileSystem::ReadFile(const std::string& filename)
{
std::ifstream file(filename, std::ios::ate | std::ios::binary);
CP_ASSERT(file.is_open(), "Failed to open file: %s", filename.c_str());
CP_ASSERT(file.is_open(), "Failed to open file: {}", filename);
size_t fileSize = (size_t)file.tellg();
std::vector<char> buffer(fileSize);
@@ -25,7 +27,7 @@ namespace Copium
std::vector<uint32_t> FileSystem::ReadFile32(const std::string& filename)
{
std::ifstream file(filename, std::ios::ate | std::ios::binary);
CP_ASSERT(file.is_open(), "Failed to open file: %s", filename.c_str());
CP_ASSERT(file.is_open(), "Failed to open file: {}", filename);
size_t fileSize = (size_t)file.tellg();
CP_ASSERT(fileSize % 4 == 0, "byte size is not divisible by 4");
@@ -40,7 +42,7 @@ namespace Copium
std::string FileSystem::ReadFileStr(const std::string& filename)
{
std::ifstream file(filename, std::ios::ate | std::ios::binary);
CP_ASSERT(file.is_open(), "Failed to open file: %s", filename.c_str());
CP_ASSERT(file.is_open(), "Failed to open file: {}", filename);
size_t fileSize = (size_t)file.tellg();
std::string buffer;
@@ -57,7 +59,7 @@ namespace Copium
std::filesystem::path path{filename};
std::filesystem::create_directories(path.parent_path());
std::ofstream file(filename, std::ios::binary);
CP_ASSERT(file.is_open(), "Failed to open file: %s", filename.c_str());
CP_ASSERT(file.is_open(), "Failed to open file: {}", filename);
file.write(data.c_str(), data.size());
}
@@ -67,7 +69,7 @@ namespace Copium
std::filesystem::path path{filename};
std::filesystem::create_directories(path.parent_path());
std::ofstream file(filename, std::ios::binary);
CP_ASSERT(file.is_open(), "Failed to open file: %s", filename.c_str());
CP_ASSERT(file.is_open(), "Failed to open file: {}", filename);
file.write(data, size);
}
@@ -81,7 +83,7 @@ namespace Copium
int64_t FileSystem::DateModified(const std::string& filename)
{
struct stat result;
CP_ASSERT(stat(filename.c_str(), &result) == 0, "Cannot stat file %s", filename.c_str());
CP_ASSERT(stat(filename.c_str(), &result) == 0, "Cannot stat file {}", filename);
return (int64_t)result.st_mtime;
}
}
@@ -1,6 +1,7 @@
#pragma once
#include <cstdint>
#include <string>
#include <vector>
#include "copium/util/Common.h"
+9 -9
View File
@@ -2,7 +2,7 @@
#include <fstream>
#include "copium/util/Common.h"
#include "copium/util/Trace.h"
#include "copium/util/StringUtil.h"
namespace Copium
@@ -23,7 +23,7 @@ namespace Copium
const std::string& MetaFileClass::GetValue(const std::string& key) const
{
auto it = values.find(key);
CP_ASSERT(it != values.end(), "Value does not exist: %s", key.c_str());
CP_ASSERT(it != values.end(), "Value does not exist: {}", key);
return it->second;
}
@@ -55,7 +55,7 @@ namespace Copium
{
std::ifstream stream(filepath);
CP_ASSERT(stream.is_open(), "Could not find meta file: %s", filepath.c_str());
CP_ASSERT(stream.is_open(), "Could not find meta file: {}", filepath);
LoadMetaFile(stream);
}
@@ -77,14 +77,14 @@ namespace Copium
MetaFileClass& MetaFile::GetMetaClass(const std::string& className)
{
auto it = classes.find(className);
CP_ASSERT(it != classes.end(), "class does not exist: %s", className.c_str());
CP_ASSERT(it != classes.end(), "class does not exist: {}", className);
return it->second;
}
const MetaFileClass& MetaFile::GetMetaClass(const std::string& className) const
{
auto it = classes.find(className);
CP_ASSERT(it != classes.end(), "class does not exist: ", className.c_str());
CP_ASSERT(it != classes.end(), "class does not exist: {}", className);
return it->second;
}
@@ -139,7 +139,7 @@ namespace Copium
currentClass = StringUtil::Trim(line);
currentClass = currentClass.substr(1, currentClass.size() - 2);
metaClassIt = classes.find(currentClass);
CP_ASSERT(metaClassIt == classes.end(), "Meta file contains two of the same class: %s", currentClass.c_str());
CP_ASSERT(metaClassIt == classes.end(), "Meta file contains two of the same class: {}", currentClass);
metaClassIt = classes.emplace(currentClass, MetaFileClass{}).first;
continue;
}
@@ -159,11 +159,11 @@ namespace Copium
continue;
}
CP_ASSERT(metaClassIt != classes.end(), "No meta file header specified: ", filepath.c_str());
CP_ASSERT(metaClassIt != classes.end(), "No meta file header specified: {}", filepath);
auto res = metaClassIt->second.values.emplace(key, value);
if (!res.second)
{
CP_WARN("Meta file key is defined twice: %s", std::string(key).c_str());
CP_WARN("Meta file key is defined twice: {}", key);
}
}
}
@@ -173,7 +173,7 @@ namespace Copium
std::vector<MetaFile> metaFiles;
std::ifstream stream{file};
CP_ASSERT(stream, "Failed to read file: %s", file.c_str());
CP_ASSERT(stream, "Failed to read file: {}", file);
MetaFile meta;
while (!stream.eof())
+212
View File
@@ -0,0 +1,212 @@
#pragma once
#include <iomanip>
#include <iostream>
#include <string_view>
#include "copium/util/Common.h"
#include "copium/util/RuntimeException.h"
#include "copium/util/VulkanException.h"
#define CP_DEBUG(...) Copium::Trace::Print(std::cout, Copium::TermColor::Gray, "[DBG]", __func__, __VA_ARGS__)
#define CP_INFO(...) Copium::Trace::Print(std::cout, Copium::TermColor::None, "[INF]", __func__, __VA_ARGS__)
#define CP_WARN(...) Copium::Trace::Print(std::cout, Copium::TermColor::Yellow, "[WRN]", __func__, __VA_ARGS__)
#define CP_ERR(...) Copium::Trace::Print(std::cout, Copium::TermColor::Red, "[ERR]", __func__, __VA_ARGS__)
// Continue traces, will not print the [XXX] tag before the log
#define CP_DEBUG_CONT(...) Copium::Trace::PrintCont(std::cout, Copium::TermColor::Gray, sizeof(__func__), __VA_ARGS__)
#define CP_INFO_CONT(...) Copium::Trace::PrintCont(std::cout, Copium::TermColor::None, sizeof(__func__), __VA_ARGS__)
#define CP_WARN_CONT(...) Copium::Trace::PrintCont(std::cout, Copium::TermColor::Yellow, sizeof(__func__), __VA_ARGS__)
#define CP_ERR_CONT(...) Copium::Trace::PrintCont(std::cout, Copium::TermColor::Red, sizeof(__func__), __VA_ARGS__)
#define CP_ABORT(...) \
do \
{ \
CP_ERR("Aborted at {}:{}", __FILE__, __LINE__); \
std::stringstream ss{}; \
Copium::Trace::Print(ss, __VA_ARGS__); \
CP_ERR_CONT(ss.str()); \
throw Copium::RuntimeException(ss.str()); \
} while (false)
#define CP_ASSERT(Function, ...) \
do \
{ \
if (!(Function)) \
{ \
CP_ERR("Assertion failed at {}:{}", __FILE__, __LINE__); \
std::stringstream ss{}; \
Copium::Trace::Print(ss, __VA_ARGS__); \
CP_ERR_CONT("{} : {}", #Function, ss.str()); \
throw Copium::RuntimeException(ss.str()); \
} \
} while (false)
#define CP_VK_ASSERT(Function, ...) \
do \
{ \
if (Function != VK_SUCCESS) \
{ \
CP_ERR("Assertion failed at {}:{}", __FILE__, __LINE__); \
std::stringstream ss{}; \
Copium::Trace::Print(ss, __VA_ARGS__); \
CP_ERR_CONT("{} : {}", #Function, ss.str()); \
throw Copium::VulkanException(ss.str()); \
} \
} while (false)
#define CP_UNIMPLEMENTED() CP_WARN("{} is unimplemented", __func__)
#define CP_ABORT_UNIMPLEMENTED() CP_ABORT("{} is unimplemented", __func__)
namespace Copium
{
enum class TermColor
{
Red,
Green,
Yellow,
Blue,
Magenta,
Cyan,
Gray,
Clear,
None,
};
class Trace
{
CP_STATIC_CLASS(Trace);
public:
template <typename... Args>
static std::ostream& Print(std::ostream& ostream, const std::string& format, const Args&... args)
{
PrintInternal(ostream, format, args...);
return ostream;
}
template <typename... Args>
static std::ostream& PrintCont(
std::ostream& ostream, TermColor color, int padding, const std::string& format, const Args&... args)
{
ostream << GetColor(color) << " " << std::setfill(' ') << std::setw(padding) << " ";
PrintInternal(ostream, format, args...);
return ostream << GetColor(TermColor::Clear) << std::endl;
}
template <typename... Args>
static std::ostream& Print(std::ostream& ostream,
TermColor color,
const std::string& logLevel,
const char* functionName,
const std::string& format,
const Args&... args)
{
ostream << GetColor(color) << logLevel << " " << functionName << " : ";
PrintInternal(ostream, format, args...);
return ostream << GetColor(TermColor::Clear) << std::endl;
}
private:
static const char* GetColor(TermColor color)
{
switch (color)
{
case TermColor::Red:
return "\x1B[31m";
case TermColor::Green:
return "\x1B[32m";
case TermColor::Yellow:
return "\x1B[33m";
case TermColor::Blue:
return "\x1B[34m";
case TermColor::Magenta:
return "\x1B[35m";
case TermColor::Cyan:
return "\x1B[36m";
case TermColor::Gray:
return "\x1B[90m";
case TermColor::Clear:
return "\033[0m";
case TermColor::None:
return "";
}
return "";
}
static size_t FindFormat(const std::string_view& format)
{
for (int i = 0; i < format.size() - 1; i++)
{
if (format[i] == '{' && format[i + 1] != '{')
{
i++;
}
if (format[i] == '{' && format[i + 1] == '}')
{
return i;
}
}
return std::string::npos;
}
template <typename Arg>
static size_t Print1(std::ostream& ostream, const std::string_view& format, const Arg& arg)
{
auto posFormat = format.find("{}");
auto posOpenEscape = format.find("{{");
auto posCloseEscape = format.find("}}");
if (posFormat < posOpenEscape && posFormat < posCloseEscape)
{
ostream << format.substr(0, posFormat);
ostream << arg;
return posFormat + 2;
}
else if (posOpenEscape < posCloseEscape)
{
ostream << format.substr(0, posOpenEscape) << '{';
return posOpenEscape + 2 + Print1(ostream, format.substr(posOpenEscape + 2), arg);
}
else if (posCloseEscape < posOpenEscape)
{
ostream << format.substr(0, posCloseEscape) << '}';
return posCloseEscape + 2 + Print1(ostream, format.substr(posCloseEscape + 2), arg);
}
ostream << format;
return format.size();
}
static size_t PrintInternal(std::ostream& ostream, const std::string& format)
{
auto posFormat = format.find("{}");
auto posOpenEscape = format.find("{{");
auto posCloseEscape = format.find("}}");
if (posFormat < posOpenEscape && posFormat < posCloseEscape)
{
ostream << format.substr(0, posFormat);
return posFormat + 2;
}
else if (posOpenEscape < posCloseEscape)
{
ostream << format.substr(0, posOpenEscape) << '{';
return posOpenEscape + 2 + PrintInternal(ostream, format.substr(posOpenEscape + 2));
}
else if (posCloseEscape < posOpenEscape)
{
ostream << format.substr(0, posCloseEscape) << '}';
return posCloseEscape + 2 + PrintInternal(ostream, format.substr(posCloseEscape + 2));
}
ostream << format;
return format.size();
}
template <typename Arg1, typename... Args>
static size_t PrintInternal(std::ostream& ostream, const std::string& format, const Arg1& arg1, const Args&... args)
{
size_t newPos = Print1(ostream, format, arg1);
return PrintInternal(ostream, format.substr(newPos), args...);
}
};
}
+4 -4
View File
@@ -1,6 +1,6 @@
#include "copium/util/Uuid.h"
#include "copium/util/Common.h"
#include "copium/util/Trace.h"
namespace Copium
{
@@ -26,7 +26,7 @@ namespace Copium
: msb{0},
lsb{0}
{
CP_ASSERT(uuidString.size() == 36, "Invalid Uuid string size: %s", uuidString.c_str());
CP_ASSERT(uuidString.size() == 36, "Invalid Uuid string size: {}", uuidString);
for (int i = 0; i < 18; i++)
{
if (i == 8 || i == 13) // skip "-"
@@ -91,7 +91,7 @@ namespace Copium
return c - '0';
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
CP_ABORT("Invalid char value: %c (%d)", c, (int)c);
CP_ABORT("Invalid char value: {} ({})", c, (int)c);
}
char Uuid::DecToHex(uint8_t nibble) const
@@ -100,6 +100,6 @@ namespace Copium
return '0' + nibble;
if (nibble >= 10 && nibble <= 15)
return 'a' + nibble - 10;
CP_ABORT("Invalid nibble value: %d", (int)nibble);
CP_ABORT("Invalid nibble value: {}", (int)nibble);
}
}