Merge pull request 'Text rendering' (#90) from text_rendering into master
Reviewed-on: https://git.madvoxel.net/OpenVulkano/OpenVulkano/pulls/90 Reviewed-by: Georg Hagen <georg.hagen@madvoxel.com>
This commit is contained in:
@@ -40,6 +40,11 @@ namespace OpenVulkano
|
||||
}
|
||||
}
|
||||
|
||||
std::string ResourceLoaderAppDirLinux::GetResourcePath(const std::string& resourceName)
|
||||
{
|
||||
return GetAppDir() + resourceName;
|
||||
}
|
||||
|
||||
Array<char> ResourceLoaderAppDirLinux::GetResource(const std::string& resourceName)
|
||||
{
|
||||
return Utils::ReadFile(GetAppDir() + resourceName, true);
|
||||
|
||||
@@ -13,6 +13,7 @@ namespace OpenVulkano
|
||||
class ResourceLoaderAppDirLinux final : public ResourceLoader
|
||||
{
|
||||
public:
|
||||
std::string GetResourcePath(const std::string& resourceName) override;
|
||||
Array<char> GetResource(const std::string& resourceName) override;
|
||||
};
|
||||
}
|
||||
@@ -54,6 +54,30 @@ namespace OpenVulkano
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string GetResourcePath(const std::string& resourceName) override
|
||||
{
|
||||
try
|
||||
{
|
||||
for (auto& loader: m_loaders)
|
||||
{
|
||||
auto res = loader->GetResourcePath(resourceName);
|
||||
if (!res.empty())
|
||||
{
|
||||
return res;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (const std::exception& e)
|
||||
{
|
||||
Logger::FILESYS->error("Error trying to get resource path for '{}'! Error: {}", resourceName, e.what());
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
Logger::FILESYS->error("Unknown error trying to get resource path for '{}'!", resourceName);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
ResourceLoader& ResourceLoader::GetInstance()
|
||||
|
||||
@@ -15,7 +15,9 @@ namespace OpenVulkano
|
||||
public:
|
||||
virtual ~ResourceLoader() = default;
|
||||
|
||||
virtual Array<char> GetResource(const std::string& resourceName) = 0;
|
||||
[[nodiscard]] virtual Array<char> GetResource(const std::string& resourceName) = 0;
|
||||
|
||||
[[nodiscard]] virtual std::string GetResourcePath(const std::string& resourceName) { return ""; }
|
||||
|
||||
static ResourceLoader& GetInstance();
|
||||
|
||||
|
||||
@@ -38,6 +38,11 @@ namespace OpenVulkano
|
||||
}
|
||||
}
|
||||
|
||||
std::string ResourceLoaderAppDirWindows::GetResourcePath(const std::string& resourceName)
|
||||
{
|
||||
return GetAppDir() + resourceName;
|
||||
}
|
||||
|
||||
Array<char> ResourceLoaderAppDirWindows::GetResource(const std::string& resourceName)
|
||||
{
|
||||
return Utils::ReadFile(GetAppDir() + resourceName);
|
||||
|
||||
@@ -13,6 +13,7 @@ namespace OpenVulkano
|
||||
class ResourceLoaderAppDirWindows final : public ResourceLoader
|
||||
{
|
||||
public:
|
||||
std::string GetResourcePath(const std::string& resourceName) override;
|
||||
Array<char> GetResource(const std::string& resourceName) override;
|
||||
};
|
||||
}
|
||||
51
openVulkanoCpp/Image/ImageLoader.cpp
Normal file
51
openVulkanoCpp/Image/ImageLoader.cpp
Normal file
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#include "ImageLoader.hpp"
|
||||
#include "Base/Logger.hpp"
|
||||
#include <memory>
|
||||
|
||||
#define STB_IMAGE_IMPLEMENTATION
|
||||
#include <stb_image.h>
|
||||
|
||||
namespace OpenVulkano::Image
|
||||
{
|
||||
std::unique_ptr<Image> IImageLoader::loadData(const uint8_t* data, int size, int desiredChannels)
|
||||
{
|
||||
Image result;
|
||||
int rows, cols, channels;
|
||||
stbi_set_flip_vertically_on_load(true);
|
||||
uint8_t* pixelData = stbi_load_from_memory(data, static_cast<int>(size), &rows, &cols, &channels, desiredChannels);
|
||||
if (desiredChannels != 0 && channels < desiredChannels)
|
||||
{
|
||||
Logger::INPUT->warn(
|
||||
"Stbi load image channels mismatch. Desired channels = {}, actual amount of channels in image = {}",
|
||||
desiredChannels, channels);
|
||||
}
|
||||
result.data = OpenVulkano::Array<uint8_t>(cols * rows * channels);
|
||||
switch (channels)
|
||||
{
|
||||
case 1:
|
||||
result.dataFormat = OpenVulkano::DataFormat::R8_UNORM;
|
||||
break;
|
||||
case 2:
|
||||
result.dataFormat = OpenVulkano::DataFormat::R8G8_UNORM;
|
||||
break;
|
||||
case 3:
|
||||
result.dataFormat = OpenVulkano::DataFormat::R8G8B8_UNORM;
|
||||
break;
|
||||
case 4:
|
||||
result.dataFormat = OpenVulkano::DataFormat::R8G8B8A8_UNORM;
|
||||
break;
|
||||
}
|
||||
result.resolution.x = cols;
|
||||
result.resolution.y = rows;
|
||||
result.resolution.z = 1;
|
||||
std::memcpy(result.data.Data(), pixelData, result.data.Size());
|
||||
stbi_image_free(pixelData);
|
||||
return std::make_unique<Image>(std::move(result));
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ namespace OpenVulkano::Image
|
||||
public:
|
||||
virtual ~IImageLoader() = default;
|
||||
|
||||
static std::unique_ptr<Image> loadData(const uint8_t* data, int size, int desiredChannels = 0);
|
||||
virtual std::unique_ptr<Image> loadFromFile(const std::string& filePath) = 0;
|
||||
virtual std::unique_ptr<Image> loadFromMemory(const std::vector<uint8_t>& buffer) = 0;
|
||||
};
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
*/
|
||||
|
||||
#include "ImageLoaderJpeg.hpp"
|
||||
#include "Base/Utils.hpp"
|
||||
#include <Data/Containers/Array.hpp>
|
||||
#include <fstream>
|
||||
#include <cstring>
|
||||
@@ -20,10 +21,8 @@ namespace OpenVulkano::Image
|
||||
{
|
||||
std::unique_ptr<Image> ImageLoaderJpeg::loadFromFile(const std::string& filePath)
|
||||
{
|
||||
std::ifstream file(filePath, std::ios::binary);
|
||||
if (!file) { throw std::runtime_error("Could not open file: " + filePath); }
|
||||
std::vector<uint8_t> buffer((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
|
||||
return loadJpeg(buffer.data(), buffer.size());
|
||||
Array<char> buffer = OpenVulkano::Utils::ReadFile(filePath);
|
||||
return loadJpeg(reinterpret_cast<uint8_t*>(buffer.Data()), buffer.Size());
|
||||
}
|
||||
|
||||
std::unique_ptr<Image> ImageLoaderJpeg::loadFromMemory(const std::vector<uint8_t>& buffer)
|
||||
@@ -33,11 +32,11 @@ namespace OpenVulkano::Image
|
||||
|
||||
std::unique_ptr<Image> ImageLoaderJpeg::loadJpeg(const uint8_t* data, size_t size)
|
||||
{
|
||||
Image result;
|
||||
|
||||
int rows, cols;
|
||||
#if __has_include("turbojpeg.h")
|
||||
{
|
||||
Image result;
|
||||
|
||||
int rows, cols;
|
||||
unsigned char* compressedImage = const_cast<uint8_t*>(data);
|
||||
|
||||
int jpegSubsamp;
|
||||
@@ -51,22 +50,16 @@ namespace OpenVulkano::Image
|
||||
tjDecompress2(jpegDecompressor, compressedImage, size, result.data.Data(), cols, 0 /*pitch*/, rows,
|
||||
TJPF_RGBA, TJFLAG_FASTDCT);
|
||||
tjDestroy(jpegDecompressor);
|
||||
result.resolution.x = cols;
|
||||
result.resolution.y = rows;
|
||||
result.resolution.z = 1;
|
||||
|
||||
return std::make_unique<Image>(std::move(result));
|
||||
}
|
||||
#else
|
||||
{
|
||||
int channels;
|
||||
uint8_t* pixelData = stbi_load_from_memory(data, size, &cols, &rows, &channels, 3);
|
||||
result.data = OpenVulkano::Array<uint8_t>(cols * rows * channels);
|
||||
result.dataFormat = channels == 3 ? OpenVulkano::DataFormat::R8G8B8_UINT :
|
||||
OpenVulkano::DataFormat::R8G8B8A8_UINT;
|
||||
std::memcpy(result.data.Data(), pixelData, result.data.Size());
|
||||
stbi_image_free(pixelData);
|
||||
return loadData(data, static_cast<int>(size));
|
||||
}
|
||||
#endif
|
||||
result.resolution.x = cols;
|
||||
result.resolution.y = rows;
|
||||
result.resolution.z = 1;
|
||||
|
||||
return std::make_unique<Image>(std::move(result));
|
||||
}
|
||||
}
|
||||
25
openVulkanoCpp/Image/ImageLoaderPng.cpp
Normal file
25
openVulkanoCpp/Image/ImageLoaderPng.cpp
Normal file
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#include "ImageLoaderPng.hpp"
|
||||
#include "Base/Utils.hpp"
|
||||
#include <Data/Containers/Array.hpp>
|
||||
#include <fstream>
|
||||
#include <cstring>
|
||||
|
||||
namespace OpenVulkano::Image
|
||||
{
|
||||
std::unique_ptr<Image> ImageLoaderPng::loadFromFile(const std::string& filePath)
|
||||
{
|
||||
Array<char> buffer = OpenVulkano::Utils::ReadFile(filePath);
|
||||
return loadData(reinterpret_cast<uint8_t*>(buffer.Data()), static_cast<int>(buffer.Size()));
|
||||
}
|
||||
|
||||
std::unique_ptr<Image> ImageLoaderPng::loadFromMemory(const std::vector<uint8_t>& buffer)
|
||||
{
|
||||
return loadData(buffer.data(), static_cast<int>(buffer.size()));
|
||||
}
|
||||
}
|
||||
19
openVulkanoCpp/Image/ImageLoaderPng.hpp
Normal file
19
openVulkanoCpp/Image/ImageLoaderPng.hpp
Normal file
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "ImageLoader.hpp"
|
||||
|
||||
namespace OpenVulkano::Image
|
||||
{
|
||||
class ImageLoaderPng : public IImageLoader
|
||||
{
|
||||
public:
|
||||
std::unique_ptr<Image> loadFromFile(const std::string& filePath) override;
|
||||
std::unique_ptr<Image> loadFromMemory(const std::vector<uint8_t>& buffer) override;
|
||||
};
|
||||
}
|
||||
28
openVulkanoCpp/Scene/AtlasMetadata.hpp
Normal file
28
openVulkanoCpp/Scene/AtlasMetadata.hpp
Normal file
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "Math/Math.hpp"
|
||||
|
||||
namespace OpenVulkano::Scene
|
||||
{
|
||||
struct GlyphInfo
|
||||
{
|
||||
//GlyphGeometry geometry;
|
||||
//GlyphBox glyphBox;
|
||||
Math::Vector3f_SIMD xyz[4] = {};
|
||||
Math::Vector2f_SIMD uv[4] = {};
|
||||
double advance = 0;
|
||||
};
|
||||
|
||||
struct AtlasMetadata
|
||||
{
|
||||
// vertical difference between baselines
|
||||
double lineHeight = 0;
|
||||
};
|
||||
|
||||
}
|
||||
32
openVulkanoCpp/Scene/FontAtlasGenerator.hpp
Normal file
32
openVulkanoCpp/Scene/FontAtlasGenerator.hpp
Normal file
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "Scene/AtlasMetadata.hpp"
|
||||
#include "Scene/Texture.hpp"
|
||||
#include <string>
|
||||
#include <optional>
|
||||
#include <map>
|
||||
#include <variant>
|
||||
#include <set>
|
||||
#include <memory>
|
||||
|
||||
namespace OpenVulkano::Scene
|
||||
{
|
||||
class FontAtlasGenerator
|
||||
{
|
||||
public:
|
||||
virtual void GenerateAtlas(const std::string& fontFile, const std::set<uint32_t>& charset,
|
||||
const std::optional<std::string>& pngOutput = std::nullopt) = 0;
|
||||
virtual void GenerateAtlas(const Array<char>& fontData, int length, const std::set<uint32_t>& charset,
|
||||
const std::optional<std::string>& pngOutput = std::nullopt) = 0;
|
||||
virtual void SaveAtlasMetadataInfo(const std::string& outputFile, bool packIntoSingleFile = true) const = 0;
|
||||
virtual const Texture& GetAtlas() const = 0;
|
||||
virtual std::map<uint32_t, GlyphInfo>& GetGlyphsInfo() = 0;
|
||||
virtual AtlasMetadata& GetAtlasMetadata() = 0;
|
||||
};
|
||||
}
|
||||
@@ -13,7 +13,7 @@
|
||||
#include <assimp/scene.h>
|
||||
#include <assimp/mesh.h>
|
||||
#include <assimp/postprocess.h>
|
||||
//#define ASSIMP_AVAILABLE
|
||||
#define ASSIMP_AVAILABLE
|
||||
#endif
|
||||
#include <stdexcept>
|
||||
|
||||
@@ -188,18 +188,16 @@ namespace OpenVulkano::Scene
|
||||
#endif
|
||||
}
|
||||
|
||||
void Geometry::SetIndices(const uint32_t* data, uint32_t size, uint32_t offset) const
|
||||
void Geometry::SetIndices(const uint32_t* data, uint32_t size, uint32_t dstOffset) const
|
||||
{
|
||||
size += offset;
|
||||
for(; offset < size; offset++)
|
||||
for(uint32_t i = 0; i < size; i++)
|
||||
{
|
||||
if (indexType == VertexIndexType::UINT16)
|
||||
{
|
||||
static_cast<uint16_t*>(indices)[offset] = static_cast<uint16_t>(data[offset]);
|
||||
static_cast<uint16_t*>(indices)[i + dstOffset] = static_cast<uint16_t>(data[i]);
|
||||
}
|
||||
else
|
||||
{
|
||||
static_cast<uint32_t*>(indices)[offset] = data[offset];
|
||||
{ static_cast<uint32_t*>(indices)[i + dstOffset] = data[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ namespace OpenVulkano
|
||||
|
||||
void Init(aiMesh* mesh);
|
||||
|
||||
void SetIndices(const uint32_t* data, uint32_t size, uint32_t offset = 0) const;
|
||||
void SetIndices(const uint32_t* data, uint32_t size, uint32_t dstOffset = 0) const;
|
||||
|
||||
void Close() override;
|
||||
|
||||
|
||||
276
openVulkanoCpp/Scene/MsdfFontAtlasGenerator.cpp
Normal file
276
openVulkanoCpp/Scene/MsdfFontAtlasGenerator.cpp
Normal file
@@ -0,0 +1,276 @@
|
||||
/*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#if __has_include("msdfgen.h")
|
||||
|
||||
#include "MsdfFontAtlasGenerator.hpp"
|
||||
#include "Base/Logger.hpp"
|
||||
#include "Scene/AtlasMetadata.hpp"
|
||||
#include <msdfgen.h>
|
||||
#include <msdfgen-ext.h>
|
||||
#include <msdf-atlas-gen/msdf-atlas-gen.h>
|
||||
#define STBI_MSC_SECURE_CRT
|
||||
#define STB_IMAGE_WRITE_IMPLEMENTATION
|
||||
#include <stb_image_write.h>
|
||||
#include <ft2build.h>
|
||||
#include FT_FREETYPE_H
|
||||
#include <fstream>
|
||||
#include <filesystem>
|
||||
|
||||
namespace OpenVulkano::Scene
|
||||
{
|
||||
using namespace msdfgen;
|
||||
using namespace msdf_atlas;
|
||||
|
||||
Charset MsdfFontAtlasGenerator::LoadAllGlyphs(const std::variant<std::string, Array<char>>& data)
|
||||
{
|
||||
FT_Library library;
|
||||
auto error = FT_Init_FreeType(&library);
|
||||
if (error) { throw std::runtime_error("Could not initalize freetype library\n"); }
|
||||
FT_Face face;
|
||||
if (std::holds_alternative<std::string>(data))
|
||||
{
|
||||
error = FT_New_Face(library, std::get<0>(data).c_str(), 0, &face);
|
||||
}
|
||||
else
|
||||
{
|
||||
auto& arr = std::get<1>(data);
|
||||
error = FT_New_Memory_Face(library, (const FT_Byte*)(arr.Data()), arr.Size(), 0, &face);
|
||||
}
|
||||
if (error == FT_Err_Unknown_File_Format) { throw std::runtime_error("Unknown font file format\n"); }
|
||||
else if (error) { throw std::runtime_error("Font file could not be opened or read or it's corrupted\n"); }
|
||||
|
||||
// some fancy font without unicode charmap
|
||||
if (face->charmap == nullptr) { throw std::runtime_error("Selected font doesn't contain unicode charmap"); }
|
||||
Charset s;
|
||||
FT_UInt glyphIndex;
|
||||
FT_ULong unicode = FT_Get_First_Char(face, &glyphIndex);
|
||||
while (glyphIndex != 0)
|
||||
{
|
||||
s.add(unicode);
|
||||
unicode = FT_Get_Next_Char(face, unicode, &glyphIndex);
|
||||
}
|
||||
FT_Done_Face(face);
|
||||
FT_Done_FreeType(library);
|
||||
return s;
|
||||
}
|
||||
|
||||
void MsdfFontAtlasGenerator::GenerateAtlas(const std::string& fontFile, const std::set<uint32_t>& charset,
|
||||
const std::optional<std::string>& pngOutput)
|
||||
{
|
||||
FreetypeHandle* ft;
|
||||
FontHandle* font;
|
||||
InitFreetypeFromFile(ft, font, fontFile);
|
||||
Charset s;
|
||||
std::for_each(s.begin(), s.end(), [&](uint32_t unicode) { s.add(unicode); });
|
||||
Generate(ft, font, s, pngOutput);
|
||||
}
|
||||
|
||||
void MsdfFontAtlasGenerator::GenerateAtlas(const Array<char>& fontData, int length,
|
||||
const std::set<uint32_t>& charset,
|
||||
const std::optional<std::string>& pngOutput)
|
||||
{
|
||||
FreetypeHandle* ft;
|
||||
FontHandle* font;
|
||||
InitFreetypeFromBuffer(ft, font, (const msdfgen::byte*)(fontData.Data()), length);
|
||||
Charset s;
|
||||
std::for_each(s.begin(), s.end(), [&](uint32_t unicode) { s.add(unicode); });
|
||||
Generate(ft, font, s, pngOutput);
|
||||
}
|
||||
|
||||
void MsdfFontAtlasGenerator::GenerateAtlas(const std::string& fontFile, const Charset& charset,
|
||||
const std::optional<std::string>& pngOutput)
|
||||
{
|
||||
// TODO: dynamic atlas and add only those symbols which are not present yet in current atlas
|
||||
FreetypeHandle* ft;
|
||||
FontHandle* font;
|
||||
InitFreetypeFromFile(ft, font, fontFile);
|
||||
Generate(ft, font, charset, pngOutput);
|
||||
}
|
||||
|
||||
void MsdfFontAtlasGenerator::GenerateAtlas(const msdfgen::byte* fontData, int length, const Charset& charset,
|
||||
const std::optional<std::string>& pngOutput)
|
||||
{
|
||||
FreetypeHandle* ft;
|
||||
FontHandle* font;
|
||||
InitFreetypeFromBuffer(ft, font, fontData, length);
|
||||
Generate(ft, font, charset, pngOutput);
|
||||
}
|
||||
|
||||
void MsdfFontAtlasGenerator::SaveAtlasMetadataInfo(const std::string& outputFile, bool packIntoSingleFile) const
|
||||
{
|
||||
if (m_symbols.empty())
|
||||
{
|
||||
Logger::DATA->info("No glyphs loaded. Nothing to save.");
|
||||
return;
|
||||
}
|
||||
std::string fileName = outputFile;
|
||||
uint32_t packedFlag = packIntoSingleFile;
|
||||
if (packIntoSingleFile)
|
||||
{
|
||||
size_t ext = outputFile.find_last_of('.');
|
||||
if (ext == std::string::npos)
|
||||
{
|
||||
fileName += "_packed";
|
||||
}
|
||||
else
|
||||
{
|
||||
fileName.insert(ext - 1, "_packed");
|
||||
}
|
||||
const BitmapConstRef<byte, 1>& storage = m_generator.atlasStorage();
|
||||
SavePng(m_generator.atlasStorage(), fileName, 1);
|
||||
}
|
||||
std::fstream fs(fileName.c_str(), std::ios_base::out | std::ios_base::binary | (packedFlag ? std::ios_base::app : std::ios_base::trunc));
|
||||
fs.write(reinterpret_cast<const char*>(&m_meta), sizeof(AtlasMetadata));
|
||||
uint64_t metadataBytes = sizeof(AtlasMetadata);
|
||||
for (const auto& [key, val] : m_symbols)
|
||||
{
|
||||
fs.write(reinterpret_cast<const char*>(&key), sizeof(uint32_t));
|
||||
fs.write(reinterpret_cast<const char*>(&val), sizeof(GlyphInfo));
|
||||
metadataBytes += sizeof(uint32_t);
|
||||
metadataBytes += sizeof(GlyphInfo);
|
||||
}
|
||||
fs.write(reinterpret_cast<const char*>(&metadataBytes), sizeof(uint64_t));
|
||||
fs.write(reinterpret_cast<const char*>(&packedFlag), sizeof(uint32_t));
|
||||
}
|
||||
|
||||
void MsdfFontAtlasGenerator::InitFreetypeFromFile(FreetypeHandle*& ft, FontHandle*& font, const std::string& fontFile)
|
||||
{
|
||||
ft = initializeFreetype();
|
||||
if (!ft) { throw std::runtime_error("Failed to initialize freetype"); }
|
||||
font = loadFont(ft, fontFile.data());
|
||||
if (!font)
|
||||
{
|
||||
deinitializeFreetype(ft);
|
||||
ft = nullptr;
|
||||
throw std::runtime_error(fmt::format("Failed to load font from file {0}", fontFile.data()));
|
||||
}
|
||||
}
|
||||
|
||||
void MsdfFontAtlasGenerator::InitFreetypeFromBuffer(FreetypeHandle*& ft, FontHandle*& font,
|
||||
const msdfgen::byte* fontData, int length)
|
||||
{
|
||||
ft = initializeFreetype();
|
||||
if (!ft) { throw std::runtime_error("Failed to initialize freetype"); }
|
||||
font = loadFontData(ft, fontData, length);
|
||||
if (!font)
|
||||
{
|
||||
deinitializeFreetype(ft);
|
||||
ft = nullptr;
|
||||
throw std::runtime_error("Failed to load font data from given buffer");
|
||||
}
|
||||
}
|
||||
|
||||
void MsdfFontAtlasGenerator::Generate(FreetypeHandle* ft, FontHandle* font, const Charset& chset,
|
||||
const std::optional<std::string>& pngOutput)
|
||||
{
|
||||
m_symbols.clear();
|
||||
std::vector<GlyphGeometry> glyphsGeometry;
|
||||
// FontGeometry is a helper class that loads a set of glyphs from a single font.
|
||||
FontGeometry fontGeometry(&glyphsGeometry);
|
||||
fontGeometry.loadCharset(font, 1, chset);
|
||||
|
||||
TightAtlasPacker packer;
|
||||
packer.setDimensionsConstraint(DimensionsConstraint::SQUARE);
|
||||
int width, height;
|
||||
const int glyphsPerRow = std::sqrt(glyphsGeometry.size());
|
||||
const int glyphSize = m_config.glyphSize;
|
||||
const int rowWidth = glyphSize * glyphsPerRow;
|
||||
packer.setDimensions(rowWidth, rowWidth);
|
||||
// something to play with. should not be too high.
|
||||
// more value - more sdf impact
|
||||
packer.setPixelRange(m_config.pixelRange);
|
||||
packer.setMiterLimit(m_config.miterLimit);
|
||||
packer.pack(glyphsGeometry.data(), glyphsGeometry.size());
|
||||
packer.getDimensions(width, height);
|
||||
|
||||
m_generator.resize(width, height);
|
||||
GeneratorAttributes attributes;
|
||||
m_generator.setAttributes(attributes);
|
||||
m_generator.setThreadCount(4);
|
||||
m_generator.generate(glyphsGeometry.data(), glyphsGeometry.size());
|
||||
|
||||
int idx = 0;
|
||||
const BitmapConstRef<byte, 1>& storage = m_generator.atlasStorage();
|
||||
m_atlasTex.resolution = Math::Vector3ui(storage.width, storage.height, 1);
|
||||
m_atlasTex.textureBuffer = (msdfgen::byte*) storage.pixels;
|
||||
m_atlasTex.format = OpenVulkano::DataFormat::R8_UNORM;
|
||||
m_atlasTex.size = storage.width * storage.height * 1; // 1 channel
|
||||
|
||||
m_meta.lineHeight = fontGeometry.getMetrics().lineHeight;
|
||||
|
||||
struct Bbox
|
||||
{
|
||||
double l = 0, r = 0, t = 0, b = 0;
|
||||
};
|
||||
|
||||
for (const auto& glyph: glyphsGeometry)
|
||||
{
|
||||
GlyphInfo& info = m_symbols[glyph.getCodepoint()];
|
||||
const GlyphBox& glyphBox = m_generator.getLayout()[idx++];
|
||||
|
||||
Bbox glyphBaselineBbox, glyphAtlasBbox;
|
||||
glyph.getQuadPlaneBounds(glyphBaselineBbox.l, glyphBaselineBbox.b, glyphBaselineBbox.r,
|
||||
glyphBaselineBbox.t);
|
||||
glyph.getQuadAtlasBounds(glyphAtlasBbox.l, glyphAtlasBbox.b, glyphAtlasBbox.r, glyphAtlasBbox.t);
|
||||
double bearingX = glyphBox.bounds.l;
|
||||
double bearingY = glyphBox.bounds.t;
|
||||
double w = glyphBaselineBbox.r - glyphBaselineBbox.l;
|
||||
double h = glyphBaselineBbox.t - glyphBaselineBbox.b;
|
||||
double l = glyphAtlasBbox.l;
|
||||
double r = glyphAtlasBbox.r;
|
||||
double t = glyphAtlasBbox.t;
|
||||
double b = glyphAtlasBbox.b;
|
||||
|
||||
info.xyz[0].x = bearingX;
|
||||
info.xyz[0].y = h - bearingY;
|
||||
info.xyz[0].z = 1;
|
||||
info.uv[0].x = l / m_atlasTex.resolution.x;
|
||||
info.uv[0].y = b / m_atlasTex.resolution.y;
|
||||
|
||||
info.xyz[1].x = bearingX + w;
|
||||
info.xyz[1].y = h - bearingY;
|
||||
info.xyz[1].z = 1;
|
||||
info.uv[1].x = r / m_atlasTex.resolution.x;
|
||||
info.uv[1].y = b / m_atlasTex.resolution.y;
|
||||
|
||||
info.xyz[2].x = bearingX + w;
|
||||
info.xyz[2].y = bearingY; //h - bearingY + h;
|
||||
info.xyz[2].z = 1;
|
||||
info.uv[2].x = r / m_atlasTex.resolution.x;
|
||||
info.uv[2].y = t / m_atlasTex.resolution.y;
|
||||
|
||||
info.xyz[3].x = bearingX;
|
||||
info.xyz[3].y = bearingY;
|
||||
info.xyz[3].z = 1;
|
||||
info.uv[3].x = l / m_atlasTex.resolution.x;
|
||||
info.uv[3].y = t / m_atlasTex.resolution.y;
|
||||
|
||||
info.advance = glyphBox.advance;
|
||||
}
|
||||
|
||||
if (pngOutput && !pngOutput->empty()) { SavePng(storage, pngOutput.value(), 1); }
|
||||
destroyFont(font);
|
||||
deinitializeFreetype(ft);
|
||||
}
|
||||
|
||||
void MsdfFontAtlasGenerator::SavePng(const BitmapConstRef<msdfgen::byte, 1>& storage, const std::string& output,
|
||||
int channels) const
|
||||
{
|
||||
stbi_flip_vertically_on_write(1);
|
||||
if (std::filesystem::path(output).extension() == ".png")
|
||||
{
|
||||
stbi_write_png(output.c_str(), storage.width, storage.height, channels, storage.pixels,
|
||||
channels * storage.width);
|
||||
}
|
||||
else
|
||||
{
|
||||
stbi_write_png((output + ".png").c_str(), storage.width, storage.height, channels, storage.pixels,
|
||||
channels * storage.width);
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
72
openVulkanoCpp/Scene/MsdfFontAtlasGenerator.hpp
Normal file
72
openVulkanoCpp/Scene/MsdfFontAtlasGenerator.hpp
Normal file
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#if __has_include("msdfgen.h")
|
||||
|
||||
#include "Scene/AtlasMetadata.hpp"
|
||||
#include "FontAtlasGenerator.hpp"
|
||||
#include "Scene/Texture.hpp"
|
||||
#include <msdfgen.h>
|
||||
#include <msdf-atlas-gen/msdf-atlas-gen.h>
|
||||
#include <string>
|
||||
#include <optional>
|
||||
#include <map>
|
||||
#include <variant>
|
||||
#define MSDFGEN_AVAILABLE 1
|
||||
|
||||
namespace OpenVulkano::Scene
|
||||
{
|
||||
|
||||
struct MsdfFontAtlasGeneratorConfig
|
||||
{
|
||||
int glyphSize = 42;
|
||||
double miterLimit = 1.0;
|
||||
msdfgen::Range pixelRange = 5;
|
||||
};
|
||||
|
||||
class MsdfFontAtlasGenerator : public FontAtlasGenerator
|
||||
{
|
||||
public:
|
||||
using SdfGenerator = msdf_atlas::ImmediateAtlasGenerator<float, 1, msdf_atlas::sdfGenerator,
|
||||
msdf_atlas::BitmapAtlasStorage<msdfgen::byte, 1>>;
|
||||
using Config = MsdfFontAtlasGeneratorConfig;
|
||||
static msdf_atlas::Charset LoadAllGlyphs(const std::variant<std::string, Array<char>>& data);
|
||||
void GenerateAtlas(const std::string& fontFile, const std::set<uint32_t>& charset,
|
||||
const std::optional<std::string>& pngOutput = std::nullopt) override;
|
||||
void GenerateAtlas(const Array<char>& fontData, int length, const std::set<uint32_t>& charset,
|
||||
const std::optional<std::string>& pngOutput = std::nullopt) override;
|
||||
void GenerateAtlas(const std::string& fontFile, const msdf_atlas::Charset& charset = msdf_atlas::Charset::ASCII,
|
||||
const std::optional<std::string>& pngOutput = std::nullopt);
|
||||
void GenerateAtlas(const msdfgen::byte* fontData, int length,
|
||||
const msdf_atlas::Charset& charset = msdf_atlas::Charset::ASCII,
|
||||
const std::optional<std::string>& pngOutput = std::nullopt);
|
||||
void SaveAtlasMetadataInfo(const std::string& outputFile, bool packIntoSingleFile = true) const override;
|
||||
void SetGeneratorConfig(const Config& config) { m_config = config; }
|
||||
const Texture& GetAtlas() const override { return m_atlasTex; }
|
||||
std::map<uint32_t, GlyphInfo>& GetGlyphsInfo() override { return m_symbols; }
|
||||
AtlasMetadata& GetAtlasMetadata() override { return m_meta; }
|
||||
SdfGenerator& GetFontAtlasGenerator() { return m_generator; }
|
||||
Config& GetGeneratorConfig() { return m_config; }
|
||||
private:
|
||||
void InitFreetypeFromFile(msdfgen::FreetypeHandle*& ft, msdfgen::FontHandle*& font, const std::string& file);
|
||||
void InitFreetypeFromBuffer(msdfgen::FreetypeHandle*& ft, msdfgen::FontHandle*& font,
|
||||
const msdfgen::byte* fontData, int length);
|
||||
void Generate(msdfgen::FreetypeHandle* ft, msdfgen::FontHandle* font, const msdf_atlas::Charset& chset,
|
||||
const std::optional<std::string>& pngOutput);
|
||||
void SavePng(const msdfgen::BitmapConstRef<msdfgen::byte, 1>& storage, const std::string& output,
|
||||
int channels) const;
|
||||
|
||||
private:
|
||||
SdfGenerator m_generator;
|
||||
Texture m_atlasTex;
|
||||
AtlasMetadata m_meta;
|
||||
Config m_config;
|
||||
std::map<uint32_t, GlyphInfo> m_symbols;
|
||||
};
|
||||
}
|
||||
#endif
|
||||
@@ -14,7 +14,7 @@ namespace OpenVulkano::Scene
|
||||
class Material;
|
||||
class UniformBuffer;
|
||||
|
||||
class SimpleDrawable final : public Drawable
|
||||
class SimpleDrawable : public Drawable
|
||||
{
|
||||
Geometry* m_mesh = nullptr;
|
||||
Material* m_material = nullptr;
|
||||
@@ -22,8 +22,9 @@ namespace OpenVulkano::Scene
|
||||
|
||||
public:
|
||||
SimpleDrawable(const DrawPhase phase = DrawPhase::MAIN)
|
||||
: Drawable(DrawEncoder::GetDrawEncoder<SimpleDrawable>(), phase)
|
||||
{}
|
||||
: Drawable(DrawEncoder::GetDrawEncoder<SimpleDrawable>(), phase)
|
||||
{
|
||||
}
|
||||
|
||||
explicit SimpleDrawable(const SimpleDrawable* toCopy)
|
||||
: Drawable(DrawEncoder::GetDrawEncoder<SimpleDrawable>(), toCopy->GetDrawPhase())
|
||||
|
||||
249
openVulkanoCpp/Scene/TextDrawable.cpp
Normal file
249
openVulkanoCpp/Scene/TextDrawable.cpp
Normal file
@@ -0,0 +1,249 @@
|
||||
/*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#include "TextDrawable.hpp"
|
||||
#include "Scene/Geometry.hpp"
|
||||
#include "Scene/Material.hpp"
|
||||
#include "Scene/Vertex.hpp"
|
||||
#include "Scene/UniformBuffer.hpp"
|
||||
#include "Scene/FontAtlasGenerator.hpp"
|
||||
#include "Base/Logger.hpp"
|
||||
#include "Host/ResourceLoader.hpp"
|
||||
#include "Image/ImageLoader.hpp"
|
||||
#include "DataFormat.hpp"
|
||||
#include "Base/Logger.hpp"
|
||||
#include <fstream>
|
||||
#include <utf8.h>
|
||||
|
||||
namespace OpenVulkano::Scene
|
||||
{
|
||||
Shader& TextDrawable::GetDefaultShader()
|
||||
{
|
||||
static bool once = true;
|
||||
static Shader textDefaultShader;
|
||||
if (once)
|
||||
{
|
||||
textDefaultShader.AddShaderProgram(OpenVulkano::ShaderProgramType::VERTEX, "Shader/text");
|
||||
textDefaultShader.AddShaderProgram(OpenVulkano::ShaderProgramType::FRAGMENT, "Shader/text");
|
||||
textDefaultShader.AddVertexInputDescription(OpenVulkano::Vertex::GetVertexInputDescription());
|
||||
textDefaultShader.AddDescriptorSetLayoutBinding(Texture::DESCRIPTOR_SET_LAYOUT_BINDING);
|
||||
textDefaultShader.AddDescriptorSetLayoutBinding(UniformBuffer::DESCRIPTOR_SET_LAYOUT_BINDING);
|
||||
textDefaultShader.alphaBlend = true;
|
||||
textDefaultShader.cullMode = CullMode::NONE;
|
||||
once = false;
|
||||
}
|
||||
return textDefaultShader;
|
||||
}
|
||||
|
||||
TextDrawable::TextDrawable(const Array<char>& atlasMetadata, const TextConfig& config)
|
||||
: TextDrawable(atlasMetadata, nullptr, config)
|
||||
{
|
||||
}
|
||||
|
||||
TextDrawable::TextDrawable(const std::string& atlasMetadataFile, const TextConfig& config)
|
||||
: TextDrawable(OpenVulkano::Utils::ReadFile(atlasMetadataFile), nullptr, config)
|
||||
{
|
||||
}
|
||||
|
||||
TextDrawable::TextDrawable(const std::string& atlasMetadataFile, Texture* atlasTex, const TextConfig& config)
|
||||
: TextDrawable(OpenVulkano::Utils::ReadFile(atlasMetadataFile), atlasTex, config)
|
||||
{
|
||||
}
|
||||
|
||||
TextDrawable::TextDrawable(const Array<char>& atlasMetadata, Texture* atlasTex, const TextConfig& config)
|
||||
{
|
||||
uint32_t isPacked;
|
||||
std::memcpy(&isPacked, atlasMetadata.Data() + (atlasMetadata.Size() - sizeof(uint32_t)), sizeof(uint32_t));
|
||||
uint64_t metadataBytes;
|
||||
std::memcpy(&metadataBytes, atlasMetadata.Data() + (atlasMetadata.Size() - sizeof(uint32_t) - sizeof(uint64_t)),
|
||||
sizeof(uint64_t));
|
||||
uint64_t offsetToMetadata = atlasMetadata.Size() - metadataBytes - sizeof(uint32_t) - sizeof(uint64_t);
|
||||
if (isPacked)
|
||||
{
|
||||
m_material.texture = new Texture();
|
||||
m_img = Image::IImageLoader::loadData((const uint8_t*) atlasMetadata.Data(),
|
||||
offsetToMetadata);
|
||||
m_material.texture->format = m_img->dataFormat;
|
||||
m_material.texture->resolution = m_img->resolution;
|
||||
m_material.texture->size = m_img->data.Size(); // 1 channel
|
||||
m_material.texture->textureBuffer = m_img->data.Data();
|
||||
}
|
||||
else
|
||||
{
|
||||
if (atlasTex == nullptr) { throw std::runtime_error("Atlas texture cannot be null with non-packed atlas metadata"); }
|
||||
m_material.texture = atlasTex;
|
||||
}
|
||||
|
||||
// metadata info
|
||||
size_t read_bytes = offsetToMetadata;
|
||||
size_t readMetadataBytes = 0;
|
||||
uint32_t unicode = 0;
|
||||
|
||||
std::memcpy(&m_meta, atlasMetadata.Data() + read_bytes, sizeof(AtlasMetadata));
|
||||
read_bytes += sizeof(AtlasMetadata);
|
||||
readMetadataBytes += sizeof(AtlasMetadata);
|
||||
while (readMetadataBytes < metadataBytes)
|
||||
{
|
||||
std::memcpy(&unicode, atlasMetadata.Data() + read_bytes, sizeof(uint32_t));
|
||||
read_bytes += sizeof(uint32_t);
|
||||
readMetadataBytes += sizeof(uint32_t);
|
||||
GlyphInfo& info = m_glyphs[unicode];
|
||||
std::memcpy(&info, atlasMetadata.Data() + read_bytes, sizeof(GlyphInfo));
|
||||
read_bytes += sizeof(GlyphInfo);
|
||||
readMetadataBytes += sizeof(GlyphInfo);
|
||||
}
|
||||
m_cfg = config;
|
||||
m_uniBuffer.Init(sizeof(TextConfig), &m_cfg, 3);
|
||||
}
|
||||
|
||||
TextDrawable::TextDrawable(const std::map<uint32_t, GlyphInfo>& glyphData, Texture* atlasTex,
|
||||
const TextConfig& config)
|
||||
{
|
||||
if (!atlasTex) { throw std::runtime_error("Atlas texture is nullptr"); }
|
||||
if (glyphData.empty()) { throw std::runtime_error("Glyphs are not loaded"); }
|
||||
m_material.texture = atlasTex;
|
||||
m_glyphs = glyphData;
|
||||
m_cfg = config;
|
||||
m_uniBuffer.Init(sizeof(TextConfig), &m_cfg, 3);
|
||||
}
|
||||
|
||||
TextDrawable::TextDrawable(FontAtlasGenerator* fontAtlasGenerator, const TextConfig& config)
|
||||
{
|
||||
if (!fontAtlasGenerator) { throw std::runtime_error("FontAtlasGenerator is nullptr"); }
|
||||
if (fontAtlasGenerator->GetGlyphsInfo().empty()) { throw std::runtime_error("Glyphs are not loaded"); }
|
||||
m_fontAtlasGenerator = fontAtlasGenerator;
|
||||
m_cfg = config;
|
||||
m_material.texture = const_cast<Texture*>(&m_fontAtlasGenerator->GetAtlas());
|
||||
m_uniBuffer.Init(sizeof(TextConfig), &m_cfg, 3);
|
||||
}
|
||||
|
||||
void TextDrawable::GenerateText(const std::string& text, const Math::Vector3f& pos)
|
||||
{
|
||||
if (text.empty())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
auto GetActualLength = [&]()
|
||||
{
|
||||
auto begin = text.begin();
|
||||
auto end = text.end();
|
||||
size_t len = 0;
|
||||
while (begin != end)
|
||||
{
|
||||
uint32_t c = utf8::next(begin, end);
|
||||
if (c == '\n') continue;
|
||||
++len;
|
||||
}
|
||||
return len;
|
||||
};
|
||||
|
||||
size_t len = GetActualLength();
|
||||
m_geometry.Close();
|
||||
m_geometry.Init(len * 4, len * 6);
|
||||
|
||||
// TODO: better implementation to decide what to use: data from atlas generator or data read from file
|
||||
// we have msdf but loaded glyphs metadata from file before
|
||||
AtlasMetadata* meta;
|
||||
std::map<uint32_t, GlyphInfo>* symbols;
|
||||
if (m_fontAtlasGenerator)
|
||||
{
|
||||
if (m_fontAtlasGenerator->GetGlyphsInfo().empty() && !m_glyphs.empty())
|
||||
{
|
||||
// texture is set in ctor
|
||||
symbols = &m_glyphs;
|
||||
}
|
||||
else
|
||||
{
|
||||
// just in case if FontAtlasGenerator changed it's atlas
|
||||
m_material.texture = const_cast<Texture*>(&m_fontAtlasGenerator->GetAtlas());
|
||||
symbols = &m_fontAtlasGenerator->GetGlyphsInfo();
|
||||
}
|
||||
meta = &m_fontAtlasGenerator->GetAtlasMetadata();
|
||||
}
|
||||
else
|
||||
{
|
||||
symbols = &m_glyphs;
|
||||
meta = &m_meta;
|
||||
}
|
||||
|
||||
const Texture& atlasTex = *m_material.texture;
|
||||
double cursorX = pos.x;
|
||||
auto begin = text.begin();
|
||||
auto end = text.end();
|
||||
const double lineHeight = meta->lineHeight;
|
||||
double posY = pos.y;
|
||||
int i = 0;
|
||||
while (begin != end)
|
||||
{
|
||||
uint32_t c = utf8::next(begin, end);
|
||||
if (c == '\n')
|
||||
{
|
||||
posY -= lineHeight;
|
||||
cursorX = pos.x;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (symbols->find(c) == symbols->end())
|
||||
{
|
||||
Logger::RENDER->error("Could not find glyph for character {}", c);
|
||||
if (symbols->find(static_cast<uint32_t>('?')) != symbols->end())
|
||||
{
|
||||
c = static_cast<uint32_t>('?');
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger::RENDER->error("Could not find glyph for character ? to replace glyph {}", c);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
uint32_t vIdx = i * 4;
|
||||
uint32_t indices[] = { 1 + vIdx, 2 + vIdx, 3 + vIdx, 1 + vIdx, 3 + vIdx, 0 + vIdx };
|
||||
GlyphInfo& info = symbols->at(c);
|
||||
|
||||
// left bottom
|
||||
m_geometry.vertices[vIdx].position.x = info.xyz[0].x + cursorX;
|
||||
m_geometry.vertices[vIdx].position.y = posY - info.xyz[0].y;
|
||||
m_geometry.vertices[vIdx].position.z = info.xyz[0].z;
|
||||
m_geometry.vertices[vIdx].textureCoordinates = Math::Vector3f(info.uv[0], 0);
|
||||
|
||||
// right bottom
|
||||
m_geometry.vertices[vIdx + 1].position.x = info.xyz[1].x + cursorX;
|
||||
m_geometry.vertices[vIdx + 1].position.y = posY - info.xyz[1].y;
|
||||
m_geometry.vertices[vIdx + 1].position.z = info.xyz[1].z;
|
||||
m_geometry.vertices[vIdx + 1].textureCoordinates = Math::Vector3f(info.uv[1], 0);
|
||||
|
||||
// top right
|
||||
m_geometry.vertices[vIdx + 2].position.x = info.xyz[2].x + cursorX;
|
||||
m_geometry.vertices[vIdx + 2].position.y = posY + info.xyz[2].y;
|
||||
m_geometry.vertices[vIdx + 2].position.z = info.xyz[2].z;
|
||||
m_geometry.vertices[vIdx + 2].textureCoordinates = Math::Vector3f(info.uv[2], 0);
|
||||
|
||||
// top left
|
||||
m_geometry.vertices[vIdx + 3].position.x = info.xyz[3].x + cursorX;
|
||||
m_geometry.vertices[vIdx + 3].position.y = posY + info.xyz[3].y;
|
||||
m_geometry.vertices[vIdx + 3].position.z = info.xyz[3].z;
|
||||
m_geometry.vertices[vIdx + 3].textureCoordinates = Math::Vector3f(info.uv[3], 0);
|
||||
m_geometry.SetIndices(indices, 6, 6 * i);
|
||||
// TODO: change to lower value(or ideally remove completely) to avoid overlapping and make less space between symbols
|
||||
// when setting for depth comparison operator will be available( <= )
|
||||
cursorX += info.advance + 0.08;
|
||||
++i;
|
||||
}
|
||||
SimpleDrawable::Init(m_shader, &m_geometry, &m_material, &m_uniBuffer);
|
||||
}
|
||||
|
||||
void TextDrawable::SetFontAtlasGenerator(FontAtlasGenerator* fontAtlasGenerator)
|
||||
{
|
||||
if (!fontAtlasGenerator || fontAtlasGenerator->GetGlyphsInfo().empty())
|
||||
{
|
||||
Logger::RENDER->error("FontAtlasGenerator is either nullptr or doesn't contain glyphs info");
|
||||
return;
|
||||
}
|
||||
m_fontAtlasGenerator = fontAtlasGenerator;
|
||||
}
|
||||
}
|
||||
63
openVulkanoCpp/Scene/TextDrawable.hpp
Normal file
63
openVulkanoCpp/Scene/TextDrawable.hpp
Normal file
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "SimpleDrawable.hpp"
|
||||
#include "Texture.hpp"
|
||||
#include "Material.hpp"
|
||||
#include "Geometry.hpp"
|
||||
#include "UniformBuffer.hpp"
|
||||
#include "AtlasMetadata.hpp"
|
||||
#include "Image/Image.hpp"
|
||||
#include <map>
|
||||
|
||||
namespace OpenVulkano::Scene
|
||||
{
|
||||
|
||||
class FontAtlasGenerator;
|
||||
|
||||
struct TextConfig
|
||||
{
|
||||
Math::Vector4f textColor = { 1, 1, 1, 1 };
|
||||
Math::Vector4f borderColor = { 1, 0, 0, 1 };
|
||||
Math::Vector4f backgroundColor = { 0, 1, 0, 0 };
|
||||
float threshold = 0.4f;
|
||||
float borderSize = 0.05f;
|
||||
float smoothing = 1.f/32.f;
|
||||
uint32_t applyBorder = false;
|
||||
//bool sdfMultiChannel = false;
|
||||
};
|
||||
|
||||
class TextDrawable : public SimpleDrawable
|
||||
{
|
||||
public:
|
||||
static Shader& GetDefaultShader();
|
||||
TextDrawable(const Array<char>& atlasMetadata, const TextConfig& config = TextConfig());
|
||||
TextDrawable(const std::string& atlasMetadataFile, const TextConfig& config = TextConfig());
|
||||
TextDrawable(const std::string& atlasMetadataFile, Texture* atlasTex, const TextConfig& config = TextConfig());
|
||||
TextDrawable(const Array<char>& atlasMetadata, Texture* atlasTex, const TextConfig& config = TextConfig());
|
||||
TextDrawable(const std::map<uint32_t, GlyphInfo>& glyphData, Texture* atlasTex, const TextConfig& config = TextConfig());
|
||||
TextDrawable(FontAtlasGenerator* fontAtlasGenerator, const TextConfig& config = TextConfig());
|
||||
void GenerateText(const std::string& text, const Math::Vector3f& pos = Math::Vector3f(0.f));
|
||||
void SetConfig(const TextConfig& cfg) { m_cfg = cfg; }
|
||||
void SetShader(Shader* shader) { m_shader = shader; }
|
||||
TextConfig& GetConfig() { return m_cfg; }
|
||||
Shader* GetShader() { return m_shader; }
|
||||
void SetFontAtlasGenerator(FontAtlasGenerator* fontAtlasGenerator);
|
||||
FontAtlasGenerator* GetFontAtlasGenerator() { return m_fontAtlasGenerator; }
|
||||
private:
|
||||
Geometry m_geometry;
|
||||
Material m_material;
|
||||
UniformBuffer m_uniBuffer;
|
||||
std::map<uint32_t, GlyphInfo> m_glyphs;
|
||||
AtlasMetadata m_meta;
|
||||
std::unique_ptr<Image::Image> m_img;
|
||||
FontAtlasGenerator* m_fontAtlasGenerator = nullptr;
|
||||
Shader* m_shader = &GetDefaultShader();
|
||||
TextConfig m_cfg;
|
||||
};
|
||||
}
|
||||
39
openVulkanoCpp/Shader/text.frag
Normal file
39
openVulkanoCpp/Shader/text.frag
Normal file
@@ -0,0 +1,39 @@
|
||||
#version 450
|
||||
|
||||
layout(location = 0) in vec2 texCoord;
|
||||
|
||||
layout(location = 0) out vec4 outColor;
|
||||
|
||||
layout(set = 2, binding = 0) uniform sampler2D texSampler;
|
||||
|
||||
layout(set = 3, binding = 0) uniform TextConfig
|
||||
{
|
||||
vec4 textColor;
|
||||
vec4 borderColor;
|
||||
vec4 backgroundColor;
|
||||
float threshold;
|
||||
float borderSize;
|
||||
float smoothing;
|
||||
bool applyBorder;
|
||||
} textConfig;
|
||||
|
||||
void main()
|
||||
{
|
||||
float distance = texture(texSampler, texCoord).r;
|
||||
float alpha = smoothstep(textConfig.threshold - textConfig.smoothing, textConfig.threshold + textConfig.smoothing, distance);
|
||||
if (textConfig.applyBorder)
|
||||
{
|
||||
float border = smoothstep(textConfig.threshold + textConfig.borderSize - textConfig.smoothing,
|
||||
textConfig.threshold + textConfig.borderSize + textConfig.smoothing, distance);
|
||||
outColor = mix(textConfig.borderColor, textConfig.textColor, border) * alpha;
|
||||
}
|
||||
else
|
||||
{
|
||||
outColor = vec4(textConfig.textColor) * alpha;
|
||||
}
|
||||
|
||||
if (textConfig.backgroundColor.a != 0)
|
||||
{
|
||||
outColor = mix(textConfig.backgroundColor, outColor, alpha);
|
||||
}
|
||||
}
|
||||
26
openVulkanoCpp/Shader/text.vert
Normal file
26
openVulkanoCpp/Shader/text.vert
Normal file
@@ -0,0 +1,26 @@
|
||||
#version 450
|
||||
layout(location = 0) in vec3 position;
|
||||
layout(location = 1) in vec3 normal;
|
||||
layout(location = 2) in vec3 tangent;
|
||||
layout(location = 3) in vec3 biTangent;
|
||||
layout(location = 4) in vec3 textureCoordinates;
|
||||
layout(location = 5) in vec4 color;
|
||||
layout(location = 0) out vec2 fragTextureCoordinates;
|
||||
|
||||
layout(set = 0, binding = 0) uniform NodeData
|
||||
{
|
||||
mat4 world;
|
||||
} node;
|
||||
|
||||
layout(set = 1, binding = 0) uniform CameraData
|
||||
{
|
||||
mat4 viewProjection;
|
||||
mat4 view;
|
||||
mat4 projection;
|
||||
vec4 camPos;
|
||||
} cam;
|
||||
|
||||
void main() {
|
||||
gl_Position = cam.viewProjection * node.world * vec4(position, 1.0);
|
||||
fragTextureCoordinates.xy = textureCoordinates.xy;
|
||||
}
|
||||
@@ -351,7 +351,7 @@ namespace OpenVulkano::Vulkan
|
||||
else
|
||||
{
|
||||
vkBuffer = new VulkanUniformBuffer();
|
||||
mBuffer = CreateDeviceOnlyBufferWithData(Scene::Node::SIZE, vk::BufferUsageFlagBits::eUniformBuffer, buffer->data);
|
||||
mBuffer = CreateDeviceOnlyBufferWithData(buffer->size, vk::BufferUsageFlagBits::eUniformBuffer, buffer->data);
|
||||
buffer->updated = false;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user