Merge remote-tracking branch 'origin/master' into project_setup_refactor

# Conflicts:
#	CMakeLists.txt
This commit is contained in:
Georg Hagen
2024-08-14 22:47:19 +02:00
61 changed files with 2489 additions and 96 deletions

View File

@@ -4,10 +4,10 @@ AccessModifierOffset: "-4"
AlignAfterOpenBracket: Align
AlignEscapedNewlines: Left
AlignOperands: true
AllowShortBlocksOnASingleLine: Always
AllowShortCaseLabelsOnASingleLine: true
AllowShortIfStatementsOnASingleLine: AllIfsAndElse
AllowShortLoopsOnASingleLine: true
AllowShortBlocksOnASingleLine: Empty
AllowShortCaseLabelsOnASingleLine: false
AllowShortIfStatementsOnASingleLine: Never
AllowShortLoopsOnASingleLine: false
BreakBeforeBinaryOperators: NonAssignment
BreakBeforeBraces: Allman
BreakBeforeTernaryOperators: false
@@ -23,6 +23,7 @@ IndentCaseLabels: true
IndentPPDirectives: BeforeHash
IndentWidth: "4"
IndentWrappedFunctionNames: true
InsertBraces: true
KeepEmptyLinesAtEOF: true
KeepEmptyLinesAtTheStartOfBlocks: false
MaxEmptyLinesToKeep: "2"

View File

@@ -22,3 +22,4 @@ TRACY_REPO=https://git.madvoxel.net/Mirrors/tracy.git
STB_REPO=https://git.madvoxel.net/Mirrors/stb.git
UNITS_REPO=https://git.madvoxel.net/Mirrors/units.git
ANKERLUD_REPO=https://git.madvoxel.net/Mirrors/ankerl_unordered_dense.git
MSDFGEN_REPO=https://git.madvoxel.net/Mirrors/msdfgen.git

View File

@@ -32,7 +32,7 @@ jobs:
- name: Install Dev Packages
if: matrix.os == 'ubuntu-latest'
run: >
sudo apt update && sudo apt install -y extra-cmake-modules libwayland-dev libxkbcommon-dev xorg-dev libarchive-dev libassimp-dev ninja-build glslang-tools glslang-dev unzip
sudo apt update && sudo apt install -y extra-cmake-modules libwayland-dev libxkbcommon-dev xorg-dev libarchive-dev libassimp-dev ninja-build glslang-tools glslang-dev unzip zip
&& sudo wget https://sourceforge.net/projects/bin2c/files/1.1/bin2c-1.1.zip && sudo unzip bin2c-1.1.zip && cd bin2c && sudo gcc -o bin2c bin2c.c && sudo mv bin2c /usr/bin
- name: Configure CMake
run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DDEPENDENCY_MIRROR_FILE="${{github.workspace}}/.gitea/workflows/DependencyMirrors.txt"

2
.gitignore vendored
View File

@@ -577,7 +577,5 @@ MigrationBackup/
CMakeSettings.json
perf.csv
.idea

View File

@@ -1,5 +1,13 @@
include(ExternalProject)
if (CMAKE_TOOLCHAIN_FILE)
if(NOT IS_ABSOLUTE ${CMAKE_TOOLCHAIN_FILE})
set(TOOLCHAIN "${CMAKE_BINARY_DIR}/${CMAKE_TOOLCHAIN_FILE}")
else()
set(TOOLCHAIN "${CMAKE_TOOLCHAIN_FILE}")
endif()
endif()
add_subdirectory(glm)
if (NOT ANDROID AND NOT IOS)
add_subdirectory(glfw)
@@ -23,6 +31,7 @@ add_subdirectory(libarchive)
add_subdirectory(boost)
add_subdirectory(units)
add_subdirectory(libjpeg-turbo)
add_subdirectory(msdf)
if (NOT IOS)
add_subdirectory(curl)
endif()

View File

@@ -1,4 +1,3 @@
Find_Package(Boost QUIET COMPONENTS regex)
include(FetchContent)
if(NOT DEFINED BOOST_LIBRARY_MIRROR)

View File

@@ -1,10 +1,10 @@
include(Utils)
find_package(LibArchive QUIET)
if (NOT DEFINED LibArchive_LIBRARIES)
if (NOT LibArchive_FOUND)
file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/deps)
execute_process(
COMMAND ${CMAKE_COMMAND} -G ${CMAKE_GENERATOR} -DTOOLCHAIN_FILE=${TOOLCHAIN_FILE} ${CMAKE_CURRENT_SOURCE_DIR}/ext -DZLIB_REPO=${ZLIB_REPO} -DZSTD_REPO=${ZSTD_REPO} -DLZ4_REPO=${LZ4_REPO} -DLIBARCHIVE_REPO=${LIBARCHIVE_REPO}
COMMAND ${CMAKE_COMMAND} -G ${CMAKE_GENERATOR} -DCMAKE_TOOLCHAIN_FILE=${TOOLCHAIN} -DPLATFORM=${PLATFORM} ${CMAKE_CURRENT_SOURCE_DIR}/ext -DZLIB_REPO=${ZLIB_REPO} -DZSTD_REPO=${ZSTD_REPO} -DLZ4_REPO=${LZ4_REPO} -DLIBARCHIVE_REPO=${LIBARCHIVE_REPO}
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/deps
)
execute_process(
@@ -22,7 +22,9 @@ endif ()
function(LinkLibArchive TARGET)
list(APPEND CMAKE_PREFIX_PATH ${CMAKE_BINARY_DIR}/deps/INSTALL)
find_package(LibArchive REQUIRED)
if (NOT IOS)
set(ZLIB_USE_STATIC_LIBS ON)
endif()
find_package(ZLIB REQUIRED)
find_package(LZ4 QUIET)
find_package(zstd QUIET)

View File

@@ -24,7 +24,8 @@ ExternalProject_Add(zlib
CMAKE_GENERATOR ${CMAKE_GENERATOR}
CMAKE_ARGS
-DBUILD_SHARED_LIBS:BOOL=OFF
-DCMAKE_TOOLCHAIN_FILE:FILEPATH=${TOOLCHAIN_FILE}
-DCMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE}
-DPLATFORM=${PLATFORM}
-DCMAKE_INSTALL_PREFIX:PATH=${CMAKE_BINARY_DIR}/INSTALL
-DCMAKE_BUILD_TYPE:STRING=Release
)
@@ -43,7 +44,8 @@ ExternalProject_Add(zstd
-DBUILD_SHARED_LIBS:BOOL=OFF
-DZSTD_BUILD_STATIC:BOOL=ON
-DCMAKE_BUILD_TYPE:STRING=Release
-DCMAKE_TOOLCHAIN_FILE:FILEPATH=${TOOLCHAIN_FILE}
-DCMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE}
-DPLATFORM=${PLATFORM}
-DCMAKE_INSTALL_PREFIX:PATH=${CMAKE_BINARY_DIR}/INSTALL
)
@@ -61,7 +63,8 @@ ExternalProject_Add(lz4
-DLZ4_BUILD_LEGACY_LZ4C:BOOL=OFF
-DLZ4_BUNDLE_MODE:BOOL=ON
-DCMAKE_BUILD_TYPE:STRING=Release
-DCMAKE_TOOLCHAIN_FILE:FILEPATH=${TOOLCHAIN_FILE}
-DCMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE}
-DPLATFORM=${PLATFORM}
-DCMAKE_INSTALL_PREFIX:PATH=${CMAKE_BINARY_DIR}/INSTALL
)
@@ -75,7 +78,8 @@ ExternalProject_Add(
BINARY_DIR libarchive-build
CMAKE_GENERATOR ${CMAKE_GENERATOR}
CMAKE_ARGS
-DCMAKE_TOOLCHAIN_FILE:FILEPATH=${TOOLCHAIN_FILE}
-DCMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE}
-DPLATFORM=${PLATFORM}
-DCMAKE_BUILD_TYPE:STRING=Release
-DBUILD_SHARED_LIBS:BOOL=OFF
-DENABLE_TEST:BOOL=OFF

View File

@@ -7,15 +7,8 @@ if (libjpeg-turbo_FOUND)
message("Using system libjpeg-turbo")
elseif (NOT IOS)
file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/deps_ljt)
if (CMAKE_TOOLCHAIN_FILE)
if(NOT IS_ABSOLUTE ${CMAKE_TOOLCHAIN_FILE})
set(TOOLCHAIN "${CMAKE_BINARY_DIR}/${CMAKE_TOOLCHAIN_FILE}")
else()
set(TOOLCHAIN "${CMAKE_TOOLCHAIN_FILE}")
endif()
endif()
execute_process(
COMMAND ${CMAKE_COMMAND} -G ${CMAKE_GENERATOR} -DTOOLCHAIN_FILE=${TOOLCHAIN} ${CMAKE_CURRENT_SOURCE_DIR}/ext -DLIBJPEGTURBO_REPO=${LIBJPEGTURBO_REPO}
COMMAND ${CMAKE_COMMAND} -G ${CMAKE_GENERATOR} -DTOOLCHAIN_FILE=${TOOLCHAIN} -DPLATFORM=${PLATFORM} ${CMAKE_CURRENT_SOURCE_DIR}/ext -DLIBJPEGTURBO_REPO=${LIBJPEGTURBO_REPO}
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/deps_ljt
)
execute_process(

97
3rdParty/msdf/CMakeLists.txt vendored Normal file
View File

@@ -0,0 +1,97 @@
if (ENABLE_MSDF)
include(FetchContent)
if(NOT DEFINED MSDFGEN_REPO)
set(MSDFGEN_REPO https://github.com/Chlumsky/msdfgen.git)
endif ()
if(NOT DEFINED MSDFGEN_ATRLAS_REPO)
set(MSDFGEN_ATRLAS_REPO https://github.com/Chlumsky/msdf-atlas-gen.git)
endif()
if(NOT DEFINED FREETYPE_REPO)
set(FREETYPE_REPO https://github.com/freetype/freetype.git)
endif()
unset(Freetype_FOUND)
find_package(Freetype QUIET)
if (NOT Freetype_FOUND OR NOT EXISTS "${CMAKE_BINARY_DIR}/_deps/freetype-src/build")
message("Installing freetype from sources")
FetchContent_Declare(
freetype
EXCLUDE_FROM_ALL
GIT_REPOSITORY ${FREETYPE_REPO}
GIT_TAG master
GIT_SHALLOW TRUE
)
set(FT_DISABLE_ZLIB ON CACHE BOOL "" FORCE)
set(FT_DISABLE_BZIP2 ON CACHE BOOL "" FORCE)
set(FT_DISABLE_PNG ON CACHE BOOL "" FORCE)
set(FT_DISABLE_HARFBUZZ ON CACHE BOOL "" FORCE)
set(FT_DISABLE_BROTLI ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(freetype)
set(FT_SRC_DIR "${CMAKE_BINARY_DIR}/_deps/freetype-src")
set(FT_BUILD_DIR "${FT_SRC_DIR}/build")
file(MAKE_DIRECTORY ${FT_BUILD_DIR})
if (IOS)
set(PLATFORM_CFG -DCMAKE_TOOLCHAIN_FILE=${CMAKE_CURRENT_SOURCE_DIR}/patched_freetype_iOS_toolchain.cmake)
elseif (APPLE)
set(PLATFORM_CFG -DCMAKE_OSX_ARCHITECTURES=arm64)
endif()
execute_process(
COMMAND ${CMAKE_COMMAND} -G ${CMAKE_GENERATOR} ${PLATFORM_CFG} -DCMAKE_BUILD_TYPE:STRING=Release -DFT_DISABLE_PNG=ON -DFT_DISABLE_HARFBUZZ=ON -DFT_DISABLE_BROTLI=ON -S ${FT_SRC_DIR} -B ${FT_BUILD_DIR}
-DBUILD_SHARED_LIBS=OFF -DCMAKE_INSTALL_PREFIX=${FT_SRC_DIR}/freetype-install ${PLATFORM_ARG}
WORKING_DIRECTORY ${FT_BUILD_DIR}
)
execute_process(
COMMAND ${CMAKE_COMMAND} --build ${FT_BUILD_DIR} --config Release --target install
WORKING_DIRECTORY ${FT_BUILD_DIR} RESULT_VARIABLE build_result
)
if (NOT ${build_result} EQUAL "0")
message(FATAL_ERROR "Failed to build freetype!")
endif()
set(FREETYPE_INCLUDE_DIR "${FT_SRC_DIR}/freetype-install/include/freetype2" CACHE INTERNAL "ft include dir")
set(FREETYPE_BUILT_FROM_SOURCES ON CACHE BOOL "ft built from sources")
list(APPEND CMAKE_PREFIX_PATH "${FT_SRC_DIR}/freetype-install")
endif()
set(MSDFGEN_DISABLE_SVG TRUE CACHE INTERNAL "disable msdfgen svg")
set(MSDFGEN_USE_SKIA OFF CACHE BOOL "use skia" FORCE)
set(MSDF_ATLAS_USE_SKIA OFF CACHE BOOL "use skia" FORCE)
set(MSDF_ATLAS_MSDFGEN_EXTERNAL ON CACHE BOOL "do not build msdfgen submodule" FORCE)
set(MSDFGEN_DYNAMIC_RUNTIME ON CACHE BOOL "msvc dynamic runtime" FORCE)
set(MSDF_ATLAS_DYNAMIC_RUNTIME ON CACHE BOOL "msvc dynamic runtime" FORCE)
set(MSDFGEN_DISABLE_PNG ON CACHE BOOL "disable png" FORCE)
set(MSDFGEN_USE_VCPKG OFF CACHE BOOL "do not use vcpkg" FORCE)
set(MSDF_ATLAS_USE_VCPKG OFF CACHE BOOL "do not use vcpkg" FORCE)
FetchContent_Declare(
msdfgen
EXCLUDE_FROM_ALL
GIT_REPOSITORY ${MSDFGEN_REPO}
GIT_TAG v1.12
GIT_SHALLOW TRUE
)
FetchContent_MakeAvailable(msdfgen)
FetchContent_Declare(
msdfgen_atlas
EXCLUDE_FROM_ALL
GIT_REPOSITORY ${MSDFGEN_ATRLAS_REPO}
GIT_TAG master
GIT_SHALLOW TRUE
)
FetchContent_MakeAvailable(msdfgen_atlas)
endif()
function(LinkMsdf TARGET)
if (ENABLE_MSDF)
target_link_libraries(${TARGET} PRIVATE msdfgen::msdfgen msdfgen::msdfgen-ext msdf-atlas-gen)
if (FREETYPE_BUILT_FROM_SOURCES)
target_include_directories(${TARGET} PUBLIC ${FREETYPE_INCLUDE_DIR})
else()
target_include_directories(${TARGET} PUBLIC ${FREETYPE_INCLUDE_DIRS})
endif()
endif()
endfunction()

View File

@@ -0,0 +1,270 @@
# iOS.cmake
#
# Copyright (C) 2014-2024 by
# David Turner, Robert Wilhelm, and Werner Lemberg.
#
# Written by David Wimsey <david@wimsey.us>
#
# This file is part of the FreeType project, and may only be used, modified,
# and distributed under the terms of the FreeType project license,
# LICENSE.TXT. By continuing to use, modify, or distribute this file you
# indicate that you have read the license and understand and accept it
# fully.
#
#
# This file is derived from the files `Platform/Darwin.cmake' and
# `Platform/UnixPaths.cmake', which are part of CMake 2.8.4. It has been
# altered for iOS development.
# Options
# -------
#
# IOS_PLATFORM = OS | SIMULATOR
#
# This decides whether SDKS are selected from the `iPhoneOS.platform' or
# `iPhoneSimulator.platform' folders.
#
# OS - the default, used to build for iPhone and iPad physical devices,
# which have an ARM architecture.
# SIMULATOR - used to build for the Simulator platforms, which have an
# x86 architecture.
#
# CMAKE_IOS_DEVELOPER_ROOT = /path/to/platform/Developer folder
#
# By default, this location is automatically chosen based on the
# IOS_PLATFORM value above. If you manually set this variable, it
# overrides the default location and forces the use of a particular
# Developer Platform.
#
# CMAKE_IOS_SDK_ROOT = /path/to/platform/Developer/SDKs/SDK folder
#
# By default, this location is automatically chosen based on the
# CMAKE_IOS_DEVELOPER_ROOT value. In this case it is always the most
# up-to-date SDK found in the CMAKE_IOS_DEVELOPER_ROOT path. If you
# manually set this variable, it forces the use of a specific SDK
# version.
#
#
# Macros
# ------
#
# set_xcode_property (TARGET XCODE_PROPERTY XCODE_VALUE)
#
# A convenience macro for setting Xcode specific properties on targets.
#
# Example:
#
# set_xcode_property(myioslib IPHONEOS_DEPLOYMENT_TARGET "3.1")
#
# find_host_package (PROGRAM ARGS)
#
# A macro to find executable programs on the host system, not within the
# iOS environment. Thanks to the `android-cmake' project for providing
# the command.
# standard settings
set(CMAKE_SYSTEM_NAME Darwin)
set(CMAKE_SYSTEM_VERSION 1)
set(UNIX True)
set(APPLE True)
set(IOS True)
# required as of cmake 2.8.10
set(CMAKE_OSX_DEPLOYMENT_TARGET ""
CACHE STRING "Force unset of the deployment target for iOS" FORCE
)
# determine the cmake host system version so we know where to find the iOS
# SDKs
find_program(CMAKE_UNAME uname /bin /usr/bin /usr/local/bin)
if (CMAKE_UNAME)
execute_process(COMMAND uname ARGS -r OUTPUT_VARIABLE CMAKE_HOST_SYSTEM_VERSION)
string(REGEX REPLACE "^([0-9]+)\\.([0-9]+).*$" "\\1"
DARWIN_MAJOR_VERSION "${CMAKE_HOST_SYSTEM_VERSION}")
endif (CMAKE_UNAME)
# skip the platform compiler checks for cross compiling
set(CMAKE_CXX_COMPILER_WORKS TRUE)
set(CMAKE_C_COMPILER_WORKS TRUE)
# all iOS/Darwin specific settings - some may be redundant
set(CMAKE_SHARED_LIBRARY_PREFIX "lib")
set(CMAKE_SHARED_LIBRARY_SUFFIX ".dylib")
set(CMAKE_SHARED_MODULE_PREFIX "lib")
set(CMAKE_SHARED_MODULE_SUFFIX ".so")
set(CMAKE_MODULE_EXISTS 1)
set(CMAKE_DL_LIBS "")
set(CMAKE_C_OSX_COMPATIBILITY_VERSION_FLAG
"-compatibility_version ")
set(CMAKE_C_OSX_CURRENT_VERSION_FLAG
"-current_version ")
set(CMAKE_CXX_OSX_COMPATIBILITY_VERSION_FLAG
"${CMAKE_C_OSX_COMPATIBILITY_VERSION_FLAG}")
set(CMAKE_CXX_OSX_CURRENT_VERSION_FLAG
"${CMAKE_C_OSX_CURRENT_VERSION_FLAG}")
# hidden visibility is required for cxx on iOS
set(CMAKE_C_FLAGS_INIT "")
set(CMAKE_CXX_FLAGS_INIT
"-headerpad_max_install_names -fvisibility=hidden -fvisibility-inlines-hidden")
set(CMAKE_C_LINK_FLAGS
"-Wl,-search_paths_first ${CMAKE_C_LINK_FLAGS}")
set(CMAKE_CXX_LINK_FLAGS
"-Wl,-search_paths_first ${CMAKE_CXX_LINK_FLAGS}")
set(CMAKE_PLATFORM_HAS_INSTALLNAME 1)
set(CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS
"-dynamiclib -headerpad_max_install_names")
set(CMAKE_SHARED_MODULE_CREATE_C_FLAGS
"-bundle -headerpad_max_install_names")
set(CMAKE_SHARED_MODULE_LOADER_C_FLAG
"-Wl,-bundle_loader,")
set(CMAKE_SHARED_MODULE_LOADER_CXX_FLAG
"-Wl,-bundle_loader,")
set(CMAKE_FIND_LIBRARY_SUFFIXES
".dylib" ".so" ".a")
# hack: If a new cmake (which uses CMAKE_INSTALL_NAME_TOOL) runs on an old
# build tree (where `install_name_tool' was hardcoded), and where
# CMAKE_INSTALL_NAME_TOOL isn't in the cache and still cmake didn't
# fail in `CMakeFindBinUtils.cmake' (because it isn't rerun), hardcode
# CMAKE_INSTALL_NAME_TOOL here to `install_name_tool' so it behaves as
# it did before.
if (NOT DEFINED CMAKE_INSTALL_NAME_TOOL)
find_program(CMAKE_INSTALL_NAME_TOOL install_name_tool)
endif (NOT DEFINED CMAKE_INSTALL_NAME_TOOL)
# set up iOS platform unless specified manually with IOS_PLATFORM
if (NOT DEFINED IOS_PLATFORM)
set(IOS_PLATFORM "OS")
endif (NOT DEFINED IOS_PLATFORM)
set(IOS_PLATFORM ${IOS_PLATFORM} CACHE STRING "Type of iOS Platform")
# check the platform selection and setup for developer root
if (${IOS_PLATFORM} STREQUAL "OS")
set(IOS_PLATFORM_LOCATION "iPhoneOS.platform")
# this causes the installers to properly locate the output libraries
set(CMAKE_XCODE_EFFECTIVE_PLATFORMS "-iphoneos")
elseif (${IOS_PLATFORM} STREQUAL "SIMULATOR")
set(IOS_PLATFORM_LOCATION "iPhoneSimulator.platform")
# this causes the installers to properly locate the output libraries
set(CMAKE_XCODE_EFFECTIVE_PLATFORMS "-iphonesimulator")
else (${IOS_PLATFORM} STREQUAL "OS")
message(FATAL_ERROR
"Unsupported IOS_PLATFORM value selected. Please choose OS or SIMULATOR.")
endif (${IOS_PLATFORM} STREQUAL "OS")
# set up iOS developer location unless specified manually with
# CMAKE_IOS_DEVELOPER_ROOT --
# note that Xcode 4.3 changed the installation location; choose the most
# recent one available
set(XCODE_POST_43_ROOT
"/Applications/Xcode.app/Contents/Developer/Platforms/${IOS_PLATFORM_LOCATION}/Developer")
set(XCODE_PRE_43_ROOT
"/Developer/Platforms/${IOS_PLATFORM_LOCATION}/Developer")
if (NOT DEFINED CMAKE_IOS_DEVELOPER_ROOT)
if (EXISTS ${XCODE_POST_43_ROOT})
set(CMAKE_IOS_DEVELOPER_ROOT ${XCODE_POST_43_ROOT})
elseif (EXISTS ${XCODE_PRE_43_ROOT})
set(CMAKE_IOS_DEVELOPER_ROOT ${XCODE_PRE_43_ROOT})
endif (EXISTS ${XCODE_POST_43_ROOT})
endif (NOT DEFINED CMAKE_IOS_DEVELOPER_ROOT)
set(CMAKE_IOS_DEVELOPER_ROOT ${CMAKE_IOS_DEVELOPER_ROOT}
CACHE PATH "Location of iOS Platform"
)
# find and use the most recent iOS SDK unless specified manually with
# CMAKE_IOS_SDK_ROOT
if (NOT DEFINED CMAKE_IOS_SDK_ROOT)
file(GLOB _CMAKE_IOS_SDKS "${CMAKE_IOS_DEVELOPER_ROOT}/SDKs/*")
if (_CMAKE_IOS_SDKS)
list(SORT _CMAKE_IOS_SDKS)
list(REVERSE _CMAKE_IOS_SDKS)
list(GET _CMAKE_IOS_SDKS 0 CMAKE_IOS_SDK_ROOT)
else (_CMAKE_IOS_SDKS)
message(FATAL_ERROR
"No iOS SDK's found in default search path ${CMAKE_IOS_DEVELOPER_ROOT}. Manually set CMAKE_IOS_SDK_ROOT or install the iOS SDK.")
endif (_CMAKE_IOS_SDKS)
message(STATUS "Toolchain using default iOS SDK: ${CMAKE_IOS_SDK_ROOT}")
endif (NOT DEFINED CMAKE_IOS_SDK_ROOT)
set(CMAKE_IOS_SDK_ROOT ${CMAKE_IOS_SDK_ROOT}
CACHE PATH "Location of the selected iOS SDK"
)
# set the sysroot default to the most recent SDK
set(CMAKE_OSX_SYSROOT ${CMAKE_IOS_SDK_ROOT}
CACHE PATH "Sysroot used for iOS support"
)
# set the architecture for iOS --
# note that currently both ARCHS_STANDARD_32_BIT and
# ARCHS_UNIVERSAL_IPHONE_OS set armv7 only, so set both manually
if (${IOS_PLATFORM} STREQUAL "OS")
set(IOS_ARCH arm64)
else (${IOS_PLATFORM} STREQUAL "OS")
set(IOS_ARCH i386)
endif (${IOS_PLATFORM} STREQUAL "OS")
set(CMAKE_OSX_ARCHITECTURES ${IOS_ARCH}
CACHE string "Build architecture for iOS"
)
# set the find root to the iOS developer roots and to user defined paths
set(CMAKE_FIND_ROOT_PATH
${CMAKE_IOS_DEVELOPER_ROOT}
${CMAKE_IOS_SDK_ROOT}
${CMAKE_PREFIX_PATH}
CACHE string "iOS find search path root"
)
# default to searching for frameworks first
set(CMAKE_FIND_FRAMEWORK FIRST)
# set up the default search directories for frameworks
set(CMAKE_SYSTEM_FRAMEWORK_PATH
${CMAKE_IOS_SDK_ROOT}/System/Library/Frameworks
${CMAKE_IOS_SDK_ROOT}/System/Library/PrivateFrameworks
${CMAKE_IOS_SDK_ROOT}/Developer/Library/Frameworks
)
# only search the iOS SDKs, not the remainder of the host filesystem
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
# this little macro lets you set any Xcode specific property
macro(set_xcode_property TARGET XCODE_PROPERTY XCODE_VALUE)
set_property(TARGET ${TARGET}
PROPERTY XCODE_ATTRIBUTE_${XCODE_PROPERTY} ${XCODE_VALUE})
endmacro(set_xcode_property)
# this macro lets you find executable programs on the host system
macro(find_host_package)
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE NEVER)
set(IOS FALSE)
find_package(${ARGN})
set(IOS TRUE)
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
endmacro(find_host_package)
# eof

View File

@@ -30,6 +30,7 @@ option(USE_ASSIMP "If assimp should be used" ON)
option(TRACY_ENABLE "Enable Tracy Profiler" OFF)
option(ENABLE_TEST "Enable testing" ON)
option(ENABLE_EXAMPLE "Enable examples" ON)
option(ENABLE_MSDF "Enable msdf library" ON)
# -----------------------------------------------------------------
if (IOS)

View File

@@ -0,0 +1,23 @@
function(CopyResourcesToExe TARGET FROM EXTENSIONS)
file(GLOB RESOURCES "${FROM}/*")
set(RESOURCES_TO_COPY "")
if (${EXTENSIONS} STREQUAL "*")
set(RESOURCES_TO_COPY ${RESOURCES})
else()
foreach(RESOURCE ${RESOURCES})
get_filename_component(EXT "${RESOURCE}" EXT)
list(FIND EXTENSIONS ${EXT} EXT_FOUND)
if(NOT EXT_FOUND EQUAL -1)
list(APPEND RESOURCES_TO_COPY "${RESOURCE}")
endif()
endforeach()
endif()
foreach(RESOURCE ${RESOURCES_TO_COPY})
add_custom_command(TARGET ${TARGET} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
${RESOURCE} $<TARGET_FILE_DIR:${TARGET}>
)
endforeach()
endfunction()

View File

@@ -17,6 +17,7 @@ function(SetWarningSettings TARGET)
target_compile_options(${TARGET} PRIVATE -Wall -Wno-unknown-pragmas)
elseif (WIN32)
if (MSVC)
add_definitions(-D_CRT_SECURE_NO_WARNINGS)
set_target_properties(${TARGET} PROPERTIES COMPILE_FLAGS "/wd4068")
set_target_properties(${TARGET} PROPERTIES LINK_FLAGS "/ignore:4099")
endif()

View File

@@ -2,6 +2,7 @@ cmake_minimum_required(VERSION 3.28 FATAL_ERROR)
include(SetupVulkan)
include(Utils)
include(CopyResourcesToExe)
file(GLOB_RECURSE SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/ExampleApps/*.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/*.h" "${CMAKE_CURRENT_SOURCE_DIR}/*.hpp")
if (IOS)
@@ -33,7 +34,8 @@ if(APPLE)
LinkAppleFrameworks(OpenVulkano_Examples)
endif ()
CopyResourcesToExe(openVulkanoCpp "${CMAKE_CURRENT_SOURCE_DIR}/../fonts" ".ttf")
CopyResourcesToExe(openVulkanoCpp "${CMAKE_CURRENT_SOURCE_DIR}/ExampleSources" "*")
target_include_directories(OpenVulkano_Examples PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_include_directories(OpenVulkano_Examples PRIVATE openVulkanoCpp)

View File

@@ -10,6 +10,7 @@
#include "ExampleApps/MovingCubeApp.hpp"
#include "ExampleApps/TexturedCubeExampleApp.hpp"
#include "ExampleApps/BillboardExampleApp.hpp"
#include "ExampleApps/TextExampleApp.hpp"
#include <vector>
namespace OpenVulkano
@@ -18,6 +19,7 @@ namespace OpenVulkano
{ "Cubes Example App", &CubesExampleApp::Create },
{ "Moving Cube Example App", &MovingCubeApp::Create },
{ "Textured Cube Example App", &TexturedCubeExampleApp::Create },
{ "Billboard Example App", &BillboardExampleApp::Create }
{ "Billboard Example App", &BillboardExampleApp::Create },
{ "Text Example App", &TextExampleApp::Create }
};
}

View File

@@ -0,0 +1,176 @@
/*
* 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 "TextExampleApp.hpp"
#include "Scene/Scene.hpp"
#include "Scene/Shader/Shader.hpp"
#include "Scene/Geometry.hpp"
#include "Scene/TextDrawable.hpp"
#include "Scene/GeometryFactory.hpp"
#include "Scene/Material.hpp"
#include "Scene/Vertex.hpp"
#include "Scene/SimpleDrawable.hpp"
#include "Scene/UI/PerformanceInfo.hpp"
#include "Scene/UniformBuffer.hpp"
#include "Input/InputManager.hpp"
#include "Host/GraphicsAppManager.hpp"
#include "Host/GLFW/WindowGLFW.hpp"
#include "Host/ResourceLoader.hpp"
#include "Math/Math.hpp"
#include "Base/EngineConfiguration.hpp"
#include "Controller/FreeCamCameraController.hpp"
#include "Image/ImageLoaderPng.hpp"
#include "Scene/FontAtlasGenerator.hpp"
#include "Scene/IFontAtlasGenerator.hpp"
#include <filesystem>
#ifdef _WIN32
#undef TRANSPARENT
#endif
namespace OpenVulkano
{
using namespace Scene;
using namespace Input;
using namespace Math;
namespace fs = std::filesystem;
class TextExampleAppImpl final : public TextExampleApp
{
public:
void Init() override
{
auto engineConfig = OpenVulkano::EngineConfiguration::GetEngineConfiguration();
engineConfig->SetNumThreads(4);
engineConfig->SetPreferFramebufferFormatSRGB(false);
std::srand(1); // Fix seed for random numbers
m_scene.Init();
m_cam.Init(70, 16, 9, 0.1f, 100);
m_scene.SetCamera(&m_cam);
static std::vector<std::pair<std::string, TextConfig>> texts;
texts.push_back(std::make_pair("ABab?.^{}_cdFGETG123)(", TextConfig()));
texts.push_back(std::make_pair("Hello, World!", TextConfig()));
texts.push_back(std::make_pair("\u0410\u0411\u0412\u041F", TextConfig()));
texts.push_back(std::make_pair("Unsupported glyphs \u1E30\u1E31 are coming", TextConfig()));
texts.push_back(std::make_pair("This is first line\nSecond gg line\nThird G line", TextConfig()));
texts[0].second.applyBorder = true;
texts[1].second.backgroundColor.a = 1;
const int N = texts.size();
auto& resourceLoader = ResourceLoader::GetInstance();
const std::string fontPath = resourceLoader.GetResourcePath("Roboto-Regular.ttf");
m_nodesPool.resize(N * 2);
m_drawablesPool.resize(N * 2);
#ifdef MSDFGEN_AVAILABLE
msdf_atlas::Charset charset = SdfFontAtlasGenerator::LoadAllGlyphs(fontPath);
m_atlasGenerator.GenerateAtlas(fontPath, charset);
m_msdfAtlasGenerator.GenerateAtlas(fontPath, charset);
#else
auto sdfMetadataInfo = resourceLoader.GetResource("sdf_atlas_packed");
auto msdfMetadataInfo = resourceLoader.GetResource("msdf_atlas_packed.png");
#endif
for (int i = 0; i < texts.size() * 2; i++)
{
int textIdx = i % texts.size();
TextDrawable* t = nullptr;
#ifdef MSDFGEN_AVAILABLE
if (i < texts.size())
{
t = new TextDrawable(&m_atlasGenerator, texts[textIdx].second);
t->SetShader(&TextDrawable::GetSdfDefaultShader());
}
else
{
t = new TextDrawable(&m_msdfAtlasGenerator, texts[textIdx].second);
t->SetShader(&TextDrawable::GetMsdfDefaultShader());
}
#else
if (i < texts.size())
{
t = new TextDrawable(sdfMetadataInfo, texts[textIdx].second);
t->SetShader(&TextDrawable::GetSdfDefaultShader());
}
else
{
t = new TextDrawable(msdfMetadataInfo, texts[textIdx].second);
t->SetShader(&TextDrawable::GetMsdfDefaultShader());
}
// OR use separate texture + metadata file
//auto metadataInfo = resourceLoader.GetResource("atlas_metadata");
//auto data = resourceLoader.GetResource("roboto-regular-atlas.png");
//Image::ImageLoaderPng loader;
//static auto image = loader.loadData(reinterpret_cast<uint8_t*>(data.Data()), data.Size());
//static Texture tex;
//tex.resolution = image->resolution;
//tex.textureBuffer = image->data.Data();
//tex.format = image->dataFormat;
//tex.size = image->data.Size(); // 1 channel
//TextDrawable* t = new TextDrawable(metadataInfo, &tex, texts[i].second);
#endif // MSDFGEN_AVAILABLE
t->GenerateText(texts[textIdx].first);
m_drawablesPool[i] = t;
m_nodesPool[i].Init();
m_nodesPool[i].SetMatrix(Math::Utils::translate(glm::mat4x4(1.f), Vector3f((i < texts.size() ? -5 : 15), 2 - textIdx * 2, 0)));
m_nodesPool[i].AddDrawable(m_drawablesPool[i]);
m_scene.GetRoot()->AddChild(&m_nodesPool[i]);
}
GetGraphicsAppManager()->GetRenderer()->SetScene(&m_scene);
m_camController.Init(&m_cam);
m_camController.SetDefaultKeybindings();
m_camController.SetPosition({ 10, 0, 15 });
m_camController.SetBoostFactor(5);
std::shared_ptr<OpenVulkano::Scene::UI::PerformanceInfo> m_perfInfo =
std::make_shared<OpenVulkano::Scene::UI::PerformanceInfo>();
m_ui.AddElement(m_perfInfo);
GetGraphicsAppManager()->GetRenderer()->SetActiveUi(&m_ui);
}
void Tick() override
{
m_camController.Tick();
}
void Close() override
{
for (SimpleDrawable* d: m_drawablesPool)
{
d->Close();
delete d;
}
}
private:
OpenVulkano::Scene::Scene m_scene;
PerspectiveCamera m_cam;
OpenVulkano::FreeCamCameraController m_camController;
#ifdef MSDFGEN_AVAILABLE
SdfFontAtlasGenerator m_atlasGenerator;
MsdfFontAtlasGenerator m_msdfAtlasGenerator;
#endif
std::vector<SimpleDrawable*> m_drawablesPool;
std::vector<Node> m_nodesPool;
Vector3f_SIMD m_position = { 0, 0, -10 };
OpenVulkano::Scene::UI::SimpleUi m_ui;
std::shared_ptr<OpenVulkano::Scene::UI::PerformanceInfo> m_perfInfo;
};
IGraphicsApp* TextExampleApp::Create() { return new TextExampleAppImpl(); }
std::unique_ptr<IGraphicsApp> TextExampleApp::CreateUnique()
{
return std::make_unique<TextExampleAppImpl>();
}
}
#pragma clang diagnostic pop
#pragma clang diagnostic pop

View File

@@ -0,0 +1,27 @@
/*
* 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 "Base/IGraphicsApp.hpp"
#include <memory>
namespace OpenVulkano
{
class TextExampleApp : public IGraphicsApp
{
public:
static IGraphicsApp* Create();
static std::unique_ptr<IGraphicsApp> CreateUnique();
[[nodiscard]] std::string GetAppName() const final
{ return "Text ExampleApp"; }
[[nodiscard]] OpenVulkano::Version GetAppVersion() const final
{ return {"v1.0"}; }
};
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1012 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 449 KiB

201
fonts/LICENSE.txt Normal file
View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

BIN
fonts/Roboto-Regular.ttf Normal file

Binary file not shown.

View File

@@ -4,6 +4,8 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
#pragma once
#include "Event.hpp"
namespace OpenVulkano

View File

@@ -0,0 +1,41 @@
/*
* 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 <condition_variable>
#include <mutex>
namespace OpenVulkano
{
class PauseCV final
{
std::mutex m_mutex;
std::condition_variable m_condVar;
bool m_paused = false;
public:
void Pause() { m_paused = true; }
void Resume()
{
{
std::unique_lock lock(m_mutex);
m_paused = false;
}
m_condVar.notify_all();
}
void Check()
{
while (m_paused)
{
std::unique_lock l(m_mutex);
m_condVar.wait(l, [this]{ return !m_paused; });
}
}
};
}

View File

@@ -59,6 +59,7 @@ target_link_libraries(openVulkanoCpp PUBLIC magic_enum yaml-cpp fmt spdlog glm p
LinkAssimp(openVulkanoCpp)
LinkLibArchive(openVulkanoCpp)
LinkLibJpegTurbo(openVulkanoCpp)
LinkMsdf(openVulkanoCpp)
SetGlmDefines(openVulkanoCpp)
add_compile_definitions(LIBARCHIVE_STATIC)

View File

@@ -45,6 +45,13 @@ namespace OpenVulkano
}
}
void MapCameraController::SetSliceHeight(float height)
{
float diff = height - GetCamera()->GetPosition().y;
GetCamera()->SetMatrix(Math::Utils::translate(Math::Vector3f_SIMD{0,diff,0}) * GetCamera()->GetMatrix());
CURRENT_FRAME.needsRedraw = true;
}
void MapCameraController::SetDefaultKeybindings()
{
m_actionUp->BindKey(Input::InputKey::Controller::AXIS_LEFT_Y);

View File

@@ -36,6 +36,8 @@ namespace OpenVulkano
m_dirSide = side;
}
void SetSliceHeight(float height);
void Tick() override;
void SetDefaultKeybindings();

View File

@@ -10,6 +10,8 @@
#include <optional>
#include "Data/Concurent/MutexProtectedObject.hpp"
#undef MAP_TYPE
namespace OpenVulkano
{
template<typename KEY, typename VALUE>

View File

@@ -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);

View File

@@ -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;
};
}

View File

@@ -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()

View File

@@ -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();

View File

@@ -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);

View File

@@ -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;
};
}

View File

@@ -69,4 +69,23 @@ namespace OpenVulkano
}
return true;
}
ByteSize FsUtils::GetDirSize(const std::filesystem::path& dir)
{
ByteSize size = 0;
for (auto& p: fs::directory_iterator(dir))
{
if (fs::is_directory(p))
{
size += GetDirSize(p);
}
else
{
size += p.file_size();
}
}
return size;
}
}

View File

@@ -6,6 +6,7 @@
#pragma once
#include "Math/ByteSize.hpp"
#include <filesystem>
namespace OpenVulkano
@@ -17,5 +18,7 @@ namespace OpenVulkano
static bool DeleteEmptySubTrees(const std::filesystem::path& dir);
static bool IsTreeEmpty(const std::filesystem::path& dir);
static ByteSize GetDirSize(const std::filesystem::path& dir);
};
}

View 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/.
*/
#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);
}
switch (channels)
{
case 1:
result.dataFormat = OpenVulkano::DataFormat::R8_UNORM;
break;
case 2:
result.dataFormat = OpenVulkano::DataFormat::R8G8_UNORM;
break;
case 3:
case 4:
result.dataFormat = OpenVulkano::DataFormat::R8G8B8A8_UNORM;
break;
}
result.resolution.x = cols;
result.resolution.y = rows;
result.resolution.z = 1;
if (channels == 3)
{
result.data = OpenVulkano::Array<uint8_t>(cols * rows * 4);
for (size_t srcPos = 0, dstPos = 0; srcPos < cols * rows * 3; srcPos += 3, dstPos += 4)
{
result.data[dstPos] = pixelData[srcPos];
result.data[dstPos + 1] = pixelData[srcPos + 1];
result.data[dstPos + 2] = pixelData[srcPos + 2];
result.data[dstPos + 3] = 255;
}
}
else
{
result.data = OpenVulkano::Array<uint8_t>(cols * rows * channels);
std::memcpy(result.data.Data(), pixelData, result.data.Size());
}
stbi_image_free(pixelData);
return std::make_unique<Image>(std::move(result));
}
}

View File

@@ -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;
};

View File

@@ -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)
@@ -32,12 +31,12 @@ namespace OpenVulkano::Image
}
std::unique_ptr<Image> ImageLoaderJpeg::loadJpeg(const uint8_t* data, size_t size)
{
#if __has_include("turbojpeg.h")
{
Image result;
int rows, cols;
#if __has_include("turbojpeg.h")
{
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);
}
#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);
}
#endif
result.resolution.x = cols;
result.resolution.y = rows;
result.resolution.z = 1;
return std::make_unique<Image>(std::move(result));
}
#else
{
return loadData(data, static_cast<int>(size));
}
#endif
}
}

View 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()));
}
}

View 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;
};
}

View File

@@ -132,6 +132,17 @@ namespace OpenVulkano
constexpr operator uint64_t() const { return bytes; }
operator std::string() const { return Format(); }
ByteSize operator +(const ByteSize other) const { return bytes + other.bytes; }
ByteSize operator -(const ByteSize other) const { return bytes + other.bytes; }
ByteSize operator +(const size_t other) const { return bytes + other; }
ByteSize operator -(const size_t other) const { return bytes + other; }
ByteSize& operator =(const size_t other) { bytes = other; return *this; }
ByteSize& operator =(const ByteSize other) { bytes = other.bytes; return *this; }
ByteSize& operator +=(const size_t other) { bytes += other; return *this; }
ByteSize& operator +=(const ByteSize other) { bytes += other.bytes; return *this; }
ByteSize& operator -=(const size_t other) { bytes -= other; return *this; }
ByteSize& operator -=(const ByteSize other) { bytes -= other.bytes; return *this; }
};
inline constexpr ByteSize operator"" _kiB(long double num) { return { num, ByteSizeUnit::kiB }; }

View File

@@ -80,12 +80,12 @@ namespace OpenVulkano::Math
[[nodiscard]] float GetFovX(float imageWidth) const
{
return 2 * atanf((Fx() / imageWidth) * 0.5f);
return 2 * atanf((imageWidth / Fx()) * 0.5f);
}
[[nodiscard]] float GetFovY(float imageHeight) const
{
return 2 * atanf((Fy() / imageHeight) * 0.5f);
return 2 * atanf((imageHeight / Fy()) * 0.5f);
}
[[nodiscard]] Math::Vector3f ProjectTo3D(Math::Vector2i pixelCoordinates, float depth) const

View File

@@ -7,20 +7,20 @@
#pragma once
#include "Math/Math.hpp"
#include <algorithm>
namespace OpenVulkano::Math
{
class RGB565
{
uint16_t Make5(uint8_t val)
{
return val * 31.0f / 255.0f;
}
uint16_t Make6(uint8_t val)
{
return val * 63.0f / 255.0f;
}
static uint16_t Make5(uint8_t val) { return val * 31.0f / 255.0f; }
static uint16_t Make6(uint8_t val) { return val * 63.0f / 255.0f; }
static uint8_t Unmake5(uint16_t val) { return static_cast<uint8_t>(val * 255.0f / 31.0f); }
static uint8_t Unmake6(uint16_t val) { return static_cast<uint8_t>(val * 255.0f / 63.0f); }
static float Unmake5ToFloat(uint16_t val) { return std::clamp(val / 31.0f, 0.0f, 1.0f); }
static float Unmake6ToFloat(uint16_t val) { return std::clamp(val / 63.0f, 0.0f, 1.0f); }
static uint16_t Make5FromFloat(float val) { return (uint16_t) std::clamp(val * 31.0f, 0.0f, 31.f); }
static uint16_t Make6FromFloat(float val) { return (uint16_t) std::clamp(val * 63.0f, 0.0f, 63.f); }
public:
union
@@ -34,12 +34,272 @@ namespace OpenVulkano::Math
};
};
RGB565(Math::Vector4uc color = {0, 0, 0, 1})
: b(Make5(color.b))
, g(Make6(color.g))
, r(Make5(color.r))
RGB565() : r(0), g(0), b(0) {}
template<typename T, typename = std::enable_if_t<std::is_unsigned_v<T> || std::is_signed_v<T>>>
RGB565(const Math::Vector3<T>& color) : b(Make5(color.b)), g(Make6(color.g)), r(Make5(color.r))
{
}
template<typename T, typename = std::enable_if_t<std::is_unsigned_v<T> || std::is_signed_v<T>>>
RGB565(const Math::Vector4<T>& color) : b(Make5(color.b)), g(Make6(color.g)), r(Make5(color.r))
{
}
template<typename T, typename = std::enable_if_t<std::is_unsigned_v<T> || std::is_signed_v<T>>>
RGB565(const Math::Vector3_SIMD<T>& color) : b(Make5(color.b)), g(Make6(color.g)), r(Make5(color.r))
{
}
template<typename T, typename = std::enable_if_t<std::is_floating_point_v<T>>>
RGB565(const Math::Vector3<T>& color)
: b(Make5FromFloat(color.b)), g(Make6FromFloat(color.g)), r(Make5FromFloat(color.r))
{
}
template<typename T, typename = std::enable_if_t<std::is_floating_point_v<T>>>
RGB565(const Math::Vector4<T>& color)
: b(Make5FromFloat(color.b)), g(Make6FromFloat(color.g)), r(Make5FromFloat(color.r))
{
}
template<typename T, typename = std::enable_if_t<std::is_floating_point_v<T>>>
RGB565(const Math::Vector3_SIMD<T>& color)
: b(Make5FromFloat(color.b)), g(Make6FromFloat(color.g)), r(Make5FromFloat(color.r))
{
}
uint8_t GetR() { return Unmake5(r); }
uint8_t GetG() { return Unmake6(g); }
uint8_t GetB() { return Unmake5(b); }
template<typename T, typename = std::enable_if_t<std::is_unsigned_v<T> || std::is_signed_v<T>>>
Math::Vector3<T> Get3()
{
return { GetR(), GetG(), GetB() };
}
template<typename T, typename = std::enable_if_t<std::is_unsigned_v<T> || std::is_signed_v<T>>>
Math::Vector4<T> Get4()
{
return { GetR(), GetG(), GetB(), 1 };
}
template<typename T, typename = std::enable_if_t<std::is_unsigned_v<T> || std::is_signed_v<T>>>
Math::Vector3_SIMD<T> GetSIMD()
{
return { GetR(), GetG(), GetB() };
}
template<typename T, typename = std::enable_if_t<std::is_floating_point_v<T>>> Math::Vector3<T> Get3Normalized()
{
return { GetR_Normalized(), GetG_Normalized(), GetB_Normalized() };
}
template<typename T, typename = std::enable_if_t<std::is_floating_point_v<T>>> Math::Vector4<T> Get4Normalized()
{
return { GetR_Normalized(), GetG_Normalized(), GetB_Normalized(), 1 };
}
template<typename T, typename = std::enable_if_t<std::is_floating_point_v<T>>>
Math::Vector3_SIMD<T> Get3NormalizedSIMD()
{
return { GetR_Normalized(), GetG_Normalized(), GetB_Normalized() };
}
void SetR(uint8_t red) { r = Make5(red); }
void SetG(uint8_t green) { g = Make6(green); }
void SetB(uint8_t blue) { b = Make5(blue); }
template<typename T, typename = std::enable_if_t<std::is_unsigned_v<T> || std::is_signed_v<T>>>
void Set(const Math::Vector3<T>& color)
{
r = Make5(color.r);
g = Make6(color.g);
b = Make5(color.b);
}
template<typename T, typename = std::enable_if_t<std::is_unsigned_v<T> || std::is_signed_v<T>>>
void Set(const Math::Vector4<T>& color)
{
r = Make5(color.r);
g = Make6(color.g);
b = Make5(color.b);
}
template<typename T, typename = std::enable_if_t<std::is_floating_point_v<T>>>
void SetNormalized(const Math::Vector3<T>& color)
{
r = Make5FromFloat(color.r);
g = Make6FromFloat(color.g);
b = Make5FromFloat(color.b);
}
template<typename T, typename = std::enable_if_t<std::is_floating_point_v<T>>>
void SetNormalized(const Math::Vector4<T>& color)
{
r = Make5FromFloat(color.r);
g = Make6FromFloat(color.g);
b = Make5FromFloat(color.b);
}
float GetR_Normalized() { return Unmake5ToFloat(r); }
float GetG_Normalized() { return Unmake6ToFloat(g); }
float GetB_Normalized() { return Unmake5ToFloat(b); }
void SetR_Normalized(float red) { r = Make5FromFloat(red); }
void SetG_Normalized(float green) { g = Make6FromFloat(green); }
void SetB_Normalized(float blue) { b = Make5FromFloat(blue); }
RGB565& operator=(const RGB565& other)
{
value = other.value;
return *this;
}
RGB565& operator=(RGB565&& other) noexcept
{
value = other.value;
return *this;
}
template<typename T, typename = std::enable_if_t<std::is_unsigned_v<T> || std::is_signed_v<T>>>
RGB565& operator=(const Vector3<T>& color)
{
Set(color);
return *this;
}
template<typename T, typename = std::enable_if_t<std::is_unsigned_v<T> || std::is_signed_v<T>>>
RGB565& operator=(const Vector4<T>& color)
{
Set(color);
return *this;
}
template<typename T, typename = std::enable_if_t<std::is_unsigned_v<T> || std::is_signed_v<T>>>
RGB565& operator=(const Vector3_SIMD<T>& color)
{
Set(color);
return *this;
}
template<typename T, typename = std::enable_if_t<std::is_unsigned_v<T> || std::is_signed_v<T>>>
RGB565& operator=(const Vector4_SIMD<T>& color)
{
Set(color);
return *this;
}
template<typename T, typename = std::enable_if_t<std::is_floating_point_v<T>>>
RGB565& operator=(const Vector3<T>& color)
{
SetNormalized(color);
return *this;
}
template<typename T, typename = std::enable_if_t<std::is_floating_point_v<T>>>
RGB565& operator=(const Vector4<T>& color)
{
SetNormalized(color);
return *this;
}
template<typename T, typename = std::enable_if_t<std::is_floating_point_v<T>>>
RGB565& operator=(const Vector3_SIMD<T>& color)
{
SetNormalized(color);
return *this;
}
template<typename T, typename = std::enable_if_t<std::is_unsigned_v<T> || std::is_signed_v<T>>>
RGB565& operator+=(const Vector3<T>& color)
{
Set(Get3<T>() + color);
return *this;
}
template<typename T, typename = std::enable_if_t<std::is_unsigned_v<T> || std::is_signed_v<T>>>
RGB565& operator+=(const Vector4<T>& color)
{
Set(Get4<T>() + color);
return *this;
}
template<typename T, typename = std::enable_if_t<std::is_unsigned_v<T> || std::is_signed_v<T>>>
RGB565& operator+=(const Vector3_SIMD<T>& color)
{
Set(Get3SIMD<T>() + color);
return *this;
}
template<typename T, typename = std::enable_if_t<std::is_floating_point_v<T>>>
RGB565& operator+=(const Vector3<T>& color)
{
SetNormalized(Get3Normalized<T>() + color);
return *this;
}
template<typename T, typename = std::enable_if_t<std::is_floating_point_v<T>>>
RGB565& operator+=(const Vector4<T>& color)
{
SetNormalized(Get4Normalized<T>() + color);
return *this;
}
template<typename T, typename = std::enable_if_t<std::is_floating_point_v<T>>>
RGB565& operator+=(const Vector3_SIMD<T>& color)
{
SetNormalized(Get3NormalizedSIMD<T>() + color);
return *this;
}
template<typename T, typename = std::enable_if_t<std::is_unsigned_v<T> || std::is_signed_v<T>>>
RGB565& operator-=(const Vector3<T>& color)
{
Set(Get3<T>() - color);
return *this;
}
template<typename T, typename = std::enable_if_t<std::is_unsigned_v<T> || std::is_signed_v<T>>>
RGB565& operator-=(const Vector4<T>& color)
{
Set(Get4<T>() - color);
return *this;
}
template<typename T, typename = std::enable_if_t<std::is_unsigned_v<T> || std::is_signed_v<T>>>
RGB565& operator-=(const Vector3_SIMD<T>& color)
{
Set(Get3SIMD<T>() - color);
return *this;
}
template<typename T, typename = std::enable_if_t<std::is_floating_point_v<T>>>
RGB565& operator-=(const Vector3<T>& color)
{
SetNormalized(Get3Normalized<T>() - color);
return *this;
}
template<typename T, typename = std::enable_if_t<std::is_floating_point_v<T>>>
RGB565& operator-=(const Vector4<T>& color)
{
SetNormalized(Get4Normalized<T>() - color);
return *this;
}
template<typename T, typename = std::enable_if_t<std::is_floating_point_v<T>>>
RGB565& operator-=(const Vector3_SIMD<T>& color)
{
SetNormalized(Get3NormalizedSIMD<T>() - color);
return *this;
}
bool operator==(const RGB565& other) const { return value == other.value; }
bool operator!=(const RGB565& other) const { return value != other.value; }
template<typename T, typename = std::enable_if_t<std::is_unsigned_v<T> || std::is_signed_v<T>>>
operator Math::Vector4<T>() { return Get4<T>(); }
template<typename T, typename = std::enable_if_t<std::is_unsigned_v<T> || std::is_signed_v<T>>>
operator Math::Vector3<T>() { return Get3<T>(); }
template<typename T, typename = std::enable_if_t<std::is_unsigned_v<T> || std::is_signed_v<T>>>
operator Math::Vector3_SIMD<T>() { return Get3SIMD<T>(); }
template<typename T, typename = std::enable_if_t<std::is_floating_point_v<T>>>
operator Math::Vector4<T>() { return Get4Normalized<T>(); }
template<typename T, typename = std::enable_if_t<std::is_floating_point_v<T>>>
operator Math::Vector3<T>() { return Get3Normalized<T>(); }
};
static_assert(sizeof(RGB565) == 2);

View 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;
};
}

View File

@@ -7,6 +7,7 @@
#include "DataFormat.hpp"
#include "Base/Logger.hpp"
#include <magic_enum.hpp>
#include "Math/Math.hpp"
namespace OpenVulkano
{
@@ -19,40 +20,203 @@ namespace OpenVulkano
{
uint32_t size = 0;
if (format == DataFormat::R4G4_UNORM_PACK8 || format == DataFormat::S8_UINT) size = 1;
else if (format >= DataFormat::R4G4B4A4_UNORM_PACK16 && format <= DataFormat::A1R5G5B5_UNORM_PACK16) size = 2;
else if (format >= DataFormat::R4G4B4A4_UNORM_PACK16 && format <= DataFormat::A1R5G5B5_UNORM_PACK16)
size = 2;
else if (format >= DataFormat::R8_UNORM && format <= DataFormat::R8_SRGB) size = 1;
else if (format >= DataFormat::R8G8_UNORM && format <= DataFormat::R8G8_SRGB) size = 2;
else if (format >= DataFormat::R8G8B8_UNORM && format <= DataFormat::B8G8R8_SRGB) size = 3;
else if (format >= DataFormat::R8G8B8A8_UNORM && format <= DataFormat::A2B10G10R10_SINT_PACK32) size = 4;
else if (format >= DataFormat::R8G8B8A8_UNORM && format <= DataFormat::A2B10G10R10_SINT_PACK32)
size = 4;
else if (format >= DataFormat::R16_UNORM && format <= DataFormat::R16_SFLOAT) size = 2;
else if (format >= DataFormat::R16G16_UNORM && format <= DataFormat::R16G16_SFLOAT) size = 4;
else if (format >= DataFormat::R16G16B16_UNORM && format <= DataFormat::R16G16B16_SFLOAT) size = 6;
else if (format >= DataFormat::R16G16B16A16_UNORM && format <= DataFormat::R16G16B16A16_SFLOAT) size = 8;
else if (format >= DataFormat::R16G16B16A16_UNORM && format <= DataFormat::R16G16B16A16_SFLOAT)
size = 8;
else if (format >= DataFormat::R32_UINT && format <= DataFormat::R32_SFLOAT) size = 4;
else if (format >= DataFormat::R32G32_UINT && format <= DataFormat::R32G32_SFLOAT) size = 8;
else if (format >= DataFormat::R32G32B32_UINT && format <= DataFormat::R32G32B32_SFLOAT) size = 12;
else if (format >= DataFormat::R32G32B32A32_UINT && format <= DataFormat::R32G32B32A32_SFLOAT) size = 16;
else if (format >= DataFormat::R32G32B32A32_UINT && format <= DataFormat::R32G32B32A32_SFLOAT)
size = 16;
else if (format >= DataFormat::R64_UINT && format <= DataFormat::R64_SFLOAT) size = 8;
else if (format >= DataFormat::R64G64_UINT && format <= DataFormat::R64G64_SFLOAT) size = 16;
else if (format >= DataFormat::R64G64B64_UINT && format <= DataFormat::R64G64B64_SFLOAT) size = 24;
else if (format >= DataFormat::R64G64B64A64_UINT && format <= DataFormat::R64G64B64A64_SFLOAT) size = 32;
else if (format == DataFormat::B10G11R11_UFLOAT_PACK32 || format == DataFormat::E5B9G9R9_UFLOAT_PACK32 ||
format == DataFormat::X8_D24_UNORM_PACK32 || format == DataFormat::D32_SFLOAT || format == DataFormat::D24_UNORM_S8_UINT) size = 4;
else if (format >= DataFormat::R64G64B64A64_UINT && format <= DataFormat::R64G64B64A64_SFLOAT)
size = 32;
else if (format == DataFormat::B10G11R11_UFLOAT_PACK32 || format == DataFormat::E5B9G9R9_UFLOAT_PACK32
|| format == DataFormat::X8_D24_UNORM_PACK32 || format == DataFormat::D32_SFLOAT
|| format == DataFormat::D24_UNORM_S8_UINT)
size = 4;
else if (format == DataFormat::D16_UNORM) size = 2;
else if (format == DataFormat::D16_UNORM_S8_UINT) size = 3;
else if (format == DataFormat::D32_SFLOAT_S8_UINT) size = 5;
else if (format == DataFormat::BC1_RGB_UNORM_BLOCK || format == DataFormat::BC1_RGB_SRGB_BLOCK
|| format == DataFormat::BC1_RGBA_UNORM_BLOCK || format == DataFormat::BC1_RGBA_SRGB_BLOCK
|| format == DataFormat::BC4_SNORM_BLOCK || format == DataFormat::BC4_UNORM_BLOCK)
size = 8;
else if (format == DataFormat::BC2_SRGB_BLOCK || format == DataFormat::BC2_UNORM_BLOCK
|| format == DataFormat::BC3_SRGB_BLOCK || format == DataFormat::BC3_UNORM_BLOCK
|| format == DataFormat::BC5_SNORM_BLOCK || format == DataFormat::BC5_UNORM_BLOCK
|| format == DataFormat::BC6H_SFLOAT_BLOCK || format == DataFormat::BC6H_UFLOAT_BLOCK
|| format == DataFormat::BC7_SRGB_BLOCK || format == DataFormat::BC7_UNORM_BLOCK)
size = 16;
else if (format == DataFormat::ETC2_R8G8B8_UNORM_BLOCK || format == DataFormat::ETC2_R8G8B8_SRGB_BLOCK
|| format == DataFormat::ETC2_R8G8B8A1_UNORM_BLOCK
|| format == DataFormat::ETC2_R8G8B8A1_SRGB_BLOCK
|| format == DataFormat::ETC2_R8G8B8A8_UNORM_BLOCK
|| format == DataFormat::ETC2_R8G8B8A8_SRGB_BLOCK || format == DataFormat::EAC_R11_UNORM_BLOCK
|| format == DataFormat::EAC_R11_SNORM_BLOCK || format == DataFormat::EAC_R11G11_UNORM_BLOCK
|| format == DataFormat::EAC_R11G11_SNORM_BLOCK)
size = 16;
else if (format == DataFormat::ASTC_4x4_UNORM_BLOCK || format == DataFormat::ASTC_4x4_SFLOAT_BLOCK
|| format == DataFormat::ASTC_4x4_SRGB_BLOCK || format == DataFormat::ASTC_5x4_UNORM_BLOCK
|| format == DataFormat::ASTC_5x4_SFLOAT_BLOCK || format == DataFormat::ASTC_5x4_SRGB_BLOCK
|| format == DataFormat::ASTC_5x5_UNORM_BLOCK || format == DataFormat::ASTC_5x5_SFLOAT_BLOCK
|| format == DataFormat::ASTC_5x5_SRGB_BLOCK || format == DataFormat::ASTC_6x5_UNORM_BLOCK
|| format == DataFormat::ASTC_6x5_SFLOAT_BLOCK || format == DataFormat::ASTC_6x5_SRGB_BLOCK
|| format == DataFormat::ASTC_6x6_UNORM_BLOCK || format == DataFormat::ASTC_6x6_SFLOAT_BLOCK
|| format == DataFormat::ASTC_6x6_SRGB_BLOCK || format == DataFormat::ASTC_8x5_UNORM_BLOCK
|| format == DataFormat::ASTC_8x5_SFLOAT_BLOCK || format == DataFormat::ASTC_8x5_SRGB_BLOCK
|| format == DataFormat::ASTC_8x6_UNORM_BLOCK || format == DataFormat::ASTC_8x6_SFLOAT_BLOCK
|| format == DataFormat::ASTC_8x6_SRGB_BLOCK || format == DataFormat::ASTC_8x8_UNORM_BLOCK
|| format == DataFormat::ASTC_8x8_SFLOAT_BLOCK || format == DataFormat::ASTC_8x8_SRGB_BLOCK
|| format == DataFormat::ASTC_10x5_UNORM_BLOCK || format == DataFormat::ASTC_10x5_SFLOAT_BLOCK
|| format == DataFormat::ASTC_10x5_SRGB_BLOCK || format == DataFormat::ASTC_10x6_UNORM_BLOCK
|| format == DataFormat::ASTC_10x6_SFLOAT_BLOCK || format == DataFormat::ASTC_10x6_SRGB_BLOCK
|| format == DataFormat::ASTC_10x8_UNORM_BLOCK || format == DataFormat::ASTC_10x8_SFLOAT_BLOCK
|| format == DataFormat::ASTC_10x8_SRGB_BLOCK || format == DataFormat::ASTC_10x10_UNORM_BLOCK
|| format == DataFormat::ASTC_10x10_SFLOAT_BLOCK || format == DataFormat::ASTC_10x10_SRGB_BLOCK
|| format == DataFormat::ASTC_12x10_UNORM_BLOCK
|| format == DataFormat::ASTC_12x10_SFLOAT_BLOCK || format == DataFormat::ASTC_12x10_SRGB_BLOCK
|| format == DataFormat::ASTC_12x12_UNORM_BLOCK || format == DataFormat::ASTC_12x12_SRGB_BLOCK
|| format == DataFormat::ASTC_12x12_SFLOAT_BLOCK)
size = 16;
else if (format == DataFormat::PVRTC1_2BPP_UNORM_BLOCK_IMG
|| format == DataFormat::PVRTC1_2BPP_SRGB_BLOCK_IMG
|| format == DataFormat::PVRTC1_4BPP_SRGB_BLOCK_IMG
|| format == DataFormat::PVRTC1_4BPP_UNORM_BLOCK_IMG
|| format == DataFormat::PVRTC2_2BPP_SRGB_BLOCK_IMG
|| format == DataFormat::PVRTC2_2BPP_UNORM_BLOCK_IMG
|| format == DataFormat::PVRTC2_4BPP_SRGB_BLOCK_IMG
|| format == DataFormat::PVRTC2_4BPP_UNORM_BLOCK_IMG)
size = 8;
else if (format == DataFormat::B10X6G10X6R10X6G10X6_422_UNORM_4PACK16
|| format == DataFormat::G10X6B10X6G10X6R10X6_422_UNORM_4PACK16
|| format == DataFormat::R10X6G10X6B10X6A10X6_UNORM_4PACK16
|| format == DataFormat::R12X4G12X4B12X4A12X4_UNORM_4PACK16
|| format == DataFormat::G12X4B12X4G12X4R12X4_422_UNORM_4PACK16
|| format == DataFormat::B12X4G12X4R12X4G12X4_422_UNORM_4PACK16
|| format == DataFormat::G16B16G16R16_422_UNORM
|| format == DataFormat::B16G16R16G16_422_UNORM)
size = 8;
else if (format == DataFormat::G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16
|| format == DataFormat::G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16
|| format == DataFormat::G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16
|| format == DataFormat::G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16
|| format == DataFormat::G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16)
size = 6;
map[format] = size;
}
return map;
}
std::unordered_map<DataFormat::Format, Math::Vector2uc> MakeBlockSizeMap()
{
std::unordered_map<DataFormat::Format, Math::Vector2uc> map;
for (auto format: magic_enum::enum_values<DataFormat::Format>())
{
Math::Vector2ui size = { 1, 1 };
if (format == DataFormat::BC1_RGB_UNORM_BLOCK || format == DataFormat::BC1_RGB_SRGB_BLOCK
|| format == DataFormat::BC1_RGBA_UNORM_BLOCK || format == DataFormat::BC1_RGBA_SRGB_BLOCK
|| format == DataFormat::BC2_UNORM_BLOCK || format == DataFormat::BC2_SRGB_BLOCK
|| format == DataFormat::BC3_UNORM_BLOCK || format == DataFormat::BC3_SRGB_BLOCK
|| format == DataFormat::BC4_UNORM_BLOCK || format == DataFormat::BC4_SNORM_BLOCK
|| format == DataFormat::BC5_UNORM_BLOCK || format == DataFormat::BC5_SNORM_BLOCK
|| format == DataFormat::BC6H_UFLOAT_BLOCK || format == DataFormat::BC6H_SFLOAT_BLOCK
|| format == DataFormat::BC7_UNORM_BLOCK || format == DataFormat::BC7_SRGB_BLOCK
|| format == DataFormat::ETC2_R8G8B8_UNORM_BLOCK || format == DataFormat::ETC2_R8G8B8_SRGB_BLOCK
|| format == DataFormat::ETC2_R8G8B8A1_UNORM_BLOCK || format == DataFormat::ETC2_R8G8B8A1_SRGB_BLOCK
|| format == DataFormat::ETC2_R8G8B8A8_UNORM_BLOCK || format == DataFormat::ETC2_R8G8B8A8_SRGB_BLOCK
|| format == DataFormat::EAC_R11_UNORM_BLOCK || format == DataFormat::EAC_R11G11_UNORM_BLOCK
|| format == DataFormat::EAC_R11G11_SNORM_BLOCK || format == DataFormat::ASTC_4x4_UNORM_BLOCK
|| format == DataFormat::ASTC_4x4_SRGB_BLOCK || format == DataFormat::PVRTC1_4BPP_UNORM_BLOCK_IMG
|| format == DataFormat::PVRTC2_4BPP_UNORM_BLOCK_IMG
|| format == DataFormat::PVRTC1_4BPP_SRGB_BLOCK_IMG || format == DataFormat::ASTC_4x4_SFLOAT_BLOCK)
size = { 4, 4 };
else if (format == DataFormat::ASTC_5x4_UNORM_BLOCK || format == DataFormat::ASTC_5x4_SRGB_BLOCK)
size = { 5, 4 };
else if (format == DataFormat::ASTC_5x5_UNORM_BLOCK || format == DataFormat::ASTC_5x5_SRGB_BLOCK)
size = { 5, 5 };
else if (format == DataFormat::ASTC_6x5_UNORM_BLOCK || format == DataFormat::ASTC_6x5_SRGB_BLOCK)
size = { 6, 5 };
else if (format == DataFormat::ASTC_6x6_UNORM_BLOCK || format == DataFormat::ASTC_6x6_SRGB_BLOCK)
size = { 6, 6 };
else if (format == DataFormat::ASTC_8x5_UNORM_BLOCK || format == DataFormat::ASTC_8x5_SRGB_BLOCK)
size = { 8, 5 };
else if (format == DataFormat::ASTC_8x6_UNORM_BLOCK || format == DataFormat::ASTC_8x6_SRGB_BLOCK)
size = { 8, 6 };
else if (format == DataFormat::ASTC_8x8_UNORM_BLOCK || format == DataFormat::ASTC_8x8_SRGB_BLOCK)
size = { 8, 8 };
else if (format == DataFormat::ASTC_10x5_UNORM_BLOCK || format == DataFormat::ASTC_10x5_SRGB_BLOCK)
size = { 10, 5 };
else if (format == DataFormat::ASTC_10x6_UNORM_BLOCK || format == DataFormat::ASTC_10x6_SRGB_BLOCK)
size = { 10, 6 };
else if (format == DataFormat::ASTC_10x8_UNORM_BLOCK || format == DataFormat::ASTC_10x8_SRGB_BLOCK)
size = { 10, 8 };
else if (format == DataFormat::ASTC_10x10_UNORM_BLOCK || format == DataFormat::ASTC_10x10_SRGB_BLOCK)
size = { 10, 10 };
else if (format == DataFormat::ASTC_12x10_UNORM_BLOCK || format == DataFormat::ASTC_12x10_SRGB_BLOCK)
size = { 12, 10 };
else if (format == DataFormat::ASTC_12x12_UNORM_BLOCK || format == DataFormat::ASTC_12x12_SRGB_BLOCK)
size = { 12, 12 };
else if (format == DataFormat::G8B8G8R8_422_UNORM || format == DataFormat::B8G8R8G8_422_UNORM
|| format == DataFormat::G8_B8_R8_3PLANE_422_UNORM
|| format == DataFormat::G8_B8R8_2PLANE_422_UNORM
|| format == DataFormat::G10X6B10X6G10X6R10X6_422_UNORM_4PACK16
|| format == DataFormat::B10X6G10X6R10X6G10X6_422_UNORM_4PACK16
|| format == DataFormat::G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16
|| format == DataFormat::G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16
|| format == DataFormat::G12X4B12X4G12X4R12X4_422_UNORM_4PACK16
|| format == DataFormat::B12X4G12X4R12X4G12X4_422_UNORM_4PACK16
|| format == DataFormat::G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16
|| format == DataFormat::G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16
|| format == DataFormat::G16B16G16R16_422_UNORM || format == DataFormat::B16G16R16G16_422_UNORM
|| format == DataFormat::G16_B16_R16_3PLANE_422_UNORM
|| format == DataFormat::G16_B16R16_2PLANE_422_UNORM)
size = { 2, 1 };
else if (format == DataFormat::G8_B8_R8_3PLANE_420_UNORM
|| format == DataFormat::G8_B8R8_2PLANE_420_UNORM
|| format == DataFormat::G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16
|| format == DataFormat::G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16
|| format == DataFormat::G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16
|| format == DataFormat::G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16
|| format == DataFormat::G16_B16_R16_3PLANE_420_UNORM
|| format == DataFormat::G16_B16R16_2PLANE_420_UNORM)
size = { 2, 2 };
else if (format == DataFormat::G8_B8_R8_3PLANE_444_UNORM
|| format == DataFormat::G8_B8R8_2PLANE_444_UNORM
|| format == DataFormat::G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16
|| format == DataFormat::G10X6_B10X6R10X6_2PLANE_444_UNORM_3PACK16
|| format == DataFormat::G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16
|| format == DataFormat::G12X4_B12X4R12X4_2PLANE_444_UNORM_3PACK16
|| format == DataFormat::G16_B16_R16_3PLANE_444_UNORM
|| format == DataFormat::G16_B16R16_2PLANE_444_UNORM)
size = { 2, 2 };
else if (format == DataFormat::PVRTC2_2BPP_UNORM_BLOCK_IMG
|| format == DataFormat::PVRTC2_2BPP_SRGB_BLOCK_IMG)
size = { 8, 4 };
map[format] = size;
}
return map;
}
const std::unordered_map<DataFormat::Format, uint32_t> FORMAT_SIZE_MAP = MakeFormatSizeMap();
const std::unordered_map<DataFormat::Format, Math::Vector2uc> BLOCK_SIZE_MAP = MakeBlockSizeMap();
}
std::string_view DataFormat::GetName() const
{
return magic_enum::enum_name(m_format);
}
std::string_view DataFormat::GetName() const { return magic_enum::enum_name(m_format); }
DataFormat DataFormat::GetFromName(std::string_view name)
{
@@ -72,10 +236,35 @@ namespace OpenVulkano
return size->second;
}
#ifndef __APPLE__
DataFormat DataFormat::GetFromMetalPixelFormat(int formatId)
bool DataFormat::IsBlockCompressed()
{
return UNDEFINED;
for (auto format: magic_enum::enum_values<DataFormat::Format>())
{
if (format == m_format)
{
return format >= BC1_RGB_UNORM_BLOCK && format <= ASTC_12x12_SRGB_BLOCK
|| format >= ASTC_4x4_SFLOAT_BLOCK && format <= PVRTC2_4BPP_SRGB_BLOCK_IMG;
}
}
}
size_t DataFormat::CalculatedSize(uint32_t& width, uint32_t& height)
{
if (IsBlockCompressed())
{
Math::Vector2uc size = BLOCK_SIZE_MAP.find(m_format)->second;
Math::Vector2uc blockCount = { std::ceil((float) width / size.x), std::ceil((float) height / size.y) };
width = blockCount.x * size.x;
height = blockCount.y * size.y;
return width * height * GetBytesPerPixel();
}
return width * height * GetBytesPerPixel();
}
#ifndef __APPLE__
DataFormat DataFormat::GetFromMetalPixelFormat(int formatId) { return UNDEFINED; }
#endif
}

View File

@@ -373,6 +373,10 @@ namespace OpenVulkano
uint32_t GetBytesPerPixel();
bool IsBlockCompressed();
size_t CalculatedSize(uint32_t& width, uint32_t& height);
static DataFormat GetFromName(std::string_view name);
static DataFormat GetFromMetalPixelFormat(int formatId);

View File

@@ -0,0 +1,319 @@
/*
* 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 "FontAtlasGenerator.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;
FontAtlasGeneratorConfig FontAtlasGeneratorConfig::sdfDefaultConfig = { 42, 1.0, 5 };
FontAtlasGeneratorConfig FontAtlasGeneratorConfig::msdfDefaultConfig = { 32, 1.0, 3 };
template<int Channels>
Charset FontAtlasGenerator<Channels>::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;
}
template<int Channels>
void FontAtlasGenerator<Channels>::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);
}
template<int Channels>
FontAtlasGenerator<Channels>::FontAtlasGenerator()
{
if constexpr (Channels == 1) m_config = FontAtlasGeneratorConfig::sdfDefaultConfig;
else m_config = FontAtlasGeneratorConfig::msdfDefaultConfig;
}
template<int Channels>
void FontAtlasGenerator<Channels>::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);
}
template<int Channels>
void FontAtlasGenerator<Channels>::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);
}
template<int Channels>
void FontAtlasGenerator<Channels>::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);
}
template<int Channels>
void FontAtlasGenerator<Channels>::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)
{
std::filesystem::path fPath(fileName);
fileName = (fPath.parent_path() / fPath.stem()).string() + "_packed.png";
SavePng(fileName);
}
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));
}
template<int Channels>
void FontAtlasGenerator<Channels>::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()));
}
}
template<int Channels>
void FontAtlasGenerator<Channels>::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");
}
}
template<int Channels>
void FontAtlasGenerator<Channels>::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);
if constexpr (Channels == 3)
{
const double maxCornerAngle = 3.0;
for (GlyphGeometry& glyph: glyphsGeometry)
glyph.edgeColoring(&msdfgen::edgeColoringByDistance, maxCornerAngle, 0);
}
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);
Generator generator;
generator.resize(width, height);
GeneratorAttributes attributes;
generator.setAttributes(attributes);
generator.setThreadCount(4);
generator.generate(glyphsGeometry.data(), glyphsGeometry.size());
int idx = 0;
if constexpr (Channels == 3)
{
// store RGB as RGBA
const BitmapConstRef<msdfgen::byte, 3> storage = generator.atlasStorage();
msdfgen::Bitmap<msdfgen::byte, 4> bitmap(width, height);
msdfgen::byte* data = static_cast<msdfgen::byte*>(bitmap);
for (size_t srcPos = 0, dstPos = 0; srcPos < width * height * 3; srcPos += 3, dstPos += 4)
{
data[dstPos] = storage.pixels[srcPos];
data[dstPos + 1] = storage.pixels[srcPos + 1];
data[dstPos + 2] = storage.pixels[srcPos + 2];
data[dstPos + 3] = 255;
}
m_atlasStorage = std::move(bitmap);
}
else
{
m_atlasStorage = generator.atlasStorage();
}
m_atlasTex.resolution = Math::Vector3ui(m_atlasStorage.width(), m_atlasStorage.height(), 1);
m_atlasTex.textureBuffer = (msdfgen::byte*) m_atlasStorage;
m_atlasTex.format = (channelsCount == 1 ? OpenVulkano::DataFormat::R8_UNORM : OpenVulkano::DataFormat::R8G8B8A8_UNORM);
m_atlasTex.size = m_atlasStorage.width() * m_atlasStorage.height() * channelsCount;
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 = 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(pngOutput.value()); }
destroyFont(font);
deinitializeFreetype(ft);
}
template<int Channels>
void FontAtlasGenerator<Channels>::SavePng(const std::string& output) const
{
stbi_flip_vertically_on_write(1);
if (std::filesystem::path(output).extension() == ".png")
{
stbi_write_png(output.c_str(), m_atlasStorage.width(), m_atlasStorage.height(), channelsCount,
m_atlasStorage.operator const msdfgen::byte*(), channelsCount * m_atlasStorage.width());
}
else
{
stbi_write_png((output + ".png").c_str(), m_atlasStorage.width(), m_atlasStorage.height(), channelsCount,
m_atlasStorage.operator const msdfgen::byte*(), channelsCount * m_atlasStorage.width());
}
}
template class FontAtlasGenerator<1>;
template class FontAtlasGenerator<3>;
}
#endif

View File

@@ -0,0 +1,82 @@
/*
* 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 "IFontAtlasGenerator.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 FontAtlasGeneratorConfig
{
static FontAtlasGeneratorConfig sdfDefaultConfig;
static FontAtlasGeneratorConfig msdfDefaultConfig;
int glyphSize;
double miterLimit;
msdfgen::Range pixelRange;
};
template<int Channels>
class FontAtlasGenerator : public IFontAtlasGenerator
{
private:
using SdfGenerator = msdf_atlas::ImmediateAtlasGenerator<float, 1, msdf_atlas::sdfGenerator,
msdf_atlas::BitmapAtlasStorage<msdfgen::byte, 1>>;
using MsdfGenerator = msdf_atlas::ImmediateAtlasGenerator<float, 3, msdf_atlas::msdfGenerator,
msdf_atlas::BitmapAtlasStorage<msdfgen::byte, 3>>;
public:
using Generator = std::conditional<Channels == 1, SdfGenerator, MsdfGenerator>::type;
using AtlasData = std::conditional<Channels == 1, msdfgen::Bitmap<msdfgen::byte, 1>, msdfgen::Bitmap<msdfgen::byte, 4>>::type;
using Config = FontAtlasGeneratorConfig;
static constexpr int channelsCount = (Channels == 1 ? 1 : 4);
static msdf_atlas::Charset LoadAllGlyphs(const std::variant<std::string, Array<char>>& data);
FontAtlasGenerator();
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; }
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 std::string& output) const;
private:
Texture m_atlasTex;
AtlasMetadata m_meta;
Config m_config;
std::map<uint32_t, GlyphInfo> m_symbols;
AtlasData m_atlasStorage;
};
using SdfFontAtlasGenerator = FontAtlasGenerator<1>;
using MsdfFontAtlasGenerator = FontAtlasGenerator<3>;
}
#endif

View File

@@ -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];
}
}
}

View File

@@ -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;

View 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 IFontAtlasGenerator
{
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;
};
}

View File

@@ -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;
@@ -23,7 +23,8 @@ namespace OpenVulkano::Scene
public:
SimpleDrawable(const DrawPhase phase = DrawPhase::MAIN)
: Drawable(DrawEncoder::GetDrawEncoder<SimpleDrawable>(), phase)
{}
{
}
explicit SimpleDrawable(const SimpleDrawable* toCopy)
: Drawable(DrawEncoder::GetDrawEncoder<SimpleDrawable>(), toCopy->GetDrawPhase())

View File

@@ -0,0 +1,268 @@
/*
* 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/IFontAtlasGenerator.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::GetSdfDefaultShader()
{
static bool once = true;
static Shader sdfDefaultShader;
if (once)
{
sdfDefaultShader.AddShaderProgram(OpenVulkano::ShaderProgramType::VERTEX, "Shader/text");
sdfDefaultShader.AddShaderProgram(OpenVulkano::ShaderProgramType::FRAGMENT, "Shader/text");
sdfDefaultShader.AddVertexInputDescription(OpenVulkano::Vertex::GetVertexInputDescription());
sdfDefaultShader.AddDescriptorSetLayoutBinding(Texture::DESCRIPTOR_SET_LAYOUT_BINDING);
sdfDefaultShader.AddDescriptorSetLayoutBinding(UniformBuffer::DESCRIPTOR_SET_LAYOUT_BINDING);
sdfDefaultShader.alphaBlend = true;
sdfDefaultShader.cullMode = CullMode::NONE;
once = false;
}
return sdfDefaultShader;
}
Shader& TextDrawable::GetMsdfDefaultShader()
{
static bool once = true;
static Shader msdfDefaultShader;
if (once)
{
msdfDefaultShader.AddShaderProgram(OpenVulkano::ShaderProgramType::VERTEX, "Shader/text");
msdfDefaultShader.AddShaderProgram(OpenVulkano::ShaderProgramType::FRAGMENT, "Shader/msdfText");
msdfDefaultShader.AddVertexInputDescription(OpenVulkano::Vertex::GetVertexInputDescription());
msdfDefaultShader.AddDescriptorSetLayoutBinding(Texture::DESCRIPTOR_SET_LAYOUT_BINDING);
msdfDefaultShader.AddDescriptorSetLayoutBinding(UniformBuffer::DESCRIPTOR_SET_LAYOUT_BINDING);
msdfDefaultShader.alphaBlend = true;
msdfDefaultShader.cullMode = CullMode::NONE;
once = false;
}
return msdfDefaultShader;
}
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_texture = Texture();
m_material.texture = &m_texture.value();
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();
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(IFontAtlasGenerator* 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(IFontAtlasGenerator* fontAtlasGenerator)
{
if (!fontAtlasGenerator || fontAtlasGenerator->GetGlyphsInfo().empty())
{
Logger::RENDER->error("FontAtlasGenerator is either nullptr or doesn't contain glyphs info");
return;
}
m_fontAtlasGenerator = fontAtlasGenerator;
}
}

View File

@@ -0,0 +1,66 @@
/*
* 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>
#include <optional>
namespace OpenVulkano::Scene
{
class IFontAtlasGenerator;
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& GetSdfDefaultShader();
static Shader& GetMsdfDefaultShader();
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(IFontAtlasGenerator* 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(IFontAtlasGenerator* fontAtlasGenerator);
IFontAtlasGenerator* 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;
std::optional<Texture> m_texture;
IFontAtlasGenerator* m_fontAtlasGenerator = nullptr;
Shader* m_shader = nullptr;
TextConfig m_cfg;
};
}

View File

@@ -40,7 +40,7 @@ void main() {
// Calculate the scaling factors for width and height
float height = realCam.height;
float realScale = realCam.intrinsic[1][1] / height;
float realScale = height / realCam.intrinsic[1][1];
float realAspect = height / realCam.width;
float scaleY = realScale / cam.scaleFactor;
float scaleX = scaleY / (cam.aspect * realAspect);

View File

@@ -0,0 +1,47 @@
#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;
float median(float r, float g, float b) {
return max(min(r, g), min(max(r, g), b));
}
// this parameter should be same as FontAtlasGeneratorConfig::pixelRange
const float pxRange = 3;
float screenPxRange() {
vec2 unitRange = vec2(pxRange)/vec2(textureSize(texSampler, 0));
vec2 screenTexSize = vec2(1.0)/fwidth(texCoord);
return max(0.5*dot(unitRange, screenTexSize), 1.0);
}
void main()
{
vec3 msd = texture(texSampler, texCoord).rgb;
float sd = median(msd.r, msd.g, msd.b);
float screenPxDistance = screenPxRange()*(sd - 0.5);
float opacity = clamp(screenPxDistance + 0.5, 0.0, 1.0);
if (textConfig.backgroundColor.a != 0)
{
outColor = mix(textConfig.backgroundColor, textConfig.textColor, opacity);
}
else
{
outColor = vec4(vec3(textConfig.textColor), opacity);
}
}

View 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);
}
}

View 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;
}

View File

@@ -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;
}

View File

@@ -29,7 +29,7 @@ namespace OpenVulkano::Vulkan
resManager->CopyDataToImage(m_texture->size, m_texture->textureBuffer, this);
texture->updated = false;
m_sampler = resManager->CreateSampler(reinterpret_cast<const vk::SamplerCreateInfo&>(texture->m_samplerConfig));
m_sampler = resManager->CreateSampler(reinterpret_cast<const vk::SamplerCreateInfo&>(*texture->m_samplerConfig));
SetDescriptorSet(resManager, descriptorSetLayout, binding);
texture->renderTexture = this;
@@ -42,7 +42,7 @@ namespace OpenVulkano::Vulkan
texture->updated = false;
texture->textureBuffer = Map();
m_sampler = resManager->CreateSampler(reinterpret_cast<const vk::SamplerCreateInfo&>(texture->m_samplerConfig));
m_sampler = resManager->CreateSampler(reinterpret_cast<const vk::SamplerCreateInfo&>(*texture->m_samplerConfig));
SetDescriptorSet(resManager, descriptorSetLayout, binding);
texture->renderTexture = this;