8 Commits

Author SHA1 Message Date
67d788ae4e Install deps before checkout 2023-05-29 11:09:52 -04:00
4f8927d95c Attempt static build on Alpine 2023-05-29 11:07:42 -04:00
5c697c006f Fix linking diaguids on Windows 2023-05-29 09:55:24 -04:00
f9545db293 Set macOS CMAKE_PREFIX_PATH 2023-05-29 09:30:31 -04:00
cee01a8df1 Actually need to link LLVMWindowsDriver 2023-05-29 09:18:08 -04:00
88b0ed137c atdna: Link clangSupport for LLVM >=15 2023-05-29 09:08:27 -04:00
50991752f8 Use macos-13 2023-05-29 09:00:41 -04:00
cce4b5e2c7 Update to LLVM 15 2023-05-29 08:56:36 -04:00
122 changed files with 6409 additions and 1532 deletions

255
.github/workflows/build.yml vendored Normal file
View File

@@ -0,0 +1,255 @@
name: Build
on:
push:
pull_request:
env:
BUILDCACHE_VERSION: v0.28.3
BUILDCACHE_ACCURACY: STRICT
BUILDCACHE_MAX_CACHE_SIZE: 1073741824 # 1GiB
jobs:
build-linux-x86_64:
name: Build Linux (GCC x86_64)
runs-on: ubuntu-latest
container:
image: alpine:3.17
env:
LLVM_MAJOR: 15
BUILDCACHE_DIR: ${{github.workspace}}/.buildcache
steps:
- name: Install dependencies
run: |
apk add --no-cache git cmake ninja clang-dev clang-static llvm-dev llvm-static musl-dev \
gcc g++ libxml2-dev libxml2-static zlib-dev zlib-static
- uses: actions/checkout@v2
with:
fetch-depth: 0
submodules: recursive
- name: Configure CMake
run: |
cmake -B build . -GNinja \
-DCMAKE_BUILD_TYPE:STRING=RelWithDebInfo \
-DATDNA_DYNAMIC_LLVM:BOOL=OFF \
-DATDNA_STATIC:BOOL=ON \
-DCMAKE_CXX_FLAGS:STRING="-I/usr/lib/llvm15/include -Dstat64=stat"
- name: Build
run: cmake --build build --target package --verbose
- name: Test
working-directory: build
run: ./atdna-test
- name: Upload artifacts
uses: actions/upload-artifact@v2
with:
name: atdna-linux-x86_64
path: |
build/athena-*.tar.gz
build-linux-aarch64:
name: Build Linux (GCC aarch64)
runs-on: ubuntu-latest
if: 'false'
env:
LLVM_MAJOR: 15
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
submodules: recursive
- uses: uraimo/run-on-arch-action@v2.0.9
name: Build & test
with:
arch: aarch64
base_image: --platform=linux/arm64/v8 alpine:3.17
githubToken: ${{github.token}}
dockerRunArgs: |
--volume "${PWD}:/workspace"
install: |
apk add --no-cache git cmake ninja clang-dev clang-static llvm-dev llvm-static musl-dev \
gcc g++ libxml2-dev libxml2-static zlib-dev zlib-static
run: |
cmake -B build . -GNinja \
-DCMAKE_BUILD_TYPE:STRING=RelWithDebInfo \
-DATDNA_DYNAMIC_LLVM:BOOL=OFF \
-DATDNA_STATIC:BOOL=ON \
-DCMAKE_CXX_FLAGS:STRING="-I/usr/lib/llvm15/include -Dstat64=stat"
cmake --build build --target package --verbose
build/atdna-test
- name: Upload artifacts
uses: actions/upload-artifact@v2
with:
name: atdna-linux-aarch64
path: |
build/athena-*.tar.gz
build-macos-universal:
name: Build macOS (AppleClang universal)
runs-on: macos-13
env:
LLVM_MAJOR: 15
LLVM_VERSION: 15.0.7_2
BUILDCACHE_DIR: ${{github.workspace}}/.buildcache
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
submodules: recursive
- name: Install dependencies
run: |
brew update
brew install ninja
# universal clang+llvm from macports
curl -LSfs https://axiodl.com/files/clang-$LLVM_MAJOR-$LLVM_VERSION.mpkg -o /tmp/clang-$LLVM_MAJOR-$LLVM_VERSION.mpkg
sudo installer -pkg /tmp/clang-$LLVM_MAJOR-$LLVM_VERSION.mpkg -target /
# setup buildcache
curl -LSfs https://github.com/mbitsnbites/buildcache/releases/download/$BUILDCACHE_VERSION/buildcache-macos.zip -o /tmp/buildcache-macos.zip
unzip /tmp/buildcache-macos.zip -d "$RUNNER_WORKSPACE"
echo "$RUNNER_WORKSPACE"/buildcache/bin >> $GITHUB_PATH
- name: Restore buildcache
uses: actions/cache@v2
with:
path: ${{env.BUILDCACHE_DIR}}
key: buildcache-macos-12
- name: Configure CMake
run: |
cmake -B build . -GNinja \
-DCMAKE_BUILD_TYPE:STRING=RelWithDebInfo \
-DCMAKE_OSX_ARCHITECTURES:STRING="x86_64;arm64" \
-DCMAKE_PREFIX_PATH:PATH=/opt/local \
-DLLVM_ROOT_DIR:PATH=/opt/local/libexec/llvm-$LLVM_MAJOR \
-DCMAKE_C_COMPILER_LAUNCHER:STRING=buildcache \
-DCMAKE_CXX_COMPILER_LAUNCHER:STRING=buildcache
- name: Build
run: cmake --build build --target package --verbose
- name: Print buildcache stats
run: buildcache -s
- name: Test
working-directory: build
run: ./atdna-test
- name: Upload artifacts
uses: actions/upload-artifact@v2
with:
name: athena-macos-universal
path: |
build/athena-*.tar.gz
build-win32-amd64:
name: Build Windows (MSVC AMD64)
runs-on: windows-2022
env:
LLVM_VERSION: 15.0.7
BUILDCACHE_DIR: C:\buildcache
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
submodules: recursive
- name: Install LLVM
run: |
$TempDir = "C:\temp" # C: has more space
$Filename = "vcpkg-llvm-$env:LLVM_VERSION-full.7z"
New-Item -Path "$TempDir" -ItemType Directory -ea 0
(New-Object Net.WebClient).DownloadFile("https://axiodl.com/files/$Filename", "$TempDir\$Filename")
7z x "-o$TempDir" -aos "$TempDir\$Filename"
- name: Install dependencies
run: |
choco install ninja
# set up buildcache
$TempDir = "$env:RUNNER_WORKSPACE\temp"
New-Item -Path "$TempDir" -ItemType Directory -ea 0
(New-Object Net.WebClient).DownloadFile("https://github.com/mbitsnbites/buildcache/releases/download/$env:BUILDCACHE_VERSION/buildcache-windows.zip", "$TempDir\buildcache.zip")
Expand-Archive -LiteralPath "$TempDir\buildcache.zip" -DestinationPath "$TempDir"
echo "$TempDir\buildcache\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
- name: Restore buildcache
uses: actions/cache@v2
with:
path: ${{env.BUILDCACHE_DIR}}
key: buildcache-windows-2019-msvc-amd64
- name: Enable Visual Studio environment
uses: ilammy/msvc-dev-cmd@v1
- name: Configure CMake
run: |
cmake -B build . -GNinja `
-DCMAKE_BUILD_TYPE:STRING=RelWithDebInfo `
-DCMAKE_MSVC_RUNTIME_LIBRARY:STRING=MultiThreaded `
-DCMAKE_TOOLCHAIN_FILE:PATH="C:\temp\vcpkg-llvm-$env:LLVM_VERSION\scripts\buildsystems\vcpkg.cmake" `
-DVCPKG_TARGET_TRIPLET:STRING=x64-windows-static
- name: Build
run: cmake --build build --target package --verbose
- name: Print buildcache stats
run: buildcache -s
- name: Test
working-directory: build
run: ./atdna-test.exe
- name: Upload artifacts
uses: actions/upload-artifact@v2
with:
name: athena-win32-amd64
path: |
build/athena-*.7z
release:
name: Release
runs-on: ubuntu-20.04
if:
contains('
refs/heads/master
refs/heads/test
', github.ref)
needs:
- build-linux-x86_64
- build-linux-aarch64
- build-macos-universal
- build-win32-amd64
steps:
- name: Download artifacts
uses: actions/download-artifact@v2
with:
path: artifacts
- name: Create release
uses: marvinpinto/action-automatic-releases@latest
with:
repo_token: ${{github.token}}
automatic_release_tag: latest
prerelease: true
title: Development build
files: |
artifacts/*/*

4
.gitmodules vendored
View File

@@ -2,3 +2,7 @@
path = extern/lzokay path = extern/lzokay
url = https://github.com/AxioDL/lzokay.git url = https://github.com/AxioDL/lzokay.git
branch = master branch = master
[submodule "extern/fmt"]
path = extern/fmt
url = https://github.com/fmtlib/fmt
branch = master

View File

@@ -2,6 +2,8 @@ cmake_minimum_required(VERSION 3.10 FATAL_ERROR) # because of c++17
# Set MSVC runtime library flags from CMAKE_MSVC_RUNTIME_LIBRARY # Set MSVC runtime library flags from CMAKE_MSVC_RUNTIME_LIBRARY
cmake_policy(SET CMP0091 NEW) cmake_policy(SET CMP0091 NEW)
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
################## ##################
# Athena Version # # Athena Version #
################## ##################
@@ -67,6 +69,11 @@ endif()
project(athena VERSION ${ATHENA_VERSION} LANGUAGES C CXX) project(athena VERSION ${ATHENA_VERSION} LANGUAGES C CXX)
if (ATDNA_STATIC)
set(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
add_link_options(-static)
endif ()
if (MSVC) if (MSVC)
# Shaddup MSVC # Shaddup MSVC
add_compile_definitions(UNICODE=1 _UNICODE=1 __SSE__=1 add_compile_definitions(UNICODE=1 _UNICODE=1 __SSE__=1
@@ -140,7 +147,7 @@ endif ()
add_subdirectory(extern) add_subdirectory(extern)
add_library(athena-core STATIC add_library(athena-core
src/athena/Utility.cpp src/athena/Utility.cpp
src/athena/MemoryReader.cpp src/athena/MemoryReader.cpp
src/athena/MemoryWriter.cpp src/athena/MemoryWriter.cpp
@@ -156,7 +163,7 @@ add_library(athena-core STATIC
src/LZ77/LZBase.cpp src/LZ77/LZBase.cpp
src/athena/FileInfo.cpp src/athena/FileInfo.cpp
src/athena/Dir.cpp src/athena/Dir.cpp
src/sha1.cpp src/athena/DNAYaml.cpp
include/athena/IStream.hpp include/athena/IStream.hpp
include/athena/IStreamReader.hpp include/athena/IStreamReader.hpp
@@ -179,12 +186,14 @@ add_library(athena-core STATIC
include/LZ77/LZType11.hpp include/LZ77/LZType11.hpp
include/athena/FileInfo.hpp include/athena/FileInfo.hpp
include/athena/Dir.hpp include/athena/Dir.hpp
include/athena/DNA.hpp
include/athena/DNAYaml.hpp
include/athena/DNAOp.hpp
include/athena/YAMLCommon.hpp include/athena/YAMLCommon.hpp
include/athena/YAMLDocReader.hpp include/athena/YAMLDocReader.hpp
include/athena/YAMLDocWriter.hpp include/athena/YAMLDocWriter.hpp
include/athena/yaml.h include/athena/yaml.h
include/athena/utf8proc.h include/athena/utf8proc.h
include/sha1.h
) )
if(WIN32) if(WIN32)
target_sources(athena-core PRIVATE target_sources(athena-core PRIVATE
@@ -223,10 +232,11 @@ target_include_directories(athena-core PUBLIC
) )
target_link_libraries(athena-core PUBLIC target_link_libraries(athena-core PUBLIC
athena-libyaml athena-libyaml
fmt
$<BUILD_INTERFACE:${ZLIB_LIBRARIES}> $<BUILD_INTERFACE:${ZLIB_LIBRARIES}>
) )
add_library(athena-sakura STATIC EXCLUDE_FROM_ALL add_library(athena-sakura EXCLUDE_FROM_ALL
src/athena/Sprite.cpp src/athena/Sprite.cpp
src/athena/SpriteFile.cpp src/athena/SpriteFile.cpp
src/athena/SpriteFileReader.cpp src/athena/SpriteFileReader.cpp
@@ -242,11 +252,8 @@ add_library(athena-sakura STATIC EXCLUDE_FROM_ALL
include/athena/SpriteFrame.hpp include/athena/SpriteFrame.hpp
include/athena/SpritePart.hpp include/athena/SpritePart.hpp
) )
target_include_directories(athena-sakura PUBLIC
include
)
add_library(athena-wiisave STATIC EXCLUDE_FROM_ALL add_library(athena-wiisave EXCLUDE_FROM_ALL
src/athena/WiiBanner.cpp src/athena/WiiBanner.cpp
src/athena/WiiFile.cpp src/athena/WiiFile.cpp
src/athena/WiiImage.cpp src/athena/WiiImage.cpp
@@ -256,6 +263,7 @@ add_library(athena-wiisave STATIC EXCLUDE_FROM_ALL
src/bn.cpp src/bn.cpp
src/ec.cpp src/ec.cpp
src/md5.cpp src/md5.cpp
src/sha1.cpp
src/aes.cpp src/aes.cpp
include/athena/WiiBanner.hpp include/athena/WiiBanner.hpp
@@ -268,16 +276,14 @@ add_library(athena-wiisave STATIC EXCLUDE_FROM_ALL
include/bn.hpp include/bn.hpp
include/ec.hpp include/ec.hpp
include/md5.h include/md5.h
) include/sha1.h
target_include_directories(athena-wiisave PUBLIC
include
) )
if(NOT MSVC AND ${CMAKE_SYSTEM_PROCESSOR} STREQUAL x86_64) if(NOT MSVC AND ${CMAKE_SYSTEM_PROCESSOR} STREQUAL x86_64)
set_source_files_properties(src/aes.cpp PROPERTIES COMPILE_FLAGS -maes) set_source_files_properties(src/aes.cpp PROPERTIES COMPILE_FLAGS -maes)
endif() endif()
add_library(athena-zelda STATIC EXCLUDE_FROM_ALL add_library(athena-zelda EXCLUDE_FROM_ALL
src/athena/ALTTPFile.cpp src/athena/ALTTPFile.cpp
src/athena/ALTTPFileReader.cpp src/athena/ALTTPFileReader.cpp
src/athena/ALTTPFileWriter.cpp src/athena/ALTTPFileWriter.cpp
@@ -311,9 +317,7 @@ add_library(athena-zelda STATIC EXCLUDE_FROM_ALL
include/athena/ZQuestFileReader.hpp include/athena/ZQuestFileReader.hpp
include/athena/ZQuestFileWriter.hpp include/athena/ZQuestFileWriter.hpp
) )
target_include_directories(athena-zelda PUBLIC
include
)
# Icon # Icon
set(ATHENA_ICO ${CMAKE_CURRENT_SOURCE_DIR}/Athena.ico) set(ATHENA_ICO ${CMAKE_CURRENT_SOURCE_DIR}/Athena.ico)
@@ -334,9 +338,12 @@ endforeach()
# Define installs # Define installs
install(DIRECTORY include/athena DESTINATION ${INSTALL_INCLUDE_DIR} COMPONENT athena) install(DIRECTORY include/athena DESTINATION ${INSTALL_INCLUDE_DIR} COMPONENT athena)
install(DIRECTORY extern/fmt/include/fmt DESTINATION ${INSTALL_INCLUDE_DIR} COMPONENT athena)
if (ATHENA_ZLIB) if (ATHENA_ZLIB)
set(ZLIB_INSTALL ${ZLIB_LIBRARIES}) set(ZLIB_INSTALL ${ZLIB_LIBRARIES})
endif () endif ()
install(TARGETS athena-core fmt ${ZLIB_INSTALL}
DESTINATION ${INSTALL_LIB_DIR} EXPORT AthenaTargets COMPONENT athena)
if(WIN32 AND NOT CYGWIN) if(WIN32 AND NOT CYGWIN)
install(FILES Athena.ico DESTINATION ${INSTALL_LIB_DIR} COMPONENT athena) install(FILES Athena.ico DESTINATION ${INSTALL_LIB_DIR} COMPONENT athena)
elseif(UNIX) elseif(UNIX)
@@ -350,6 +357,9 @@ endif()
# Package Export # # Package Export #
################## ##################
# Add all targets to the build-tree export set
export(TARGETS athena-core athena-libyaml fmt ${ZLIB_LIBRARIES} FILE "${CMAKE_CURRENT_BINARY_DIR}/AthenaTargets.cmake")
# Export the package for use from the build-tree # Export the package for use from the build-tree
# (this registers the build-tree with a global CMake-registry) # (this registers the build-tree with a global CMake-registry)
export(PACKAGE athena) export(PACKAGE athena)
@@ -377,6 +387,23 @@ install(FILES
# Install the export set for use with the install-tree # Install the export set for use with the install-tree
install(EXPORT AthenaTargets DESTINATION ${INSTALL_CMAKE_DIR} COMPONENT athena) install(EXPORT AthenaTargets DESTINATION ${INSTALL_CMAKE_DIR} COMPONENT athena)
################
# atdna import #
################
add_subdirectory(atdna)
if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
# Test target
add_executable(atdna-test atdna/test.cpp atdna/test.hpp)
if (CMAKE_SYSTEM_NAME STREQUAL "Switch")
set_target_properties(atdna-test PROPERTIES SUFFIX ".elf")
target_link_libraries(atdna-test athena-core nx)
else()
target_link_libraries(atdna-test athena-core)
endif()
target_atdna(atdna-test atdna_test.cpp atdna/test.hpp)
endif()
######### #########
# CPack # # CPack #
######### #########

190
atdna/CMakeLists.txt Normal file
View File

@@ -0,0 +1,190 @@
###############
# ATDNA Build #
###############
if(NOT TARGET atdna AND NOT CMAKE_CROSSCOMPILING)
get_directory_property(ATDNA_DEFINES COMPILE_DEFINITIONS)
list(REMOVE_ITEM ATDNA_DEFINES _GLIBCXX_DEBUG=1)
set_directory_properties(PROPERTIES COMPILE_DEFINITIONS "${ATDNA_DEFINES}")
# Find dependencies
if (NOT "${LLVM_ROOT_DIR}" STREQUAL "")
# use existing LLVM_ROOT_DIR
elseif (APPLE AND CMAKE_SYSTEM_PROCESSOR STREQUAL x86_64)
set(LLVM_ROOT_DIR /usr/local/opt/llvm)
elseif (APPLE AND CMAKE_SYSTEM_PROCESSOR STREQUAL arm64)
set(LLVM_ROOT_DIR /opt/homebrew/opt/llvm)
elseif (WIN32)
get_filename_component(LLVM_ROOT_DIR [HKEY_LOCAL_MACHINE\\Software\\LLVM\\LLVM] ABSOLUTE)
else ()
set(LLVM_ROOT_DIR "")
endif ()
find_package(Clang REQUIRED PATHS ${LLVM_ROOT_DIR})
find_package(LLVM REQUIRED PATHS ${CLANG_INSTALL_PREFIX})
if(LLVM_FOUND)
if(${CMAKE_SYSTEM_NAME} STREQUAL "Linux")
option(ATDNA_DYNAMIC_LLVM "Use dynamic library targets when linking LLVM" ON)
else()
option(ATDNA_DYNAMIC_LLVM "Use dynamic library targets when linking LLVM" OFF)
endif()
set(CLANG_LIBS "")
set(LLVM_LIBS "")
if (ATDNA_DYNAMIC_LLVM)
list(APPEND CLANG_LIBS clang-cpp)
list(APPEND LLVM_LIBS LLVM)
else()
function(recursive_remove_library target library)
get_target_property(target_dependencies ${target} INTERFACE_LINK_LIBRARIES)
foreach(dep ${target_dependencies})
if (NOT "${dep}" STREQUAL "${library}" AND TARGET "${dep}")
recursive_remove_library(${dep} ${library})
endif()
endforeach()
list(FIND target_dependencies "${library}" list_index)
if (${list_index} GREATER -1)
list(REMOVE_AT target_dependencies ${list_index})
set_property(TARGET ${target} PROPERTY INTERFACE_LINK_LIBRARIES "${target_dependencies}")
endif()
endfunction()
# Add LLVM static libs
list(APPEND CLANG_LIBS clangTooling)
list(APPEND LLVM_LIBS LLVMFrontendOpenMP LLVMOption)
if (LLVM_VERSION_MAJOR GREATER_EQUAL 15)
list(APPEND LLVM_LIBS LLVMWindowsDriver)
endif ()
# Remove LLVM dynamic library from Clang dependencies
foreach (lib ${CLANG_LIBS})
recursive_remove_library(${lib} LLVM)
endforeach ()
# Hack around link order issues
target_link_libraries(clangAST INTERFACE LLVMFrontendOpenMP)
# Fix linking diaguids on Windows
if (WIN32 AND TARGET LLVMDebugInfoPDB)
find_package(DiaSDK REQUIRED)
get_target_property(target_dependencies LLVMDebugInfoPDB INTERFACE_LINK_LIBRARIES)
list(TRANSFORM target_dependencies REPLACE ".*diaguids.*" "${DIASDK_GUIDS_LIBRARY}")
set_property(TARGET LLVMDebugInfoPDB PROPERTY INTERFACE_LINK_LIBRARIES "${target_dependencies}")
endif ()
# Allow static linking against zstd
if (ATDNA_STATIC)
get_target_property(target_dependencies LLVMSupport INTERFACE_LINK_LIBRARIES)
list(TRANSFORM target_dependencies REPLACE "zstd::libzstd_shared" "zstd::libzstd_static")
set_property(TARGET LLVMSupport PROPERTY INTERFACE_LINK_LIBRARIES "${target_dependencies}")
endif ()
endif()
# Offer the user the choice of overriding the installation directories
set(INSTALL_INCLUDE_DIR include CACHE PATH "Installation directory for header files")
set(INSTALL_BIN_DIR bin CACHE PATH "Installation directory for executables")
set(INSTALL_CMAKE_DIR lib/cmake/atdna)
# Make relative paths absolute (needed later on)
foreach(p BIN INCLUDE CMAKE)
set(var INSTALL_${p}_DIR)
if(NOT IS_ABSOLUTE "${${var}}")
set(ABS_${var} "${CMAKE_INSTALL_PREFIX}/${${var}}")
else()
set(ABS_${var} "${${var}}")
endif()
endforeach()
# Windows resource
if(WIN32)
configure_file(main.rc.in main.rc @ONLY)
set(PLAT_SRCS ${CMAKE_CURRENT_BINARY_DIR}/main.rc)
endif()
# ATDNA target
add_executable(atdna main.cpp test.hpp ${PLAT_SRCS})
target_link_libraries(atdna ${CLANG_LIBS} ${LLVM_LIBS})
if (APPLE)
set(ATDNA_ARGV0 clang-tool)
else ()
set(ATDNA_ARGV0 "${LLVM_TOOLS_BINARY_DIR}/clang-tool")
endif ()
target_compile_definitions(atdna PRIVATE
INSTALL_PREFIX=${ABS_INSTALL_BIN_DIR}
__STDC_LIMIT_MACROS=1
__STDC_CONSTANT_MACROS=1
ATDNA_ARGV0=${ATDNA_ARGV0})
target_include_directories(atdna PRIVATE ${CLANG_INCLUDE_DIRS})
# Clang 10.0.x headers currently broken with C++20
set_property(TARGET atdna PROPERTY CXX_STANDARD 17)
if(MSVC)
if (VCPKG_TOOLCHAIN)
# Assumes static build of LLVM
if ("${CMAKE_BUILD_TYPE}" STREQUAL "Debug")
set_property(TARGET atdna PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreadedDebug")
else ()
set_property(TARGET atdna PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded")
endif ()
else ()
# Allow linking against release-built LLVM libraries
target_compile_options(atdna PRIVATE /GR- /D_ITERATOR_DEBUG_LEVEL=0)
set_property(TARGET atdna PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreadedDLL")
endif ()
else ()
target_compile_options(atdna PRIVATE -fno-rtti -fvisibility=hidden -Wno-error)
if (METAFORCE_ASAN AND CMAKE_SYSTEM_NAME STREQUAL "Linux")
# On Linux, we need to compile without ASAN; explicitly disable it here
target_compile_options(atdna PRIVATE -stdlib=libstdc++ -fno-sanitize=address)
target_link_options(atdna PRIVATE -stdlib=libstdc++ -fno-sanitize=address)
endif ()
endif()
# Define installs
install(TARGETS atdna DESTINATION ${INSTALL_BIN_DIR} EXPORT atdnaTargets COMPONENT atdna)
install(DIRECTORY ${LLVM_INCLUDE_DIR}/clang DESTINATION ${INSTALL_INCLUDE_DIR}/athena COMPONENT atdna)
##################
# Package Export #
##################
# Add all targets to the build-tree export set
export(TARGETS atdna FILE "${CMAKE_CURRENT_BINARY_DIR}/atdnaTargets.cmake")
# Export the package for use from the build-tree
# (this registers the build-tree with a global CMake-registry)
export(PACKAGE atdna)
# Create the atdnaConfig.cmake
# ... for the build tree
configure_file(atdnaConfig.cmake.in "${CMAKE_CURRENT_BINARY_DIR}/atdnaConfig.cmake" @ONLY)
# ... for the install tree
configure_file(atdnaConfig.cmake.in "${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/atdnaConfig.cmake" @ONLY)
# ... for both
configure_file(atdnaConfigVersion.cmake.in "${CMAKE_CURRENT_BINARY_DIR}/atdnaConfigVersion.cmake" @ONLY)
# Install atdnaConfig.cmake
install(FILES
"${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/atdnaConfig.cmake"
"${CMAKE_CURRENT_BINARY_DIR}/atdnaConfigVersion.cmake"
DESTINATION ${INSTALL_CMAKE_DIR} COMPONENT atdna)
# Install the export set for use with the install-tree
install(EXPORT atdnaTargets DESTINATION ${INSTALL_CMAKE_DIR} COMPONENT atdna)
#########
# CTest #
#########
if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
enable_testing()
add_test(NAME test-dna COMMAND $<TARGET_FILE:atdna> -o test.cpp
"-I${ATHENA_INCLUDE_DIR}" ${CMAKE_SOURCE_DIR}/test.hpp)
endif()
endif()
endif()
include(atdnaHelpers.cmake)

3
atdna/README.md Normal file
View File

@@ -0,0 +1,3 @@
# atdna
[User Overview](http://libAthena.github.io/doc/atdna.html)
[DNA Record Reference](http://libAthena.github.io/doc/atdna-ref.html)

View File

@@ -0,0 +1,88 @@
# - Config file for the atdna package
# Compute paths
get_filename_component(ATDNA_CMAKE_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH)
# Our library dependencies (contains definitions for IMPORTED targets)
if(NOT TARGET atdna AND NOT atdna_BINARY_DIR)
include("${ATDNA_CMAKE_DIR}/atdnaTargets.cmake")
endif()
# Super handy macro for adding atdna target
function(atdna out)
# Ninja wants invocations in root binary dir for DEPFILE application
file(RELATIVE_PATH out_rel ${CMAKE_BINARY_DIR} "${CMAKE_CURRENT_BINARY_DIR}/${out}")
# Make input files source-relative
set(ins "")
set(ins_impdeps "")
foreach(arg ${ARGN})
list(APPEND ins ${CMAKE_CURRENT_SOURCE_DIR}/${arg})
list(APPEND ins_impdeps CXX)
list(APPEND ins_impdeps ${CMAKE_CURRENT_SOURCE_DIR}/${arg})
endforeach()
# Get local include directories for atdna
get_property(incdirs DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY INCLUDE_DIRECTORIES)
set(inccli "")
foreach(dir ${incdirs})
if (NOT dir MATCHES ".*emscripten.*")
list(APPEND inccli "-I${dir}")
endif()
endforeach()
# Get local defines for atdna
get_property(cdefs DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY COMPILE_DEFINITIONS)
set(cdefcli "")
foreach(def ${cdefs})
list(APPEND cdefcli "-D${def}")
endforeach()
# MS extra
unset(extraargs)
if(MSVC)
list(APPEND extraargs -fms-compatibility -fexceptions)
if(MSVC_VERSION EQUAL 1800)
list(APPEND extraargs -fms-compatibility-version=18.00)
elseif(MSVC_VERSION EQUAL 1900)
list(APPEND extraargs -fms-compatibility-version=19.00)
elseif(MSVC_VERSION EQUAL 1910)
list(APPEND extraargs -fms-compatibility-version=19.10)
elseif(MSVC_VERSION EQUAL 1911)
list(APPEND extraargs -fms-compatibility-version=19.11)
endif()
# OSX Extra
elseif(APPLE)
get_filename_component(COMPILER_DIR "${CMAKE_CXX_COMPILER}" DIRECTORY)
if (NOT EXISTS "${CMAKE_OSX_SYSROOT}")
message(FATAL_ERROR "CMAKE_OSX_SYSROOT not set")
endif()
file(GLOB SYSTEM_INCLUDE_DIR "${COMPILER_DIR}/../lib/clang/*/include")
list(APPEND extraargs
-isysroot ${CMAKE_OSX_SYSROOT}
-stdlib++-isystem "${COMPILER_DIR}/../include/c++/v1"
-isystem "${SYSTEM_INCLUDE_DIR}")
endif()
# Make target
if(${CMAKE_GENERATOR} STREQUAL "Ninja")
# Use Ninja's DEPFILE parser in cooperation with atdna
add_custom_command(OUTPUT ${out} COMMAND $<TARGET_FILE:atdna>
ARGS ${extraargs} -o ${out_rel} -MD -MT ${out_rel} -MF ${out_rel}.d ${cdefcli} ${inccli}
"-I${ATHENA_INCLUDE_DIR}" ${ins}
DEPENDS atdna ${ins} IMPLICIT_DEPENDS ${ins_impdeps}
DEPFILE "${CMAKE_CURRENT_BINARY_DIR}/${out}.d"
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
COMMENT "Generating DNA ${out_rel}")
else()
# Use CMake's built-in dependency scanner for makefile targets
add_custom_command(OUTPUT ${out} COMMAND $<TARGET_FILE:atdna>
ARGS ${extraargs} -o ${out_rel} ${cdefcli} ${inccli}
"-I${ATHENA_INCLUDE_DIR}" ${ins}
DEPENDS atdna ${ins} IMPLICIT_DEPENDS ${ins_impdeps}
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
COMMENT "Generating DNA ${out_rel}")
endif()
endfunction()

View File

@@ -0,0 +1,12 @@
set(PACKAGE_VERSION "@ATHENA_VERSION_STRING@")
# Check whether the requested PACKAGE_FIND_VERSION is compatible
if("${PACKAGE_VERSION}" VERSION_LESS "${PACKAGE_FIND_VERSION}")
set(PACKAGE_VERSION_COMPATIBLE FALSE)
else()
set(PACKAGE_VERSION_COMPATIBLE TRUE)
if ("${PACKAGE_VERSION}" VERSION_EQUAL "${PACKAGE_FIND_VERSION}")
set(PACKAGE_VERSION_EXACT TRUE)
endif()
endif()

164
atdna/atdnaHelpers.cmake Normal file
View File

@@ -0,0 +1,164 @@
#
# gather_include_directories recursively builds a list of include directories
# across all dependencies.
#
if (CMAKE_VERSION VERSION_GREATER_EQUAL "3.20")
# Don't transform add_custom_command DEPFILE for Ninja
cmake_policy(SET CMP0116 OLD)
endif ()
function(_atdna_gather_include_directories_impl target_name)
get_target_property(target_dependencies ${target_name} INTERFACE_LINK_LIBRARIES)
foreach(dep ${target_dependencies})
if(TARGET ${dep})
get_target_property(dep_includes ${dep} INTERFACE_INCLUDE_DIRECTORIES)
if(dep_includes)
list(APPEND target_includes ${dep_includes})
endif()
_atdna_gather_include_directories_impl(${dep})
endif()
endforeach()
set(target_includes ${target_includes} PARENT_SCOPE)
endfunction()
function(atdna_gather_include_directories var target_name)
unset(target_includes)
get_directory_property(dir_includes INCLUDE_DIRECTORIES)
if(dir_includes)
list(APPEND target_includes ${dir_includes})
endif()
get_target_property(target_includes1 ${target_name} INCLUDE_DIRECTORIES)
if(target_includes1)
list(APPEND target_includes ${target_includes1})
endif()
get_target_property(target_includes2 ${target_name} INTERFACE_INCLUDE_DIRECTORIES)
if(target_includes2)
list(APPEND target_includes ${target_includes2})
endif()
_atdna_gather_include_directories_impl(${target_name})
list(REMOVE_DUPLICATES target_includes)
set(${var} ${target_includes} PARENT_SCOPE)
endfunction()
function(_atdna_gather_compile_definitions_impl target_name)
get_target_property(target_dependencies ${target_name} INTERFACE_LINK_LIBRARIES)
foreach(dep ${target_dependencies})
if(TARGET ${dep})
get_target_property(dep_defines ${dep} INTERFACE_COMPILE_DEFINITIONS)
if(dep_defines)
list(APPEND target_defines ${dep_defines})
endif()
_atdna_gather_compile_definitions_impl(${dep})
endif()
endforeach()
set(target_defines ${target_defines} PARENT_SCOPE)
endfunction()
function(atdna_gather_compile_definitions var target_name)
unset(target_defines)
get_directory_property(dir_defines COMPILE_DEFINITIONS)
if(dir_defines)
list(APPEND target_defines ${dir_defines})
endif()
get_target_property(target_defines1 ${target_name} COMPILE_DEFINITIONS)
if(target_defines1)
list(APPEND target_defines ${target_defines1})
endif()
get_target_property(target_defines2 ${target_name} INTERFACE_COMPILE_DEFINITIONS)
if(target_defines2)
list(APPEND target_defines ${target_defines2})
endif()
_atdna_gather_compile_definitions_impl(${target_name})
list(REMOVE_DUPLICATES target_defines)
set(${var} ${target_defines} PARENT_SCOPE)
endfunction()
#######################
# In-tree atdna macro #
#######################
# Super handy macro for adding atdna target
function(atdna out incdirs cdefs)
# Ninja wants invocations in root binary dir for DEPFILE application
file(RELATIVE_PATH out_rel ${CMAKE_BINARY_DIR} "${CMAKE_CURRENT_BINARY_DIR}/${out}")
# Make input files source-relative
unset(ins)
unset(ins_impdeps)
foreach(arg ${ARGN})
list(APPEND ins ${CMAKE_CURRENT_SOURCE_DIR}/${arg})
list(APPEND ins_impdeps CXX)
list(APPEND ins_impdeps ${CMAKE_CURRENT_SOURCE_DIR}/${arg})
endforeach()
set(inccli "")
foreach(dir ${incdirs})
if (NOT dir MATCHES ".*emscripten.*")
list(APPEND inccli "-I${dir}")
endif()
endforeach()
set(cdefcli "")
foreach(def ${cdefs})
list(APPEND cdefcli "-D${def}")
endforeach()
# MS extra
unset(extraargs)
if(MSVC)
list(APPEND extraargs -fms-compatibility -fexceptions)
if(MSVC_VERSION EQUAL 1800)
list(APPEND extraargs -fms-compatibility-version=18.00)
elseif(MSVC_VERSION EQUAL 1900)
list(APPEND extraargs -fms-compatibility-version=19.00)
elseif(MSVC_VERSION EQUAL 1910)
list(APPEND extraargs -fms-compatibility-version=19.10)
elseif(MSVC_VERSION EQUAL 1911)
list(APPEND extraargs -fms-compatibility-version=19.11)
endif()
# OSX Extra
elseif(APPLE)
get_filename_component(COMPILER_DIR "${CMAKE_CXX_COMPILER}" DIRECTORY)
if (NOT EXISTS "${CMAKE_OSX_SYSROOT}")
message(FATAL_ERROR "CMAKE_OSX_SYSROOT not set")
endif()
file(GLOB SYSTEM_INCLUDE_DIR "${COMPILER_DIR}/../lib/clang/*/include")
list(APPEND extraargs
-isysroot ${CMAKE_OSX_SYSROOT}
-stdlib++-isystem "${COMPILER_DIR}/../include/c++/v1"
-isystem "${SYSTEM_INCLUDE_DIR}")
endif()
# Make target
if(${CMAKE_GENERATOR} STREQUAL "Ninja")
# Use Ninja's DEPFILE parser in cooperation with atdna
add_custom_command(OUTPUT ${out} COMMAND $<TARGET_FILE:atdna>
ARGS ${extraargs} -o ${out_rel} -MD -MT ${out_rel} -MF ${out_rel}.d
${inccli} ${cdefcli}
"-I${athena_SOURCE_DIR}/include" ${ins}
DEPENDS atdna ${ins} IMPLICIT_DEPENDS ${ins_impdeps}
DEPFILE "${CMAKE_CURRENT_BINARY_DIR}/${out}.d"
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
COMMENT "Generating DNA ${out_rel}"
COMMAND_EXPAND_LISTS)
else()
# Use CMake's built-in dependency scanner for makefile targets
add_custom_command(OUTPUT ${out} COMMAND $<TARGET_FILE:atdna>
ARGS ${extraargs} -o ${out_rel}
${inccli} ${cdefcli}
"-I${athena_SOURCE_DIR}/include" ${ins}
DEPENDS atdna ${ins} IMPLICIT_DEPENDS ${ins_impdeps}
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
COMMENT "Generating DNA ${out_rel}"
COMMAND_EXPAND_LISTS)
endif()
endfunction()
function(target_atdna target out)
atdna_gather_include_directories(include_list ${target})
atdna_gather_compile_definitions(define_list ${target})
atdna(${out} "${include_list}" "${define_list}" ${ARGN})
target_sources(${target} PRIVATE ${out} ${ARGN})
endfunction()

1354
atdna/main.cpp Normal file

File diff suppressed because it is too large Load Diff

32
atdna/main.rc.in Normal file
View File

@@ -0,0 +1,32 @@
#include "winver.h"
IDI_ICON1 ICON DISCARDABLE "@ATHENA_ICO@"
VS_VERSION_INFO VERSIONINFO
FILEVERSION @ATHENA_MAJOR_VERSION@,@ATHENA_MINOR_VERSION@,@ATHENA_PATCH_VERSION@,0
PRODUCTVERSION @ATHENA_MAJOR_VERSION@,@ATHENA_MINOR_VERSION@,@ATHENA_PATCH_VERSION@,0
FILEFLAGS 0x0L
FILEFLAGSMASK 0x3fL
FILEOS 0x00040004L
FILETYPE 0x1L
FILESUBTYPE 0x0L
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "000004b0"
BEGIN
VALUE "CompanyName", "Jackoalan / Antidote"
VALUE "FileDescription", "ATDNA"
VALUE "FileVersion", "@ATHENA_VERSION@"
VALUE "LegalCopyright", "Copyright (C) 2016 Jackoalan / Antidote"
VALUE "InternalName", "atdna"
VALUE "OriginalFilename", "atdna.exe"
VALUE "ProductName", "ATDNA"
VALUE "ProductVersion", "@ATHENA_VERSION@"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x0, 1200
END
END

28
atdna/test.cpp Normal file
View File

@@ -0,0 +1,28 @@
#include "test.hpp"
#include <athena/MemoryWriter.hpp>
#include <fmt/format.h>
#define EXPECTED_BYTES 281
int main(int argc, const char** argv) {
TESTFile<atUint32, 2> file = {};
file.arrCount[0] = 2;
file.array.push_back(42);
file.array.push_back(64);
size_t binSize = 0;
file.binarySize(binSize);
athena::io::MemoryCopyWriter w(nullptr, binSize);
atInt64 pos = w.position();
file.write(w);
const bool pass = !w.hasError() && w.position() - pos == binSize && binSize == EXPECTED_BYTES;
if (pass) {
fmt::print(FMT_STRING("[PASS] {} bytes written\n"), size_t(w.position() - pos));
} else {
fmt::print(FMT_STRING("[FAIL] {} bytes written; {} bytes sized; {} bytes expected\n"), size_t(w.position() - pos), binSize,
EXPECTED_BYTES);
}
return pass ? 0 : 1;
}

73
atdna/test.hpp Normal file
View File

@@ -0,0 +1,73 @@
#include <athena/DNAYaml.hpp>
using namespace athena;
typedef io::DNA<Endian::Big> BigDNA;
enum ETest : atUint8 { ZERO, ONE, TWO, THREE };
template <ETest EVal>
struct AT_SPECIALIZE_PARMS(ETest::ZERO, ETest::ONE, ETest::TWO, ETest::THREE) TESTSubFile : public BigDNA {
AT_DECL_DNA
Value<ETest> varE = EVal;
Value<atUint32> sub1;
Value<atUint32> sub2;
};
struct TESTSubClassFile : public TESTSubFile<ETest::ONE> {
AT_DECL_DNA
Value<atUint32> sub3;
Value<atUint16> sub4;
};
struct TESTSubSubClassFile : public TESTSubClassFile {
AT_DECL_DNA
Value<atUint32> sub5;
Value<atUint32> sub6;
};
template <class Var32Tp, int Var32Val>
struct AT_SPECIALIZE_PARMS(atUint16, 42, atUint32, 87, atUint32, 2) TESTFile : public BigDNA {
AT_DECL_DNA
Value<bool> varBool;
AT_OVERRIDE_RCRC32(12345678) Value<Var32Tp> x4_var32 = Var32Val;
AT_OVERRIDE_RCRC32(deadbabe) Value<atUint16> x8_var16;
Value<atVec3f> vec3;
Value<atVec4f> vec4;
struct TESTNestedSubFile : public BigDNA {
AT_DECL_DNA
Value<atUint32> nestSub1;
Value<atUint32> nestSub2;
} nestedSubFile;
using TESTSubFileUsing = TESTSubFile<ETest::TWO>;
TESTSubFileUsing subFile;
Align<4> align;
template <class NestedTp, int NestedVal>
struct AT_SPECIALIZE_PARMS(atInt32, 36, atInt64, 96) TESTTemplateSubFile : public BigDNA {
AT_DECL_DNA
Value<NestedTp> explSub1 = NestedVal;
Value<Var32Tp> explSub2 = Var32Val;
};
Value<TESTTemplateSubFile<atInt32, 36>> nestedTemplate1;
Value<TESTTemplateSubFile<atInt64, 96>> nestedTemplate2;
Value<atUint32, Endian::Little> arrCount[2];
Vector<atUint32, AT_DNA_COUNT(arrCount[0])> array;
Value<atUint32> arrAltCount;
Vector<atUint32, AT_DNA_COUNT(arrAltCount)> arrayAlt;
Seek<21, SeekOrigin::Current> seek;
Value<atUint32> arrCount2;
Vector<TESTSubFile<ETest::ZERO>, AT_DNA_COUNT(arrCount[1] + arrCount2)> array2;
Value<atUint32> bufSz;
Buffer<AT_DNA_COUNT(bufSz)> buf;
String<32> str;
WString<64> wstr;
};

51
cmake/FindDiaSDK.cmake Normal file
View File

@@ -0,0 +1,51 @@
# From https://github.com/microsoft/DirectXShaderCompiler/blob/18c9e114f9c314f93e68fbc72ce207d4ed2e65ae/cmake/modules/FindDiaSDK.cmake
# This file is distributed under the University of Illinois Open Source
# Find the DIA SDK path.
# It will typically look something like this:
# C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\DIA SDK\include
# CMAKE_GENERATOR_INSTANCE has the location of Visual Studio used
# i.e. C:/Program Files (x86)/Microsoft Visual Studio/2019/Community
set(VS_PATH ${CMAKE_GENERATOR_INSTANCE})
get_filename_component(VS_DIA_INC_PATH "${VS_PATH}/DIA SDK/include" ABSOLUTE CACHE)
# Starting in VS 15.2, vswhere is included.
# Unclear what the right component to search for is, might be Microsoft.VisualStudio.Component.VC.DiagnosticTools
# (although the friendly name of that is C++ profiling tools). The toolset is the most likely target.
set(PROGRAMFILES_X86 "ProgramFiles(x86)")
execute_process(
COMMAND "$ENV{${PROGRAMFILES_X86}}/Microsoft Visual Studio/Installer/vswhere.exe" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
OUTPUT_VARIABLE VSWHERE_LATEST
ERROR_QUIET
OUTPUT_STRIP_TRAILING_WHITESPACE
)
find_path(DIASDK_INCLUDE_DIR # Set variable DIASDK_INCLUDE_DIR
dia2.h # Find a path with dia2.h
HINTS "${VS_DIA_INC_PATH}"
HINTS "${VSWHERE_LATEST}/DIA SDK/include"
DOC "path to DIA SDK header files"
)
if ((CMAKE_GENERATOR_PLATFORM STREQUAL "x64") OR ("${CMAKE_C_COMPILER_ARCHITECTURE_ID}" STREQUAL "x64"))
find_library(DIASDK_GUIDS_LIBRARY NAMES diaguids.lib HINTS ${DIASDK_INCLUDE_DIR}/../lib/amd64 )
elseif ((CMAKE_GENERATOR_PLATFORM STREQUAL "ARM") OR ("${CMAKE_C_COMPILER_ARCHITECTURE_ID}" STREQUAL "ARM"))
find_library(DIASDK_GUIDS_LIBRARY NAMES diaguids.lib HINTS ${DIASDK_INCLUDE_DIR}/../lib/arm )
elseif ((CMAKE_GENERATOR_PLATFORM MATCHES "ARM64.*") OR ("${CMAKE_C_COMPILER_ARCHITECTURE_ID}" MATCHES "ARM64.*"))
find_library(DIASDK_GUIDS_LIBRARY NAMES diaguids.lib HINTS ${DIASDK_INCLUDE_DIR}/../lib/arm64 )
else ((CMAKE_GENERATOR_PLATFORM STREQUAL "x64") OR ("${CMAKE_C_COMPILER_ARCHITECTURE_ID}" STREQUAL "x64"))
find_library(DIASDK_GUIDS_LIBRARY NAMES diaguids.lib HINTS ${DIASDK_INCLUDE_DIR}/../lib )
endif((CMAKE_GENERATOR_PLATFORM STREQUAL "x64") OR ("${CMAKE_C_COMPILER_ARCHITECTURE_ID}" STREQUAL "x64"))
set(DIASDK_LIBRARIES ${DIASDK_GUIDS_LIBRARY})
set(DIASDK_INCLUDE_DIRS ${DIASDK_INCLUDE_DIR})
include(FindPackageHandleStandardArgs)
# handle the QUIETLY and REQUIRED arguments and set DIASDK_FOUND to TRUE
# if all listed variables are TRUE
find_package_handle_standard_args(DiaSDK DEFAULT_MSG
DIASDK_LIBRARIES DIASDK_INCLUDE_DIR)
mark_as_advanced(DIASDK_INCLUDE_DIRS DIASDK_LIBRARIES)

16
extern/CMakeLists.txt vendored
View File

@@ -1,8 +1,14 @@
if (EXISTS ${CMAKE_SOURCE_DIR}/extern/lzokay) add_subdirectory(lzokay)
add_subdirectory(lzokay) if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU") target_compile_options(lzokay PRIVATE -Wno-maybe-uninitialized)
target_compile_options(lzokay PRIVATE -Wno-maybe-uninitialized)
endif ()
endif () endif ()
add_subdirectory(zlib) add_subdirectory(zlib)
add_subdirectory(yaml) add_subdirectory(yaml)
if(NOT TARGET fmt)
add_subdirectory(fmt)
target_compile_definitions(fmt PUBLIC
FMT_ARM_ABI_COMPATIBILITY=1
FMT_EXCEPTIONS=0)
target_compile_definitions(fmt INTERFACE
FMT_ENFORCE_COMPILE_STRING=1)
endif()

1
extern/fmt vendored Submodule

Submodule extern/fmt added at 9e8b86fd2d

2
extern/lzokay vendored

View File

@@ -4,31 +4,31 @@
class LZBase { class LZBase {
public: public:
explicit LZBase(int32_t minimumOffset = 1, int32_t slidingWindow = 4096, int32_t minimumMatch = 3, explicit LZBase(atInt32 minimumOffset = 1, atInt32 slidingWindow = 4096, atInt32 minimumMatch = 3,
int32_t blockSize = 8); atInt32 blockSize = 8);
virtual ~LZBase(); virtual ~LZBase();
virtual uint32_t compress(const uint8_t* src, uint8_t** dest, uint32_t srcLength) = 0; virtual atUint32 compress(const atUint8* src, atUint8** dest, atUint32 srcLength) = 0;
virtual uint32_t decompress(const uint8_t* src, uint8_t** dest, uint32_t srcLength) = 0; virtual atUint32 decompress(const atUint8* src, atUint8** dest, atUint32 srcLength) = 0;
void setSlidingWindow(int32_t SlidingWindow); void setSlidingWindow(atInt32 SlidingWindow);
int32_t slidingWindow() const; atInt32 slidingWindow() const;
void setReadAheadBuffer(int32_t ReadAheadBuffer); void setReadAheadBuffer(atInt32 ReadAheadBuffer);
int32_t readAheadBuffer() const; atInt32 readAheadBuffer() const;
void setMinMatch(int32_t minimumMatch); void setMinMatch(atInt32 minimumMatch);
int32_t minMatch() const; atInt32 minMatch() const;
void setBlockSize(int32_t BlockSize); void setBlockSize(atInt32 BlockSize);
int32_t blockSize() const; atInt32 blockSize() const;
void setMinimumOffset(uint32_t minimumOffset); void setMinimumOffset(atUint32 minimumOffset);
uint32_t minimumOffset() const; atUint32 minimumOffset() const;
protected: protected:
LZLengthOffset search(const uint8_t* posPtr, const uint8_t* dataBegin, const uint8_t* dataEnd) const; LZLengthOffset search(const atUint8* posPtr, const atUint8* dataBegin, const atUint8* dataEnd) const;
int32_t m_slidingWindow; atInt32 m_slidingWindow;
int32_t m_readAheadBuffer; atInt32 m_readAheadBuffer;
int32_t m_minMatch; // Minimum number of bytes that have to matched to go through with compression atInt32 m_minMatch; // Minimum number of bytes that have to matched to go through with compression
int32_t m_blockSize; atInt32 m_blockSize;
uint32_t m_minOffset; atUint32 m_minOffset;
LZLookupTable m_lookupTable; LZLookupTable m_lookupTable;
}; };

View File

@@ -6,8 +6,8 @@
#include <athena/Types.hpp> #include <athena/Types.hpp>
struct LZLengthOffset { struct LZLengthOffset {
uint32_t length; // The number of bytes compressed atUint32 length; // The number of bytes compressed
uint16_t offset; // How far back in sliding window where bytes that match the lookAheadBuffer is located atUint16 offset; // How far back in sliding window where bytes that match the lookAheadBuffer is located
bool operator==(const LZLengthOffset& lo_pair) const { return length == lo_pair.length && offset == lo_pair.offset; } bool operator==(const LZLengthOffset& lo_pair) const { return length == lo_pair.length && offset == lo_pair.offset; }
bool operator!=(const LZLengthOffset& lo_pair) const { return !operator==(lo_pair); } bool operator!=(const LZLengthOffset& lo_pair) const { return !operator==(lo_pair); }
}; };
@@ -15,16 +15,16 @@ struct LZLengthOffset {
class LZLookupTable { class LZLookupTable {
public: public:
LZLookupTable(); LZLookupTable();
explicit LZLookupTable(int32_t minimumMatch, int32_t slidingWindow = 4096, int32_t lookAheadWindow = 18); explicit LZLookupTable(atInt32 minimumMatch, atInt32 slidingWindow = 4096, atInt32 lookAheadWindow = 18);
~LZLookupTable(); ~LZLookupTable();
LZLengthOffset search(const uint8_t* curPos, const uint8_t* dataBegin, const uint8_t* dataEnd); LZLengthOffset search(const atUint8* curPos, const atUint8* dataBegin, const atUint8* dataEnd);
void setLookAheadWindow(int32_t lookAheadWindow); void setLookAheadWindow(atInt32 lookAheadWindow);
private: private:
using LookupTable = std::multimap<std::vector<uint8_t>, int32_t>; using LookupTable = std::multimap<std::vector<uint8_t>, int32_t>;
LookupTable table; LookupTable table;
int32_t m_minimumMatch = 3; atInt32 m_minimumMatch = 3;
int32_t m_slidingWindow = 4096; atInt32 m_slidingWindow = 4096;
int32_t m_lookAheadWindow = 18; atInt32 m_lookAheadWindow = 18;
std::vector<uint8_t> m_buffer; std::vector<uint8_t> m_buffer;
}; };

View File

@@ -4,8 +4,8 @@
class LZType10 : public LZBase { class LZType10 : public LZBase {
public: public:
explicit LZType10(int32_t minimumOffset = 1, int32_t SlidingWindow = 4096, int32_t MinimumMatch = 3, explicit LZType10(atInt32 minimumOffset = 1, atInt32 SlidingWindow = 4096, atInt32 MinimumMatch = 3,
int32_t BlockSize = 8); atInt32 BlockSize = 8);
uint32_t compress(const uint8_t* src, uint8_t** dstBuf, uint32_t srcLength) override; atUint32 compress(const atUint8* src, atUint8** dstBuf, atUint32 srcLength) override;
uint32_t decompress(const uint8_t* src, uint8_t** dst, uint32_t srcLen) override; atUint32 decompress(const atUint8* src, atUint8** dst, atUint32 srcLen) override;
}; };

View File

@@ -4,8 +4,8 @@
class LZType11 : public LZBase { class LZType11 : public LZBase {
public: public:
explicit LZType11(int32_t MinimumOffset = 1, int32_t SlidingWindow = 4096, int32_t MinimumMatch = 3, explicit LZType11(atInt32 MinimumOffset = 1, atInt32 SlidingWindow = 4096, atInt32 MinimumMatch = 3,
int32_t BlockSize = 8); atInt32 BlockSize = 8);
uint32_t compress(const uint8_t* src, uint8_t** dst, uint32_t srcLength) override; atUint32 compress(const atUint8* src, atUint8** dst, atUint32 srcLength) override;
uint32_t decompress(const uint8_t* src, uint8_t** dst, uint32_t srcLength) override; atUint32 decompress(const atUint8* src, atUint8** dst, atUint32 srcLength) override;
}; };

View File

@@ -40,7 +40,7 @@ public:
* \param val The new quest to assign to the given index * \param val The new quest to assign to the given index
* \throw InvalidOperationException on index out of range * \throw InvalidOperationException on index out of range
*/ */
void setQuest(uint32_t id, ALTTPQuest* val); void setQuest(atUint32 id, ALTTPQuest* val);
/*! \brief Returns the primary quest list /*! \brief Returns the primary quest list
* *
* \return The primary quest list * \return The primary quest list
@@ -54,13 +54,13 @@ public:
* \return ALTTPQuest* * \return ALTTPQuest*
* \throw InvalidOperationException on index out of range * \throw InvalidOperationException on index out of range
*/ */
ALTTPQuest* quest(uint32_t id) const; ALTTPQuest* quest(atUint32 id) const;
/*! \brief Returns the number of primary quests /*! \brief Returns the number of primary quests
* *
* \return The number of quests * \return The number of quests
*/ */
uint32_t questCount() const; atUint32 questCount() const;
private: private:
std::vector<ALTTPQuest*> m_quests; std::vector<ALTTPQuest*> m_quests;

View File

@@ -23,7 +23,7 @@ public:
* \param data The existing buffer * \param data The existing buffer
* \param length The length of the existing buffer * \param length The length of the existing buffer
*/ */
ALTTPFileReader(uint8_t*, uint64_t); ALTTPFileReader(atUint8*, atUint64);
/*! \brief This constructor creates an instance from a file on disk. /*! \brief This constructor creates an instance from a file on disk.
* *

View File

@@ -22,7 +22,7 @@ public:
* \param data The existing buffer * \param data The existing buffer
* \param length The length of the existing buffer * \param length The length of the existing buffer
*/ */
ALTTPFileWriter(uint8_t*, uint64_t); ALTTPFileWriter(atUint8*, atUint64);
/*! \brief This constructor creates an instance from a file on disk. /*! \brief This constructor creates an instance from a file on disk.
* *
@@ -40,7 +40,7 @@ private:
void writeRoomFlags(ALTTPRoomFlags*); void writeRoomFlags(ALTTPRoomFlags*);
void writeOverworldEvent(ALTTPOverworldEvent*); void writeOverworldEvent(ALTTPOverworldEvent*);
void writeDungeonItems(ALTTPDungeonItemFlags); void writeDungeonItems(ALTTPDungeonItemFlags);
uint16_t calculateChecksum(uint32_t game); atUint16 calculateChecksum(atUint32 game);
}; };
} // namespace io } // namespace io

View File

@@ -33,7 +33,7 @@ public:
* \param rf * \param rf
* \param id * \param id
*/ */
void setRoomFlags(ALTTPRoomFlags* rf, uint32_t id); void setRoomFlags(ALTTPRoomFlags* rf, atUint32 id);
/*! /*!
* \brief roomFlags * \brief roomFlags
@@ -46,7 +46,7 @@ public:
* \param id * \param id
* \return * \return
*/ */
ALTTPRoomFlags* roomFlags(uint32_t id); ALTTPRoomFlags* roomFlags(atUint32 id);
/*! /*!
* \brief setOverworldEvents * \brief setOverworldEvents
@@ -59,7 +59,7 @@ public:
* \param ow * \param ow
* \param id * \param id
*/ */
void setOverworldEvents(ALTTPOverworldEvent* ow, uint32_t id); void setOverworldEvents(ALTTPOverworldEvent* ow, atUint32 id);
/*! /*!
* \brief overworldEvents * \brief overworldEvents
@@ -72,7 +72,7 @@ public:
* \param id * \param id
* \return * \return
*/ */
ALTTPOverworldEvent* overworldEvent(uint32_t id) const; ALTTPOverworldEvent* overworldEvent(atUint32 id) const;
/*! /*!
* \brief setInventory * \brief setInventory
@@ -90,25 +90,25 @@ public:
* \brief setRupeeMax * \brief setRupeeMax
* \param val * \param val
*/ */
void setRupeeMax(uint16_t val); void setRupeeMax(atUint16 val);
/*! /*!
* \brief rupeeMax * \brief rupeeMax
* \return * \return
*/ */
uint16_t rupeeMax() const; atUint16 rupeeMax() const;
/*! /*!
* \brief setRupeeCurrent * \brief setRupeeCurrent
* \param val * \param val
*/ */
void setRupeeCurrent(uint16_t val); void setRupeeCurrent(atUint16 val);
/*! /*!
* \brief rupeeCurrent * \brief rupeeCurrent
* \return * \return
*/ */
uint16_t rupeeCurrent() const; atUint16 rupeeCurrent() const;
/*! /*!
* \brief setCompasses * \brief setCompasses
@@ -150,109 +150,109 @@ public:
* \brief setWishingPond * \brief setWishingPond
* \param val * \param val
*/ */
void setWishingPond(uint16_t val); void setWishingPond(atUint16 val);
/*! /*!
* \brief wishingPond * \brief wishingPond
* \return * \return
*/ */
uint16_t wishingPond() const; atUint16 wishingPond() const;
/*! /*!
* \brief setHealthMax * \brief setHealthMax
* \param val * \param val
*/ */
void setHealthMax(uint8_t val); void setHealthMax(atUint8 val);
/*! /*!
* \brief healthMax * \brief healthMax
* \return * \return
*/ */
uint8_t healthMax() const; atUint8 healthMax() const;
/*! /*!
* \brief setHealth * \brief setHealth
* \param val * \param val
*/ */
void setHealth(uint8_t val); void setHealth(atUint8 val);
/*! /*!
* \brief health * \brief health
* \return * \return
*/ */
uint8_t health() const; atUint8 health() const;
/*! /*!
* \brief setMagicPower * \brief setMagicPower
* \param val * \param val
*/ */
void setMagicPower(uint8_t val); void setMagicPower(atUint8 val);
/*! /*!
* \brief magicPower * \brief magicPower
* \return * \return
*/ */
uint8_t magicPower() const; atUint8 magicPower() const;
/*! /*!
* \brief setKeys * \brief setKeys
* \param val * \param val
*/ */
void setKeys(uint8_t val); void setKeys(atUint8 val);
/*! /*!
* \brief keys * \brief keys
* \return * \return
*/ */
uint8_t keys() const; atUint8 keys() const;
/*! /*!
* \brief setBombUpgrades * \brief setBombUpgrades
* \param val * \param val
*/ */
void setBombUpgrades(uint8_t val); void setBombUpgrades(atUint8 val);
/*! /*!
* \brief bombUpgrades * \brief bombUpgrades
* \return * \return
*/ */
uint8_t bombUpgrades() const; atUint8 bombUpgrades() const;
/*! /*!
* \brief setArrowUpgrades * \brief setArrowUpgrades
* \param val * \param val
*/ */
void setArrowUpgrades(uint8_t val); void setArrowUpgrades(atUint8 val);
/*! /*!
* \brief arrowUpgrades * \brief arrowUpgrades
* \return * \return
*/ */
uint8_t arrowUpgrades() const; atUint8 arrowUpgrades() const;
/*! /*!
* \brief setHealthFiller * \brief setHealthFiller
* \param val * \param val
*/ */
void setHealthFiller(uint8_t val); void setHealthFiller(atUint8 val);
/*! /*!
* \brief healthFiller * \brief healthFiller
* \return * \return
*/ */
uint8_t healthFiller() const; atUint8 healthFiller() const;
/*! /*!
* \brief setMagicFiller * \brief setMagicFiller
* \param val * \param val
*/ */
void setMagicFiller(uint8_t val); void setMagicFiller(atUint8 val);
/*! /*!
* \brief magicFiller * \brief magicFiller
* \return * \return
*/ */
uint8_t magicFiller() const; atUint8 magicFiller() const;
/*! /*!
* \brief setPendants * \brief setPendants
@@ -270,37 +270,37 @@ public:
* \brief setBombFiller * \brief setBombFiller
* \param val * \param val
*/ */
void setBombFiller(uint8_t val); void setBombFiller(atUint8 val);
/*! /*!
* \brief bombFiller * \brief bombFiller
* \return * \return
*/ */
uint8_t bombFiller() const; atUint8 bombFiller() const;
/*! /*!
* \brief setArrowFiller * \brief setArrowFiller
* \param val * \param val
*/ */
void setArrowFiller(uint8_t val); void setArrowFiller(atUint8 val);
/*! /*!
* \brief arrowFiller * \brief arrowFiller
* \return * \return
*/ */
uint8_t arrowFiller() const; atUint8 arrowFiller() const;
/*! /*!
* \brief setArrows * \brief setArrows
* \param val * \param val
*/ */
void setArrows(uint8_t val); void setArrows(atUint8 val);
/*! /*!
* \brief arrows * \brief arrows
* \return * \return
*/ */
uint8_t arrows() const; atUint8 arrows() const;
/*! /*!
* \brief setAbilityFlags * \brief setAbilityFlags
@@ -342,27 +342,27 @@ public:
* \brief setDungeonKeys * \brief setDungeonKeys
* \param val * \param val
*/ */
void setDungeonKeys(std::vector<uint8_t> val); void setDungeonKeys(std::vector<atUint8> val);
/*! /*!
* \brief setDungeonKeys * \brief setDungeonKeys
* \param id * \param id
* \param val * \param val
*/ */
void setDungeonKeys(uint32_t id, uint8_t val); void setDungeonKeys(atUint32 id, atUint8 val);
/*! /*!
* \brief dungeonKeys * \brief dungeonKeys
* \param id * \param id
* \return * \return
*/ */
uint8_t dungeonKeys(uint32_t id) const; atUint8 dungeonKeys(atUint32 id) const;
/*! /*!
* \brief dungeonCount * \brief dungeonCount
* \return * \return
*/ */
uint32_t dungeonCount() const; atUint32 dungeonCount() const;
/*! /*!
* \brief setProgressIndicator * \brief setProgressIndicator
@@ -452,71 +452,71 @@ public:
* \brief setOldManFlags * \brief setOldManFlags
* \param flags * \param flags
*/ */
void setOldManFlags(std::vector<uint8_t> flags); void setOldManFlags(std::vector<atUint8> flags);
/*! /*!
* \brief setOldManFlag * \brief setOldManFlag
* \param id * \param id
* \param val * \param val
*/ */
void setOldManFlag(uint32_t id, uint8_t val); void setOldManFlag(atUint32 id, atUint8 val);
/*! /*!
* \brief oldManFlag * \brief oldManFlag
* \param id * \param id
* \return * \return
*/ */
uint8_t oldManFlag(uint32_t id); atUint8 oldManFlag(atUint32 id);
/*! /*!
* \brief oldManFlagCount * \brief oldManFlagCount
* \return * \return
*/ */
uint32_t oldManFlagCount() const; atUint32 oldManFlagCount() const;
/*! /*!
* \brief setBombFlag * \brief setBombFlag
* \param flag * \param flag
*/ */
void setBombFlag(uint8_t flag); void setBombFlag(atUint8 flag);
/*! /*!
* \brief bombFlag * \brief bombFlag
* \return * \return
*/ */
uint8_t bombFlag() const; atUint8 bombFlag() const;
/*! /*!
* \brief setUnknown1 * \brief setUnknown1
* \param flags * \param flags
*/ */
void setUnknown1(std::vector<uint8_t> flags); void setUnknown1(std::vector<atUint8> flags);
/*! /*!
* \brief setUnknown1 * \brief setUnknown1
* \param id * \param id
* \param val * \param val
*/ */
void setUnknown1(uint32_t id, uint8_t val); void setUnknown1(atUint32 id, atUint8 val);
/*! /*!
* \brief unknown1 * \brief unknown1
* \param id * \param id
* \return * \return
*/ */
uint8_t unknown1(uint32_t id); atUint8 unknown1(atUint32 id);
/*! /*!
* \brief unknown1Count * \brief unknown1Count
* \return * \return
*/ */
uint32_t unknown1Count() const; atUint32 unknown1Count() const;
/*! /*!
* \brief setPlayerName * \brief setPlayerName
* \param playerName * \param playerName
*/ */
void setPlayerName(std::vector<uint16_t> playerName); void setPlayerName(std::vector<atUint16> playerName);
/*! /*!
* \brief setPlayerName * \brief setPlayerName
* \param playerName * \param playerName
@@ -526,7 +526,7 @@ public:
* \brief playerName * \brief playerName
* \return * \return
*/ */
std::vector<uint16_t> playerName() const; std::vector<atUint16> playerName() const;
/*! /*!
* \brief playerNameToString * \brief playerNameToString
* \return * \return
@@ -549,102 +549,102 @@ public:
* \brief setDungeonDeathTotals * \brief setDungeonDeathTotals
* \param val * \param val
*/ */
void setDungeonDeathTotals(std::vector<uint16_t> val); void setDungeonDeathTotals(std::vector<atUint16> val);
/*! /*!
* \brief setDungeonDeathTotal * \brief setDungeonDeathTotal
* \param id * \param id
* \param val * \param val
*/ */
void setDungeonDeathTotal(uint32_t id, uint16_t val); void setDungeonDeathTotal(atUint32 id, atUint16 val);
/*! /*!
* \brief dungeonDeathTotal * \brief dungeonDeathTotal
* \param id * \param id
* \return * \return
*/ */
uint16_t dungeonDeathTotal(uint32_t id) const; atUint16 dungeonDeathTotal(atUint32 id) const;
/*! /*!
* \brief dungeonDeathTotalCount * \brief dungeonDeathTotalCount
* \return * \return
*/ */
uint16_t dungeonDeathTotalCount() const; atUint16 dungeonDeathTotalCount() const;
/*! /*!
* \brief setUnknown2 * \brief setUnknown2
* \param val * \param val
*/ */
void setUnknown2(uint16_t val); void setUnknown2(atUint16 val);
/*! /*!
* \brief unknown2 * \brief unknown2
* \return * \return
*/ */
uint16_t unknown2() const; atUint16 unknown2() const;
/*! /*!
* \brief setDeathSaveCount * \brief setDeathSaveCount
* \param val * \param val
*/ */
void setDeathSaveCount(uint16_t val); void setDeathSaveCount(atUint16 val);
/*! /*!
* \brief deathSaveCount * \brief deathSaveCount
* \return * \return
*/ */
uint16_t deathSaveCount() const; atUint16 deathSaveCount() const;
/*! /*!
* \brief setPostGameDeathCounter * \brief setPostGameDeathCounter
* \param val * \param val
*/ */
void setPostGameDeathCounter(int16_t val); void setPostGameDeathCounter(atInt16 val);
/*! /*!
* \brief postGameDeathCounter * \brief postGameDeathCounter
* \return * \return
*/ */
int16_t postGameDeathCounter() const; atInt16 postGameDeathCounter() const;
/*! /*!
* \brief setChecksum * \brief setChecksum
* \param checksum * \param checksum
*/ */
void setChecksum(uint16_t checksum); void setChecksum(atUint16 checksum);
/*! /*!
* \brief checksum * \brief checksum
* \return * \return
*/ */
uint16_t checksum() const; atUint16 checksum() const;
private: private:
std::vector<ALTTPRoomFlags*> m_roomFlags; std::vector<ALTTPRoomFlags*> m_roomFlags;
std::vector<ALTTPOverworldEvent*> m_overworldEvents; std::vector<ALTTPOverworldEvent*> m_overworldEvents;
ALTTPInventory m_inventory; ALTTPInventory m_inventory;
uint16_t m_rupeeMax; atUint16 m_rupeeMax;
uint16_t m_rupeeCurrent; atUint16 m_rupeeCurrent;
ALTTPDungeonItemFlags m_compasses; ALTTPDungeonItemFlags m_compasses;
ALTTPDungeonItemFlags m_bigKeys; ALTTPDungeonItemFlags m_bigKeys;
ALTTPDungeonItemFlags m_dungeonMaps; ALTTPDungeonItemFlags m_dungeonMaps;
uint16_t m_wishingPond; atUint16 m_wishingPond;
uint8_t m_healthMax; atUint8 m_healthMax;
uint8_t m_health; atUint8 m_health;
uint8_t m_magicPower; atUint8 m_magicPower;
uint8_t m_keys; atUint8 m_keys;
uint8_t m_bombUpgrades; atUint8 m_bombUpgrades;
uint8_t m_arrowUpgrades; atUint8 m_arrowUpgrades;
uint8_t m_heartFiller; atUint8 m_heartFiller;
uint8_t m_magicFiller; atUint8 m_magicFiller;
ALTTPPendants m_pendants; ALTTPPendants m_pendants;
uint8_t m_bombFiller; atUint8 m_bombFiller;
uint8_t m_arrowFiller; atUint8 m_arrowFiller;
uint8_t m_arrows; atUint8 m_arrows;
ALTTPAbilities m_abilityFlags; ALTTPAbilities m_abilityFlags;
ALTTPCrystals m_crystals; ALTTPCrystals m_crystals;
ALTTPMagicUsage m_magicUsage; ALTTPMagicUsage m_magicUsage;
std::vector<uint8_t> m_dungeonKeys; std::vector<atUint8> m_dungeonKeys;
ALTTPProgressIndicator m_progressIndicator; ALTTPProgressIndicator m_progressIndicator;
ALTTPProgressFlags1 m_progressFlags1; ALTTPProgressFlags1 m_progressFlags1;
ALTTPMapIcon m_mapIcon; ALTTPMapIcon m_mapIcon;
@@ -652,16 +652,16 @@ private:
ALTTPProgressFlags2 m_progressFlags2; ALTTPProgressFlags2 m_progressFlags2;
ALTTPLightDarkWorldIndicator m_lightDarkWorldIndicator; ALTTPLightDarkWorldIndicator m_lightDarkWorldIndicator;
ALTTPTagAlong m_tagAlong; ALTTPTagAlong m_tagAlong;
std::vector<uint8_t> m_oldManFlags; std::vector<atUint8> m_oldManFlags;
uint8_t m_bombFlag; atUint8 m_bombFlag;
std::vector<uint8_t> m_unknown1; std::vector<atUint8> m_unknown1;
std::vector<uint16_t> m_playerName; std::vector<atUint16> m_playerName;
bool m_valid; bool m_valid;
std::vector<uint16_t> m_dungeonDeathTotals; std::vector<atUint16> m_dungeonDeathTotals;
uint16_t m_unknown2; atUint16 m_unknown2;
uint16_t m_deathSaveCount; atUint16 m_deathSaveCount;
int16_t m_postGameDeathCounter; atInt16 m_postGameDeathCounter;
uint16_t m_checksum; atUint16 m_checksum;
}; };
} // namespace athena } // namespace athena

View File

@@ -92,7 +92,7 @@ struct ALTTPDungeonItemFlags {
bool IcePalace : 1; bool IcePalace : 1;
bool SkullWoods : 1; bool SkullWoods : 1;
}; };
uint8_t flags1; atUint8 flags1;
}; };
union { union {
@@ -106,7 +106,7 @@ struct ALTTPDungeonItemFlags {
bool HyruleCastle : 1; // unused exist in original game bool HyruleCastle : 1; // unused exist in original game
bool SewerPassage : 1; // unused exist in original game bool SewerPassage : 1; // unused exist in original game
}; };
uint8_t flags2; atUint8 flags2;
}; };
}; };

View File

@@ -3,9 +3,9 @@
#include "athena/Types.hpp" #include "athena/Types.hpp"
namespace athena::checksums { namespace athena::checksums {
uint64_t crc64(const uint8_t* data, uint64_t length, uint64_t seed = 0xFFFFFFFFFFFFFFFF, atUint64 crc64(const atUint8* data, atUint64 length, atUint64 seed = 0xFFFFFFFFFFFFFFFF,
uint64_t final = 0xFFFFFFFFFFFFFFFF); atUint64 final = 0xFFFFFFFFFFFFFFFF);
uint32_t crc32(const uint8_t* data, uint64_t length, uint32_t seed = 0xFFFFFFFF, uint32_t final = 0xFFFFFFFF); atUint32 crc32(const atUint8* data, atUint64 length, atUint32 seed = 0xFFFFFFFF, atUint32 final = 0xFFFFFFFF);
uint16_t crc16CCITT(const uint8_t* data, uint64_t length, uint16_t seed = 0xFFFF, uint16_t final = 0); atUint16 crc16CCITT(const atUint8* data, atUint64 length, atUint16 seed = 0xFFFF, atUint16 final = 0);
uint16_t crc16(const uint8_t* data, uint64_t length, uint16_t seed = 0, uint16_t final = 0); atUint16 crc16(const atUint8* data, atUint64 length, atUint16 seed = 0, atUint16 final = 0);
} // namespace athena::checksums } // namespace athena::checksums

View File

@@ -4,8 +4,8 @@
namespace athena::io::Compression { namespace athena::io::Compression {
// Zlib compression // Zlib compression
int32_t decompressZlib(const uint8_t* src, uint32_t srcLen, uint8_t* dst, uint32_t dstLen); atInt32 decompressZlib(const atUint8* src, atUint32 srcLen, atUint8* dst, atUint32 dstLen);
int32_t compressZlib(const uint8_t* src, uint32_t srcLen, uint8_t* dst, uint32_t dstLen); atInt32 compressZlib(const atUint8* src, atUint32 srcLen, atUint8* dst, atUint32 dstLen);
#if AT_LZOKAY #if AT_LZOKAY
// lzo compression // lzo compression
@@ -13,9 +13,9 @@ atInt32 decompressLZO(const atUint8* source, atInt32 sourceSize, atUint8* dst, a
#endif #endif
// Yaz0 encoding // Yaz0 encoding
uint32_t yaz0Decode(const uint8_t* src, uint8_t* dst, uint32_t uncompressedSize); atUint32 yaz0Decode(const atUint8* src, atUint8* dst, atUint32 uncompressedSize);
uint32_t yaz0Encode(const uint8_t* src, uint32_t srcSize, uint8_t* data); atUint32 yaz0Encode(const atUint8* src, atUint32 srcSize, atUint8* data);
uint32_t decompressLZ77(const uint8_t* src, uint32_t srcLen, uint8_t** dst); atUint32 decompressLZ77(const atUint8* src, atUint32 srcLen, atUint8** dst);
uint32_t compressLZ77(const uint8_t* src, uint32_t srcLen, uint8_t** dst, bool extended = false); atUint32 compressLZ77(const atUint8* src, atUint32 srcLen, atUint8** dst, bool extended = false);
} // namespace athena::io::Compression } // namespace athena::io::Compression

152
include/athena/DNA.hpp Normal file
View File

@@ -0,0 +1,152 @@
#pragma once
/* BIG FAT WARNING!!!
*
* The type-structure of this file is expected to remain consistent for 'atdna'
* Any changes to the types or namespacing must be reflected in 'atdna/main.cpp'
*/
#include <memory>
#include <string>
#include <vector>
#include <sys/types.h>
#include "athena/DNAOp.hpp"
#include "athena/Global.hpp"
#include "athena/IStreamReader.hpp"
#include "athena/IStreamWriter.hpp"
using namespace std::literals;
namespace athena::io {
/**
* @brief Base DNA class used against 'atdna'
* @tparam DNAE Default-endianness for contained DNA values
*
* Athena bundles a build-tool called 'atdna'. This tool functions
* just like the 'clang' compiler, except it emits a full .cpp implementation
* with all read/write calls necessary to marshal the DNA structure to/from
* a streamed medium
*/
template <Endian DNAE>
struct DNA {
/**
* @brief Designated byte-order used for serializing fields
*/
static constexpr Endian DNAEndian = DNAE;
/**
* @brief Template type signaling atdna to capture the value where it's used
* @tparam T The type of the value. Can be any numeric type or atVec* type
* @tparam VE Endianness of the value
*/
template <typename T, Endian VE = DNAE>
using Value = T;
/**
* @brief Template type wrapping std::vector and signaling atdna to manipulate it where it's used
* @tparam T The type of contained elements. Can be any numeric type, atVec* type, or another DNA subclass
* @tparam cntVar C++ expression wrapped in DNA_COUNT macro to determine number of elements for vector
* @tparam VE Endianness of the contained values
*/
template <typename T, size_t cntVar, Endian VE = DNAE>
using Vector = std::vector<T>;
/**
* @brief Template type wrapping std::unique_ptr<atUint8[]> and signaling atdna to read a
* raw byte-buffer where it's used
* @tparam sizeVar C++ expression wrapped in DNA_COUNT macro to determine number of bytes for buffer
*/
template <size_t sizeVar>
using Buffer = std::unique_ptr<atUint8[]>;
/**
* @brief Template type wrapping std::string and signaling atdna to read string data where it's used
* @tparam sizeVar C++ expression wrapped in DNA_COUNT macro to determine number of characters for string
* -1 literal indicates null-terminated string
*/
template <atInt32 sizeVar = -1>
using String = std::string;
/**
* @brief Template type wrapping std::wstring and signaling atdna to read wstring data where it's used
* @tparam sizeVar C++ expression wrapped in DNA_COUNT macro to determine number of characters for wstring
* -1 literal indicates null-terminated wstring
*/
template <atInt32 sizeVar = -1, Endian VE = DNAE>
using WString = std::wstring;
/**
* @brief Meta Template signaling atdna to insert a stream seek where it's used
* @tparam offset C++ expression wrapped in DNA_COUNT macro to determine number of bytes to seek
* @tparam direction SeekOrigin to seek relative to
*/
template <off_t offset, SeekOrigin direction>
struct Seek {};
/**
* @brief Meta Template signaling atdna to insert an aligning stream seek where it's used
* @tparam align Number of bytes to align to
*/
template <size_t align>
struct Align {};
/**
* @brief Meta Template preventing atdna from emitting read/write implementations
*/
struct Delete {};
/* Bring fundamental operations into DNA subclasses for easier per-op overrides */
using Read = athena::io::Read<PropType::None>;
using Write = athena::io::Write<PropType::None>;
using BinarySize = athena::io::BinarySize<PropType::None>;
using PropCount = athena::io::PropCount<PropType::None>;
using ReadYaml = athena::io::ReadYaml<PropType::None>;
using WriteYaml = athena::io::WriteYaml<PropType::None>;
};
/**
* @brief Virtual DNA wrapper for subclasses that utilize virtual method calls
* @tparam DNAE Default-endianness for contained DNA values
*
* Typically, static template-based DNA resolution is sufficient; however, formats
* with a tree of variously-typed data structures would benefit from having a vtable.
*
* Note: It's not recommended to implement these directly. Instead, use the AT_DECL_DNA or
* AT_DECL_EXPLCIT_DNA macro in the subclasses. Specializing the Enumerate method
* is the proper way to override individual I/O operations. Owners of the virtualized
* subclass will typically use a unique_ptr to reference the data; specializing their own
* Enumerate methods as such:
*
* template <> void MySubclass::Enumerate<Read>(typename Read::StreamT& r)
* { (Do stuff with `r`) }
*/
template <Endian DNAE>
struct DNAV : DNA<DNAE> {
virtual ~DNAV() = default;
virtual void read(athena::io::IStreamReader& r) = 0;
virtual void write(athena::io::IStreamWriter& w) const = 0;
virtual void binarySize(size_t& s) const = 0;
virtual std::string_view DNATypeV() const = 0;
};
template <Endian DNAE>
struct DNAVYaml : DNAV<DNAE> {
virtual ~DNAVYaml() = default;
void read(athena::io::IStreamReader& r) override = 0;
void write(athena::io::IStreamWriter& w) const override = 0;
void binarySize(size_t& s) const override = 0;
virtual void read(athena::io::YAMLDocReader& r) = 0;
virtual void write(athena::io::YAMLDocWriter& w) const = 0;
};
/** Macro to supply count variable to atdna and mute it for other compilers */
#ifdef __clang__
#define AT_DNA_COUNT(...) sizeof(__VA_ARGS__)
#else
#define AT_DNA_COUNT(...) 0
#endif
} // namespace athena::io

1187
include/athena/DNAOp.hpp Normal file

File diff suppressed because it is too large Load Diff

121
include/athena/DNAYaml.hpp Normal file
View File

@@ -0,0 +1,121 @@
#pragma once
#include <string>
#include "athena/DNA.hpp"
#include "athena/FileReader.hpp"
#include "athena/FileWriter.hpp"
#include "athena/YAMLDocReader.hpp"
#include "athena/YAMLDocWriter.hpp"
namespace athena::io {
template <class T>
std::string_view __GetDNAName(const T& dna) {
if constexpr (__IsDNAVRecord_v<T>) {
return dna.DNATypeV();
} else {
return dna.DNAType();
}
}
template <class T>
std::string ToYAMLString(const T& dna) {
YAMLDocWriter docWriter(__GetDNAName(dna));
std::string res;
yaml_emitter_set_output(docWriter.getEmitter(), (yaml_write_handler_t*)YAMLStdStringWriter, &res);
yaml_emitter_set_unicode(docWriter.getEmitter(), true);
yaml_emitter_set_width(docWriter.getEmitter(), -1);
dna.write(docWriter);
if (!docWriter.finish(nullptr))
return std::string();
return res;
}
template <class T>
bool FromYAMLString(T& dna, std::string_view str) {
YAMLStdStringViewReaderState reader(str);
YAMLDocReader docReader;
yaml_parser_set_input(docReader.getParser(), (yaml_read_handler_t*)YAMLStdStringReader, &reader);
if (!docReader.parse(nullptr))
return false;
dna.read(docReader);
return true;
}
template <class DNASubtype>
bool ValidateFromYAMLString(std::string_view str) {
YAMLStdStringViewReaderState reader(str);
YAMLDocReader docReader;
yaml_parser_set_input(docReader.getParser(), (yaml_read_handler_t*)YAMLStdStringReader, &reader);
bool retval = docReader.ValidateClassType(DNASubtype::DNAType());
return retval;
}
template <class T>
bool ToYAMLStream(const T& dna, athena::io::IStreamWriter& fout) {
YAMLDocWriter docWriter(__GetDNAName(dna));
yaml_emitter_set_unicode(docWriter.getEmitter(), true);
yaml_emitter_set_width(docWriter.getEmitter(), -1);
dna.write(docWriter);
return docWriter.finish(&fout);
}
template <class T>
bool ToYAMLStream(const T& dna, athena::io::IStreamWriter& fout, void (T::*fn)(YAMLDocWriter& out) const) {
YAMLDocWriter docWriter(__GetDNAName(dna));
yaml_emitter_set_unicode(docWriter.getEmitter(), true);
yaml_emitter_set_width(docWriter.getEmitter(), -1);
(dna.*fn)(docWriter);
return docWriter.finish(&fout);
}
template <class T>
bool FromYAMLStream(T& dna, athena::io::IStreamReader& fin) {
YAMLDocReader docReader;
if (!docReader.parse(&fin))
return false;
dna.read(docReader);
return true;
}
template <class T>
bool FromYAMLStream(T& dna, athena::io::IStreamReader& fin, void (T::*fn)(YAMLDocReader& in)) {
YAMLDocReader docReader;
if (!docReader.parse(&fin))
return false;
(dna.*fn)(docReader);
return true;
}
template <class T, typename NameT>
bool MergeToYAMLFile(const T& dna, const NameT& filename) {
athena::io::FileReader r(filename);
YAMLDocWriter docWriter(__GetDNAName(dna), r.isOpen() ? &r : nullptr);
r.close();
dna.write(docWriter);
athena::io::FileWriter w(filename);
if (!w.isOpen())
return false;
return docWriter.finish(&w);
}
template <class DNASubtype>
bool ValidateFromYAMLStream(athena::io::IStreamReader& fin) {
YAMLDocReader reader;
atUint64 pos = fin.position();
yaml_parser_set_input(reader.getParser(), (yaml_read_handler_t*)YAMLAthenaReader, &fin);
bool retval = reader.ValidateClassType(DNASubtype::DNAType());
fin.seek(pos, athena::SeekOrigin::Begin);
return retval;
}
} // namespace athena::io

View File

@@ -2,7 +2,7 @@
#include <string> #include <string>
#if _WIN32 && !defined(__MINGW32__) #if _WIN32
using mode_t = int; using mode_t = int;
#else #else
#include <sys/stat.h> #include <sys/stat.h>

View File

@@ -24,8 +24,8 @@ public:
std::string extension() const; std::string extension() const;
static std::string extension(std::string_view path) { return FileInfo(path).extension(); } static std::string extension(std::string_view path) { return FileInfo(path).extension(); }
uint64_t size() const; atUint64 size() const;
static uint64_t size(std::string_view path) { return FileInfo(path).size(); } static atUint64 size(std::string_view path) { return FileInfo(path).size(); }
bool exists() const; bool exists() const;
static bool exists(std::string_view path) { return FileInfo(path).exists(); } static bool exists(std::string_view path) { return FileInfo(path).exists(); }

View File

@@ -10,8 +10,8 @@
namespace athena::io { namespace athena::io {
class FileReader : public IStreamReader { class FileReader : public IStreamReader {
public: public:
explicit FileReader(std::string_view filename, int32_t cacheSize = (32 * 1024), bool globalErr = true); explicit FileReader(std::string_view filename, atInt32 cacheSize = (32 * 1024), bool globalErr = true);
explicit FileReader(std::wstring_view filename, int32_t cacheSize = (32 * 1024), bool globalErr = true); explicit FileReader(std::wstring_view filename, atInt32 cacheSize = (32 * 1024), bool globalErr = true);
~FileReader() override; ~FileReader() override;
std::string filename() const { std::string filename() const {
@@ -33,12 +33,12 @@ public:
void open(); void open();
void close(); void close();
bool isOpen() const { return m_fileHandle != nullptr; } bool isOpen() const { return m_fileHandle != nullptr; }
void seek(int64_t pos, SeekOrigin origin = SeekOrigin::Current) override; void seek(atInt64 pos, SeekOrigin origin = SeekOrigin::Current) override;
uint64_t position() const override; atUint64 position() const override;
uint64_t length() const override; atUint64 length() const override;
uint64_t readUBytesToBuf(void* buf, uint64_t len) override; atUint64 readUBytesToBuf(void* buf, atUint64 len) override;
void setCacheSize(const int32_t blockSize); void setCacheSize(const atInt32 blockSize);
#if _WIN32 #if _WIN32
using HandleType = void*; using HandleType = void*;
@@ -55,11 +55,11 @@ protected:
std::string m_filename; std::string m_filename;
#endif #endif
HandleType m_fileHandle; HandleType m_fileHandle;
uint64_t m_fileSize; atUint64 m_fileSize;
std::unique_ptr<uint8_t[]> m_cacheData; std::unique_ptr<atUint8[]> m_cacheData;
int32_t m_blockSize; atInt32 m_blockSize;
int32_t m_curBlock; atInt32 m_curBlock;
uint64_t m_offset; atUint64 m_offset;
bool m_globalErr; bool m_globalErr;
}; };
} // namespace athena::io } // namespace athena::io

View File

@@ -30,10 +30,10 @@ public:
void open(bool overwrite = true); void open(bool overwrite = true);
void close(); void close();
bool isOpen() const { return m_fileHandle != nullptr; } bool isOpen() const { return m_fileHandle != nullptr; }
void seek(int64_t pos, SeekOrigin origin = SeekOrigin::Current) override; void seek(atInt64 pos, SeekOrigin origin = SeekOrigin::Current) override;
uint64_t position() const override; atUint64 position() const override;
uint64_t length() const override; atUint64 length() const override;
void writeUBytes(const uint8_t* data, uint64_t len) override; void writeUBytes(const atUint8* data, atUint64 len) override;
#ifdef _WIN32 #ifdef _WIN32
using HandleType = void*; using HandleType = void*;
@@ -61,7 +61,7 @@ class TransactionalFileWriter : public IStreamWriter {
#endif #endif
bool m_overwrite, m_globalErr; bool m_overwrite, m_globalErr;
std::vector<uint8_t> m_deferredBuffer; std::vector<uint8_t> m_deferredBuffer;
uint64_t m_position = 0; atUint64 m_position = 0;
public: public:
explicit TransactionalFileWriter(std::string_view filename, bool overwrite = true, bool globalErr = true) explicit TransactionalFileWriter(std::string_view filename, bool overwrite = true, bool globalErr = true)
@@ -94,10 +94,10 @@ public:
m_position = 0; m_position = 0;
} }
uint64_t position() const override { return m_position; } atUint64 position() const override { return m_position; }
uint64_t length() const override { return m_deferredBuffer.size(); } atUint64 length() const override { return m_deferredBuffer.size(); }
void seek(int64_t pos, SeekOrigin origin = SeekOrigin::Current) override; void seek(atInt64 pos, SeekOrigin origin = SeekOrigin::Current) override;
void writeUBytes(const uint8_t* data, uint64_t len) override; void writeUBytes(const atUint8* data, atUint64 len) override;
~TransactionalFileWriter() override { flush(); } ~TransactionalFileWriter() override { flush(); }
}; };

View File

@@ -3,7 +3,7 @@
#include <ostream> #include <ostream>
#include "athena/Types.hpp" #include "athena/Types.hpp"
#include <format> #include <fmt/format.h>
#ifdef _MSC_VER #ifdef _MSC_VER
#pragma warning(disable : 4996) #pragma warning(disable : 4996)
@@ -17,11 +17,11 @@
#include <sys/stat.h> #include <sys/stat.h>
#if !defined(S_ISREG) && defined(S_IFMT) && defined(S_IFREG) #if !defined(S_ISREG) && defined(S_IFMT) && defined(S_IFREG)
#define S_ISREG(m) (((m) & S_IFMT) == S_IFREG) #define S_ISREG(m) (((m)&S_IFMT) == S_IFREG)
#endif #endif
#if !defined(S_ISDIR) && defined(S_IFMT) && defined(S_IFDIR) #if !defined(S_ISDIR) && defined(S_IFMT) && defined(S_IFDIR)
#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) #define S_ISDIR(m) (((m)&S_IFMT) == S_IFDIR)
#endif #endif
#if !defined(S_ISLNK) #if !defined(S_ISLNK)
@@ -118,14 +118,31 @@ enum class SeekOrigin { Begin, Current, End };
enum class Endian { Little, Big }; enum class Endian { Little, Big };
namespace io {
template <Endian DNAE>
struct DNA;
template <Endian DNAE>
struct DNAV;
template <class T>
using __IsDNARecord = std::disjunction<std::is_base_of<DNA<Endian::Big>, T>, std::is_base_of<DNA<Endian::Little>, T>>;
template <class T>
constexpr bool __IsDNARecord_v = __IsDNARecord<T>::value;
template <class T>
using __IsDNAVRecord =
std::disjunction<std::is_base_of<DNAV<Endian::Big>, T>, std::is_base_of<DNAV<Endian::Little>, T>>;
template <class T>
constexpr bool __IsDNAVRecord_v = __IsDNAVRecord<T>::value;
} // namespace io
} // namespace athena } // namespace athena
typedef void (*atEXCEPTION_HANDLER)(athena::error::Level level, const char* /*file*/, const char*, int /*line*/, typedef void (*atEXCEPTION_HANDLER)(athena::error::Level level, const char* /*file*/, const char*, int /*line*/,
std::string_view fmt, std::format_args args); fmt::string_view fmt, fmt::format_args args);
atEXCEPTION_HANDLER atGetExceptionHandler(); atEXCEPTION_HANDLER atGetExceptionHandler();
/** /**
* atSetExceptionHandler is only meant to be used at the start and end of an application's lifetime, * atSetExceptionHandler is only meant to be used a the start and end of an application's lifetime,
* this function cannot be considered thread-safe, therefore modifying during runtime is not recommended. * this function cannot be considered thread-safe, therefore modifying during runtime is not recommended.
*/ */
void atSetExceptionHandler(atEXCEPTION_HANDLER func); void atSetExceptionHandler(atEXCEPTION_HANDLER func);
@@ -133,47 +150,54 @@ void atSetExceptionHandler(atEXCEPTION_HANDLER func);
std::ostream& operator<<(std::ostream& os, const athena::SeekOrigin& origin); std::ostream& operator<<(std::ostream& os, const athena::SeekOrigin& origin);
std::ostream& operator<<(std::ostream& os, const athena::Endian& endian); std::ostream& operator<<(std::ostream& os, const athena::Endian& endian);
template <typename First, typename... Rest>
constexpr auto __FIRST_ARG__(First first, Rest...) { return first; }
template <typename S, typename... Args>
auto __make_args_checked__(const S& format_str, Args&&... args) {
return fmt::make_args_checked<Args...>(format_str, std::forward<Args>(args)...);
}
#ifndef NDEBUG #ifndef NDEBUG
#define atDebug(fmt, ...) \ #define atDebug(...) \
do { \ do { \
atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \ atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \
if (__handler) \ if (__handler) \
__handler(athena::error::Level::Message, __FILE__, AT_PRETTY_FUNCTION, __LINE__, fmt, \ __handler(athena::error::Level::Message, __FILE__, AT_PRETTY_FUNCTION, __LINE__, __FIRST_ARG__(__VA_ARGS__), \
std::make_format_args(__VA_ARGS__)); \ __make_args_checked__(__VA_ARGS__)); \
} while (0) } while (0)
#else #else
#define atDebug(...) #define atDebug(...)
#endif #endif
#define atMessage(fmt, ...) \ #define atMessage(...) \
do { \ do { \
atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \ atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \
if (__handler) \ if (__handler) \
__handler(athena::error::Level::Message, __FILE__, AT_PRETTY_FUNCTION, __LINE__, fmt, \ __handler(athena::error::Level::Message, __FILE__, AT_PRETTY_FUNCTION, __LINE__, __FIRST_ARG__(__VA_ARGS__), \
std::make_format_args(__VA_ARGS__)); \ __make_args_checked__(__VA_ARGS__)); \
} while (0) } while (0)
#define atWarning(fmt, ...) \ #define atWarning(...) \
do { \ do { \
atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \ atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \
if (__handler) { \ if (__handler) { \
__handler(athena::error::Level::Warning, __FILE__, AT_PRETTY_FUNCTION, __LINE__, fmt, \ __handler(athena::error::Level::Warning, __FILE__, AT_PRETTY_FUNCTION, __LINE__, __FIRST_ARG__(__VA_ARGS__), \
std::make_format_args(__VA_ARGS__)); \ __make_args_checked__(__VA_ARGS__)); \
} \ } \
} while (0) } while (0)
#define atError(fmt, ...) \ #define atError(...) \
do { \ do { \
atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \ atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \
if (__handler) \ if (__handler) \
__handler(athena::error::Level::Error, __FILE__, AT_PRETTY_FUNCTION, __LINE__, fmt, \ __handler(athena::error::Level::Error, __FILE__, AT_PRETTY_FUNCTION, __LINE__, __FIRST_ARG__(__VA_ARGS__), \
std::make_format_args(__VA_ARGS__)); \ __make_args_checked__(__VA_ARGS__)); \
} while (0) } while (0)
#define atFatal(fmt, ...) \ #define atFatal(...) \
do { \ do { \
atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \ atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \
if (__handler) \ if (__handler) \
__handler(athena::error::Level::Fatal, __FILE__, AT_PRETTY_FUNCTION, __LINE__, fmt, \ __handler(athena::error::Level::Fatal, __FILE__, AT_PRETTY_FUNCTION, __LINE__, __FIRST_ARG__(__VA_ARGS__), \
std::make_format_args(__VA_ARGS__)); \ __make_args_checked__(__VA_ARGS__)); \
} while (0) } while (0)

View File

@@ -12,10 +12,10 @@ public:
Endian endian() const { return m_endian; } Endian endian() const { return m_endian; }
bool isBigEndian() const { return (m_endian == Endian::Big); } bool isBigEndian() const { return (m_endian == Endian::Big); }
bool isLittleEndian() const { return (m_endian == Endian::Little); } bool isLittleEndian() const { return (m_endian == Endian::Little); }
virtual void seek(int64_t, SeekOrigin) = 0; virtual void seek(atInt64, SeekOrigin) = 0;
virtual bool atEnd() const = 0; virtual bool atEnd() const = 0;
virtual uint64_t position() const = 0; virtual atUint64 position() const = 0;
virtual uint64_t length() const = 0; virtual atUint64 length() const = 0;
bool hasError() const { return m_hasError; } bool hasError() const { return m_hasError; }
protected: protected:

View File

@@ -24,7 +24,7 @@ public:
* @param position where in the buffer to seek * @param position where in the buffer to seek
* @param origin The Origin to seek relative to * @param origin The Origin to seek relative to
*/ */
void seek(int64_t position, SeekOrigin origin = SeekOrigin::Current) override = 0; void seek(atInt64 position, SeekOrigin origin = SeekOrigin::Current) override = 0;
/** @brief Sets the buffer's position relative to the next 64-byte aligned position.<br /> /** @brief Sets the buffer's position relative to the next 64-byte aligned position.<br />
*/ */
@@ -52,33 +52,33 @@ public:
* *
* @return The current position in the stream. * @return The current position in the stream.
*/ */
uint64_t position() const override = 0; atUint64 position() const override = 0;
/** @brief Returns the length of the file. /** @brief Returns the length of the file.
* *
* @return True length of the file. * @return True length of the file.
*/ */
uint64_t length() const override = 0; atUint64 length() const override = 0;
/** @brief Reads a byte at the current position and advances the current position /** @brief Reads a byte at the current position and advances the current position
* *
* @return The value at the current position * @return The value at the current position
*/ */
int8_t readByte() { atInt8 readByte() {
int8_t val = 0; atInt8 val = 0;
readUBytesToBuf(&val, 1); readUBytesToBuf(&val, 1);
return val; return val;
} }
template <class T> template <class T>
int8_t readVal(std::enable_if_t<std::is_same_v<T, int8_t>>* = nullptr) { atInt8 readVal(std::enable_if_t<std::is_same_v<T, atInt8>>* = nullptr) {
return readByte(); return readByte();
} }
template <class T> template <class T>
int8_t readValLittle(std::enable_if_t<std::is_same_v<T, int8_t>>* = nullptr) { atInt8 readValLittle(std::enable_if_t<std::is_same_v<T, atInt8>>* = nullptr) {
return readByte(); return readByte();
} }
template <class T> template <class T>
int8_t readValBig(std::enable_if_t<std::is_same_v<T, int8_t>>* = nullptr) { atInt8 readValBig(std::enable_if_t<std::is_same_v<T, atInt8>>* = nullptr) {
return readByte(); return readByte();
} }
@@ -86,17 +86,17 @@ public:
* *
* @return The value at the current position * @return The value at the current position
*/ */
uint8_t readUByte() { return readByte(); } atUint8 readUByte() { return readByte(); }
template <class T> template <class T>
uint8_t readVal(std::enable_if_t<std::is_same_v<T, uint8_t>>* = nullptr) { atUint8 readVal(std::enable_if_t<std::is_same_v<T, atUint8>>* = nullptr) {
return readUByte(); return readUByte();
} }
template <class T> template <class T>
uint8_t readValLittle(std::enable_if_t<std::is_same_v<T, uint8_t>>* = nullptr) { atUint8 readValLittle(std::enable_if_t<std::is_same_v<T, atUint8>>* = nullptr) {
return readUByte(); return readUByte();
} }
template <class T> template <class T>
uint8_t readValBig(std::enable_if_t<std::is_same_v<T, uint8_t>>* = nullptr) { atUint8 readValBig(std::enable_if_t<std::is_same_v<T, atUint8>>* = nullptr) {
return readUByte(); return readUByte();
} }
@@ -104,8 +104,8 @@ public:
* *
* @return The buffer at the current position from the given length. * @return The buffer at the current position from the given length.
*/ */
std::unique_ptr<int8_t[]> readBytes(uint64_t length) { std::unique_ptr<atInt8[]> readBytes(atUint64 length) {
auto buf = std::make_unique<int8_t[]>(length); auto buf = std::make_unique<atInt8[]>(length);
readUBytesToBuf(buf.get(), length); readUBytesToBuf(buf.get(), length);
return buf; return buf;
} }
@@ -114,8 +114,8 @@ public:
* *
* @return The buffer at the current position from the given length. * @return The buffer at the current position from the given length.
*/ */
std::unique_ptr<uint8_t[]> readUBytes(uint64_t length) { std::unique_ptr<atUint8[]> readUBytes(atUint64 length) {
auto buf = std::make_unique<uint8_t[]>(length); auto buf = std::make_unique<atUint8[]>(length);
readUBytesToBuf(buf.get(), length); readUBytesToBuf(buf.get(), length);
return buf; return buf;
} }
@@ -125,7 +125,7 @@ public:
* @param len The length of the buffer * @param len The length of the buffer
* @return How much data was actually read, useful for detecting read errors. * @return How much data was actually read, useful for detecting read errors.
*/ */
uint64_t readBytesToBuf(void* buf, uint64_t len) { return readUBytesToBuf(buf, len); } atUint64 readBytesToBuf(void* buf, atUint64 len) { return readUBytesToBuf(buf, len); }
/** @brief Attempts to read a fixed length of data into a pre-allocated buffer, this function is client defined /** @brief Attempts to read a fixed length of data into a pre-allocated buffer, this function is client defined
* and must be implemented. * and must be implemented.
@@ -133,20 +133,20 @@ public:
* @param len The length of the buffer * @param len The length of the buffer
* @return How much data was actually read, useful for detecting read errors. * @return How much data was actually read, useful for detecting read errors.
*/ */
virtual uint64_t readUBytesToBuf(void* buf, uint64_t len) = 0; virtual atUint64 readUBytesToBuf(void* buf, atUint64 len) = 0;
/** @brief Reads a Int16 and swaps to endianness specified by setEndian depending on platform /** @brief Reads a Int16 and swaps to endianness specified by setEndian depending on platform
* and advances the current position * and advances the current position
* *
* @return The value at the current address * @return The value at the current address
*/ */
int16_t readInt16() { atInt16 readInt16() {
int16_t val = 0; atInt16 val = 0;
readUBytesToBuf(&val, 2); readUBytesToBuf(&val, 2);
return m_endian == Endian::Big ? utility::BigInt16(val) : utility::LittleInt16(val); return m_endian == Endian::Big ? utility::BigInt16(val) : utility::LittleInt16(val);
} }
template <class T> template <class T>
int16_t readVal(std::enable_if_t<std::is_same_v<T, int16_t>>* = nullptr) { atInt16 readVal(std::enable_if_t<std::is_same_v<T, atInt16>>* = nullptr) {
return readInt16(); return readInt16();
} }
@@ -155,13 +155,13 @@ public:
* *
* @return The value at the current address * @return The value at the current address
*/ */
int16_t readInt16Little() { atInt16 readInt16Little() {
int16_t val = 0; atInt16 val = 0;
readUBytesToBuf(&val, 2); readUBytesToBuf(&val, 2);
return utility::LittleInt16(val); return utility::LittleInt16(val);
} }
template <class T> template <class T>
int16_t readValLittle(std::enable_if_t<std::is_same_v<T, int16_t>>* = nullptr) { atInt16 readValLittle(std::enable_if_t<std::is_same_v<T, atInt16>>* = nullptr) {
return readInt16Little(); return readInt16Little();
} }
@@ -170,13 +170,13 @@ public:
* *
* @return The value at the current address * @return The value at the current address
*/ */
int16_t readInt16Big() { atInt16 readInt16Big() {
int16_t val = 0; atInt16 val = 0;
readUBytesToBuf(&val, 2); readUBytesToBuf(&val, 2);
return utility::BigInt16(val); return utility::BigInt16(val);
} }
template <class T> template <class T>
int16_t readValBig(std::enable_if_t<std::is_same_v<T, int16_t>>* = nullptr) { atInt16 readValBig(std::enable_if_t<std::is_same_v<T, atInt16>>* = nullptr) {
return readInt16Big(); return readInt16Big();
} }
@@ -185,9 +185,9 @@ public:
* *
* @return The value at the current address * @return The value at the current address
*/ */
uint16_t readUint16() { return readInt16(); } atUint16 readUint16() { return readInt16(); }
template <class T> template <class T>
uint16_t readVal(std::enable_if_t<std::is_same_v<T, uint16_t>>* = 0) { atUint16 readVal(std::enable_if_t<std::is_same_v<T, atUint16>>* = 0) {
return readUint16(); return readUint16();
} }
@@ -196,13 +196,13 @@ public:
* *
* @return The value at the current address * @return The value at the current address
*/ */
uint16_t readUint16Little() { atUint16 readUint16Little() {
uint16_t val = 0; atUint16 val = 0;
readUBytesToBuf(&val, 2); readUBytesToBuf(&val, 2);
return utility::LittleUint16(val); return utility::LittleUint16(val);
} }
template <class T> template <class T>
uint16_t readValLittle(std::enable_if_t<std::is_same_v<T, uint16_t>>* = nullptr) { atUint16 readValLittle(std::enable_if_t<std::is_same_v<T, atUint16>>* = nullptr) {
return readUint16Little(); return readUint16Little();
} }
@@ -211,13 +211,13 @@ public:
* *
* @return The value at the current address * @return The value at the current address
*/ */
uint16_t readUint16Big() { atUint16 readUint16Big() {
uint16_t val = 0; atUint16 val = 0;
readUBytesToBuf(&val, 2); readUBytesToBuf(&val, 2);
return utility::BigUint16(val); return utility::BigUint16(val);
} }
template <class T> template <class T>
uint16_t readValBig(std::enable_if_t<std::is_same_v<T, uint16_t>>* = nullptr) { atUint16 readValBig(std::enable_if_t<std::is_same_v<T, atUint16>>* = nullptr) {
return readUint16Big(); return readUint16Big();
} }
@@ -226,13 +226,13 @@ public:
* *
* @return The value at the current address * @return The value at the current address
*/ */
int32_t readInt32() { atInt32 readInt32() {
int32_t val = 0; atInt32 val = 0;
readUBytesToBuf(&val, 4); readUBytesToBuf(&val, 4);
return m_endian == Endian::Big ? utility::BigInt32(val) : utility::LittleInt32(val); return m_endian == Endian::Big ? utility::BigInt32(val) : utility::LittleInt32(val);
} }
template <class T> template <class T>
int32_t readVal(std::enable_if_t<std::is_same_v<T, int32_t>>* = nullptr) { atInt32 readVal(std::enable_if_t<std::is_same_v<T, atInt32>>* = nullptr) {
return readInt32(); return readInt32();
} }
@@ -241,13 +241,13 @@ public:
* *
* @return The value at the current address * @return The value at the current address
*/ */
int32_t readInt32Little() { atInt32 readInt32Little() {
int32_t val = 0; atInt32 val = 0;
readUBytesToBuf(&val, 4); readUBytesToBuf(&val, 4);
return utility::LittleInt32(val); return utility::LittleInt32(val);
} }
template <class T> template <class T>
int32_t readValLittle(std::enable_if_t<std::is_same_v<T, int32_t>>* = nullptr) { atInt32 readValLittle(std::enable_if_t<std::is_same_v<T, atInt32>>* = nullptr) {
return readInt32Little(); return readInt32Little();
} }
@@ -256,13 +256,13 @@ public:
* *
* @return The value at the current address * @return The value at the current address
*/ */
int32_t readInt32Big() { atInt32 readInt32Big() {
int32_t val = 0; atInt32 val = 0;
readUBytesToBuf(&val, 4); readUBytesToBuf(&val, 4);
return utility::BigInt32(val); return utility::BigInt32(val);
} }
template <class T> template <class T>
int32_t readValBig(std::enable_if_t<std::is_same_v<T, int32_t>>* = nullptr) { atInt32 readValBig(std::enable_if_t<std::is_same_v<T, atInt32>>* = nullptr) {
return readInt32Big(); return readInt32Big();
} }
@@ -271,9 +271,9 @@ public:
* *
* @return The value at the current address * @return The value at the current address
*/ */
uint32_t readUint32() { return readInt32(); } atUint32 readUint32() { return readInt32(); }
template <class T> template <class T>
uint32_t readVal(std::enable_if_t<std::is_same_v<T, uint32_t>>* = nullptr) { atUint32 readVal(std::enable_if_t<std::is_same_v<T, atUint32>>* = nullptr) {
return readUint32(); return readUint32();
} }
@@ -282,13 +282,13 @@ public:
* *
* @return The value at the current address * @return The value at the current address
*/ */
uint32_t readUint32Little() { atUint32 readUint32Little() {
uint32_t val = 0; atUint32 val = 0;
readUBytesToBuf(&val, 4); readUBytesToBuf(&val, 4);
return utility::LittleUint32(val); return utility::LittleUint32(val);
} }
template <class T> template <class T>
int32_t readValLittle(std::enable_if_t<std::is_same_v<T, uint32_t>>* = nullptr) { atInt32 readValLittle(std::enable_if_t<std::is_same_v<T, atUint32>>* = nullptr) {
return readUint32Little(); return readUint32Little();
} }
@@ -297,13 +297,13 @@ public:
* *
* @return The value at the current address * @return The value at the current address
*/ */
uint32_t readUint32Big() { atUint32 readUint32Big() {
uint32_t val = 0; atUint32 val = 0;
readUBytesToBuf(&val, 4); readUBytesToBuf(&val, 4);
return utility::BigUint32(val); return utility::BigUint32(val);
} }
template <class T> template <class T>
uint32_t readValBig(std::enable_if_t<std::is_same_v<T, uint32_t>>* = nullptr) { atUint32 readValBig(std::enable_if_t<std::is_same_v<T, atUint32>>* = nullptr) {
return readUint32Big(); return readUint32Big();
} }
@@ -312,13 +312,13 @@ public:
* *
* @return The value at the current address * @return The value at the current address
*/ */
int64_t readInt64() { atInt64 readInt64() {
int64_t val = 0; atInt64 val = 0;
readUBytesToBuf(&val, 8); readUBytesToBuf(&val, 8);
return m_endian == Endian::Big ? utility::BigInt64(val) : utility::LittleInt64(val); return m_endian == Endian::Big ? utility::BigInt64(val) : utility::LittleInt64(val);
} }
template <class T> template <class T>
int64_t readVal(std::enable_if_t<std::is_same_v<T, int64_t>>* = nullptr) { atInt64 readVal(std::enable_if_t<std::is_same_v<T, atInt64>>* = nullptr) {
return readInt64(); return readInt64();
} }
@@ -327,13 +327,13 @@ public:
* *
* @return The value at the current address * @return The value at the current address
*/ */
int64_t readInt64Little() { atInt64 readInt64Little() {
int64_t val = 0; atInt64 val = 0;
readUBytesToBuf(&val, 8); readUBytesToBuf(&val, 8);
return utility::LittleInt64(val); return utility::LittleInt64(val);
} }
template <class T> template <class T>
int64_t readValLittle(std::enable_if_t<std::is_same_v<T, int64_t>>* = nullptr) { atInt64 readValLittle(std::enable_if_t<std::is_same_v<T, atInt64>>* = nullptr) {
return readInt64Little(); return readInt64Little();
} }
@@ -342,13 +342,13 @@ public:
* *
* @return The value at the current address * @return The value at the current address
*/ */
int64_t readInt64Big() { atInt64 readInt64Big() {
int64_t val = 0; atInt64 val = 0;
readUBytesToBuf(&val, 8); readUBytesToBuf(&val, 8);
return utility::BigInt64(val); return utility::BigInt64(val);
} }
template <class T> template <class T>
int64_t readValBig(std::enable_if_t<std::is_same_v<T, int64_t>>* = nullptr) { atInt64 readValBig(std::enable_if_t<std::is_same_v<T, atInt64>>* = nullptr) {
return readInt64Big(); return readInt64Big();
} }
@@ -357,9 +357,9 @@ public:
* *
* @return The value at the current address * @return The value at the current address
*/ */
uint64_t readUint64() { return readInt64(); } atUint64 readUint64() { return readInt64(); }
template <class T> template <class T>
uint64_t readVal(std::enable_if_t<std::is_same_v<T, uint64_t>>* = nullptr) { atUint64 readVal(std::enable_if_t<std::is_same_v<T, atUint64>>* = nullptr) {
return readUint64(); return readUint64();
} }
@@ -368,13 +368,13 @@ public:
* *
* @return The value at the current address * @return The value at the current address
*/ */
uint64_t readUint64Little() { atUint64 readUint64Little() {
uint64_t val = 0; atUint64 val = 0;
readUBytesToBuf(&val, 8); readUBytesToBuf(&val, 8);
return utility::LittleUint64(val); return utility::LittleUint64(val);
} }
template <class T> template <class T>
uint64_t readValLittle(std::enable_if_t<std::is_same_v<T, uint64_t>>* = nullptr) { atUint64 readValLittle(std::enable_if_t<std::is_same_v<T, atUint64>>* = nullptr) {
return readUint64Little(); return readUint64Little();
} }
@@ -383,13 +383,13 @@ public:
* *
* @return The value at the current address * @return The value at the current address
*/ */
uint64_t readUint64Big() { atUint64 readUint64Big() {
uint64_t val = 0; atUint64 val = 0;
readUBytesToBuf(&val, 8); readUBytesToBuf(&val, 8);
return utility::BigUint64(val); return utility::BigUint64(val);
} }
template <class T> template <class T>
uint64_t readValBig(std::enable_if_t<std::is_same_v<T, uint64_t>>* = nullptr) { atUint64 readValBig(std::enable_if_t<std::is_same_v<T, atUint64>>* = nullptr) {
return readUint64Big(); return readUint64Big();
} }
@@ -488,7 +488,7 @@ public:
* @return The value at the current address * @return The value at the current address
*/ */
bool readBool() { bool readBool() {
uint8_t val = false; atUint8 val = false;
readUBytesToBuf(&val, 1); readUBytesToBuf(&val, 1);
return val != 0; return val != 0;
} }
@@ -927,13 +927,13 @@ public:
* *
* @return The read string * @return The read string
*/ */
std::string readString(int32_t fixedLen = -1, bool doSeek = true) { std::string readString(atInt32 fixedLen = -1, bool doSeek = true) {
if (fixedLen == 0) if (fixedLen == 0)
return std::string(); return std::string();
std::string ret; std::string ret;
uint8_t chr = readByte(); atUint8 chr = readByte();
int32_t i; atInt32 i;
for (i = 1; chr != 0; ++i) { for (i = 1; chr != 0; ++i) {
ret += chr; ret += chr;
@@ -961,14 +961,14 @@ public:
* *
* @return The read wstring * @return The read wstring
*/ */
std::wstring readWString(int32_t fixedLen = -1, bool doSeek = true) { std::wstring readWString(atInt32 fixedLen = -1, bool doSeek = true) {
if (fixedLen == 0) if (fixedLen == 0)
return std::wstring(); return std::wstring();
std::wstring ret; std::wstring ret;
uint16_t chr = readUint16(); atUint16 chr = readUint16();
int32_t i; atInt32 i;
for (i = 1; chr != 0; ++i) { for (i = 1; chr != 0; ++i) {
ret += chr; ret += chr;
@@ -997,14 +997,14 @@ public:
* *
* @return The read wstring * @return The read wstring
*/ */
std::wstring readWStringLittle(int32_t fixedLen = -1, bool doSeek = true) { std::wstring readWStringLittle(atInt32 fixedLen = -1, bool doSeek = true) {
if (fixedLen == 0) if (fixedLen == 0)
return std::wstring(); return std::wstring();
std::wstring ret; std::wstring ret;
uint16_t chr = readUint16Little(); atUint16 chr = readUint16Little();
int32_t i; atInt32 i;
for (i = 1; chr != 0; ++i) { for (i = 1; chr != 0; ++i) {
ret += chr; ret += chr;
@@ -1033,13 +1033,13 @@ public:
* *
* @return The read wstring * @return The read wstring
*/ */
std::wstring readWStringBig(int32_t fixedLen = -1, bool doSeek = true) { std::wstring readWStringBig(atInt32 fixedLen = -1, bool doSeek = true) {
if (fixedLen == 0) if (fixedLen == 0)
return std::wstring(); return std::wstring();
std::wstring ret; std::wstring ret;
uint16_t chr = readUint16Big(); atUint16 chr = readUint16Big();
int32_t i; atInt32 i;
for (i = 1; chr != 0; ++i) { for (i = 1; chr != 0; ++i) {
ret += chr; ret += chr;
@@ -1068,13 +1068,13 @@ public:
* *
* @return The read wstring * @return The read wstring
*/ */
std::u16string readU16StringBig(int32_t fixedLen = -1, bool doSeek = true) { std::u16string readU16StringBig(atInt32 fixedLen = -1, bool doSeek = true) {
if (fixedLen == 0) if (fixedLen == 0)
return std::u16string(); return std::u16string();
std::u16string ret; std::u16string ret;
char16_t chr = readUint16Big(); char16_t chr = readUint16Big();
int32_t i; atInt32 i;
for (i = 1; chr != 0; ++i) { for (i = 1; chr != 0; ++i) {
ret += chr; ret += chr;
@@ -1103,13 +1103,13 @@ public:
* *
* @return The read wstring * @return The read wstring
*/ */
std::u32string readU32StringBig(int32_t fixedLen = -1, bool doSeek = true) { std::u32string readU32StringBig(atInt32 fixedLen = -1, bool doSeek = true) {
if (fixedLen == 0) if (fixedLen == 0)
return std::u32string(); return std::u32string();
std::u32string ret; std::u32string ret;
char32_t chr = readUint32Big(); char32_t chr = readUint32Big();
int32_t i; atInt32 i;
for (i = 1; chr != 0; ++i) { for (i = 1; chr != 0; ++i) {
ret += chr; ret += chr;

View File

@@ -19,7 +19,7 @@ public:
* @param position where in the buffer to seek * @param position where in the buffer to seek
* @param origin The location to seek relative to * @param origin The location to seek relative to
*/ */
void seek(int64_t position, SeekOrigin origin = SeekOrigin::Current) override = 0; void seek(atInt64 position, SeekOrigin origin = SeekOrigin::Current) override = 0;
/** @brief Sets the buffers position relative to the next 32-byte aligned position.<br /> /** @brief Sets the buffers position relative to the next 32-byte aligned position.<br />
*/ */
@@ -27,11 +27,11 @@ public:
/** @brief Writes zero up to specified absolute offset.<br /> /** @brief Writes zero up to specified absolute offset.<br />
*/ */
void writeZeroTo(int64_t pos) { void writeZeroTo(atInt64 pos) {
int64_t delta = pos - position(); atInt64 delta = pos - position();
if (delta <= 0) if (delta <= 0)
return; return;
for (int64_t i = 0; i < delta; ++i) for (atInt64 i = 0; i < delta; ++i)
writeUByte(0); writeUByte(0);
} }
@@ -45,29 +45,29 @@ public:
* *
* @return The current position in the stream. * @return The current position in the stream.
*/ */
uint64_t position() const override = 0; atUint64 position() const override = 0;
/** @brief Returns whether or not the stream is at the end. /** @brief Returns whether or not the stream is at the end.
* *
* @return True if at end; False otherwise. * @return True if at end; False otherwise.
*/ */
uint64_t length() const override = 0; atUint64 length() const override = 0;
/** @brief Writes a byte at the current position and advances the position by one byte. /** @brief Writes a byte at the current position and advances the position by one byte.
* @param val The value to write * @param val The value to write
*/ */
void writeUByte(uint8_t val) { writeUBytes(&val, 1); } void writeUByte(atUint8 val) { writeUBytes(&val, 1); }
void writeVal(uint8_t val) { writeUByte(val); } void writeVal(atUint8 val) { writeUByte(val); }
void writeValLittle(uint8_t val) { writeUByte(val); } void writeValLittle(atUint8 val) { writeUByte(val); }
void writeValBig(uint8_t val) { writeUByte(val); } void writeValBig(atUint8 val) { writeUByte(val); }
/** @brief Writes a byte at the current position and advances the position by one byte. /** @brief Writes a byte at the current position and advances the position by one byte.
* @param val The value to write * @param val The value to write
*/ */
void writeByte(int8_t val) { writeUByte(val); } void writeByte(atInt8 val) { writeUByte(val); }
void writeVal(int8_t val) { writeByte(val); } void writeVal(atInt8 val) { writeByte(val); }
void writeValLittle(int8_t val) { writeByte(val); } void writeValLittle(atInt8 val) { writeByte(val); }
void writeValBig(int8_t val) { writeByte(val); } void writeValBig(atInt8 val) { writeByte(val); }
/** @brief Writes the given buffer with the specified length, buffers can be bigger than the length /** @brief Writes the given buffer with the specified length, buffers can be bigger than the length
* however it's undefined behavior to try and write a buffer which is smaller than the given length. * however it's undefined behavior to try and write a buffer which is smaller than the given length.
@@ -75,7 +75,7 @@ public:
* @param data The buffer to write * @param data The buffer to write
* @param length The amount to write * @param length The amount to write
*/ */
virtual void writeUBytes(const uint8_t* data, uint64_t length) = 0; virtual void writeUBytes(const atUint8* data, atUint64 length) = 0;
/** @brief Writes the given buffer with the specified length, buffers can be bigger than the length /** @brief Writes the given buffer with the specified length, buffers can be bigger than the length
* however it's undefined behavior to try and write a buffer which is smaller than the given length. * however it's undefined behavior to try and write a buffer which is smaller than the given length.
@@ -83,14 +83,14 @@ public:
* @param data The buffer to write * @param data The buffer to write
* @param length The amount to write * @param length The amount to write
*/ */
void writeBytes(const void* data, uint64_t length) { writeUBytes(reinterpret_cast<const uint8_t*>(data), length); } void writeBytes(const void* data, atUint64 length) { writeUBytes(reinterpret_cast<const atUint8*>(data), length); }
/** @brief Writes an Int16 to the buffer and advances the buffer. /** @brief Writes an Int16 to the buffer and advances the buffer.
* It also swaps the bytes depending on the platform and Stream settings. * It also swaps the bytes depending on the platform and Stream settings.
* *
* @param val The value to write to the buffer * @param val The value to write to the buffer
*/ */
void writeInt16(int16_t val) { void writeInt16(atInt16 val) {
if (m_endian == Endian::Big) { if (m_endian == Endian::Big) {
utility::BigInt16(val); utility::BigInt16(val);
} else { } else {
@@ -98,60 +98,60 @@ public:
} }
writeBytes(&val, sizeof(val)); writeBytes(&val, sizeof(val));
} }
void writeVal(int16_t val) { writeInt16(val); } void writeVal(atInt16 val) { writeInt16(val); }
/** @brief Writes an Int16 to the buffer and advances the buffer. /** @brief Writes an Int16 to the buffer and advances the buffer.
* It also swaps the bytes against little depending on the platform. * It also swaps the bytes against little depending on the platform.
* *
* @param val The value to write to the buffer * @param val The value to write to the buffer
*/ */
void writeInt16Little(int16_t val) { void writeInt16Little(atInt16 val) {
utility::LittleInt16(val); utility::LittleInt16(val);
writeBytes(&val, sizeof(val)); writeBytes(&val, sizeof(val));
} }
void writeValLittle(int16_t val) { writeInt16Little(val); } void writeValLittle(atInt16 val) { writeInt16Little(val); }
/** @brief Writes an Int16 to the buffer and advances the buffer. /** @brief Writes an Int16 to the buffer and advances the buffer.
* It also swaps the bytes against big depending on the platform. * It also swaps the bytes against big depending on the platform.
* *
* @param val The value to write to the buffer * @param val The value to write to the buffer
*/ */
void writeInt16Big(int16_t val) { void writeInt16Big(atInt16 val) {
utility::BigInt16(val); utility::BigInt16(val);
writeBytes(&val, sizeof(val)); writeBytes(&val, sizeof(val));
} }
void writeValBig(int16_t val) { writeInt16Big(val); } void writeValBig(atInt16 val) { writeInt16Big(val); }
/** @brief Writes an Uint16 to the buffer and advances the buffer. /** @brief Writes an Uint16 to the buffer and advances the buffer.
* It also swaps the bytes depending on the platform and Stream settings * It also swaps the bytes depending on the platform and Stream settings
* *
* @param val The value to write to the buffer * @param val The value to write to the buffer
*/ */
void writeUint16(uint16_t val) { writeInt16(val); } void writeUint16(atUint16 val) { writeInt16(val); }
void writeVal(uint16_t val) { writeUint16(val); } void writeVal(atUint16 val) { writeUint16(val); }
/** @brief Writes an Uint16 to the buffer and advances the buffer. /** @brief Writes an Uint16 to the buffer and advances the buffer.
* It also swaps the bytes against little depending on the platform * It also swaps the bytes against little depending on the platform
* *
* @param val The value to write to the buffer * @param val The value to write to the buffer
*/ */
void writeUint16Little(uint16_t val) { writeInt16Little(val); } void writeUint16Little(atUint16 val) { writeInt16Little(val); }
void writeValLittle(uint16_t val) { writeUint16Little(val); } void writeValLittle(atUint16 val) { writeUint16Little(val); }
/** @brief Writes an Uint16 to the buffer and advances the buffer. /** @brief Writes an Uint16 to the buffer and advances the buffer.
* It also swaps the bytes against big depending on the platform * It also swaps the bytes against big depending on the platform
* *
* @param val The value to write to the buffer * @param val The value to write to the buffer
*/ */
void writeUint16Big(uint16_t val) { writeInt16Big(val); } void writeUint16Big(atUint16 val) { writeInt16Big(val); }
void writeValBig(uint16_t val) { writeUint16Big(val); } void writeValBig(atUint16 val) { writeUint16Big(val); }
/** @brief Writes an Int32 to the buffer and advances the buffer. /** @brief Writes an Int32 to the buffer and advances the buffer.
* It also swaps the bytes depending on the platform and Stream settings. * It also swaps the bytes depending on the platform and Stream settings.
* *
* @param val The value to write to the buffer * @param val The value to write to the buffer
*/ */
void writeInt32(int32_t val) { void writeInt32(atInt32 val) {
if (m_endian == Endian::Big) { if (m_endian == Endian::Big) {
utility::BigInt32(val); utility::BigInt32(val);
} else { } else {
@@ -159,60 +159,60 @@ public:
} }
writeBytes(&val, sizeof(val)); writeBytes(&val, sizeof(val));
} }
void writeVal(int32_t val) { writeInt32(val); } void writeVal(atInt32 val) { writeInt32(val); }
/** @brief Writes an Int32 to the buffer and advances the buffer. /** @brief Writes an Int32 to the buffer and advances the buffer.
* It also swaps the bytes against little depending on the platform. * It also swaps the bytes against little depending on the platform.
* *
* @param val The value to write to the buffer * @param val The value to write to the buffer
*/ */
void writeInt32Little(int32_t val) { void writeInt32Little(atInt32 val) {
utility::LittleInt32(val); utility::LittleInt32(val);
writeBytes(&val, sizeof(val)); writeBytes(&val, sizeof(val));
} }
void writeValLittle(int32_t val) { writeInt32Little(val); } void writeValLittle(atInt32 val) { writeInt32Little(val); }
/** @brief Writes an Int32 to the buffer and advances the buffer. /** @brief Writes an Int32 to the buffer and advances the buffer.
* It also swaps the bytes against big depending on the platform. * It also swaps the bytes against big depending on the platform.
* *
* @param val The value to write to the buffer * @param val The value to write to the buffer
*/ */
void writeInt32Big(int32_t val) { void writeInt32Big(atInt32 val) {
utility::BigInt32(val); utility::BigInt32(val);
writeBytes(&val, sizeof(val)); writeBytes(&val, sizeof(val));
} }
void writeValBig(int32_t val) { writeInt32Big(val); } void writeValBig(atInt32 val) { writeInt32Big(val); }
/** @brief Writes an Uint32 to the buffer and advances the buffer. /** @brief Writes an Uint32 to the buffer and advances the buffer.
* It also swaps the bytes depending on the platform and Stream settings. * It also swaps the bytes depending on the platform and Stream settings.
* *
* @param val The value to write to the buffer * @param val The value to write to the buffer
*/ */
void writeUint32(uint32_t val) { writeInt32(val); } void writeUint32(atUint32 val) { writeInt32(val); }
void writeVal(uint32_t val) { writeUint32(val); } void writeVal(atUint32 val) { writeUint32(val); }
/** @brief Writes an Uint32 to the buffer and advances the buffer. /** @brief Writes an Uint32 to the buffer and advances the buffer.
* It also swaps the bytes against little depending on the platform. * It also swaps the bytes against little depending on the platform.
* *
* @param val The value to write to the buffer * @param val The value to write to the buffer
*/ */
void writeUint32Little(uint32_t val) { writeInt32Little(val); } void writeUint32Little(atUint32 val) { writeInt32Little(val); }
void writeValLittle(uint32_t val) { writeUint32Little(val); } void writeValLittle(atUint32 val) { writeUint32Little(val); }
/** @brief Writes an Uint32 to the buffer and advances the buffer. /** @brief Writes an Uint32 to the buffer and advances the buffer.
* It also swaps the bytes against big depending on the platform. * It also swaps the bytes against big depending on the platform.
* *
* @param val The value to write to the buffer * @param val The value to write to the buffer
*/ */
void writeUint32Big(uint32_t val) { writeInt32Big(val); } void writeUint32Big(atUint32 val) { writeInt32Big(val); }
void writeValBig(uint32_t val) { writeUint32Big(val); } void writeValBig(atUint32 val) { writeUint32Big(val); }
/** @brief Writes an Int64 to the buffer and advances the buffer. /** @brief Writes an Int64 to the buffer and advances the buffer.
* It also swaps the bytes depending on the platform and Stream settings. * It also swaps the bytes depending on the platform and Stream settings.
* *
* @param val The value to write to the buffer * @param val The value to write to the buffer
*/ */
void writeInt64(int64_t val) { void writeInt64(atInt64 val) {
if (m_endian == Endian::Big) { if (m_endian == Endian::Big) {
utility::BigInt64(val); utility::BigInt64(val);
} else { } else {
@@ -220,53 +220,53 @@ public:
} }
writeBytes(&val, sizeof(val)); writeBytes(&val, sizeof(val));
} }
void writeVal(int64_t val) { writeInt64(val); } void writeVal(atInt64 val) { writeInt64(val); }
/** @brief Writes an Int64 to the buffer and advances the buffer. /** @brief Writes an Int64 to the buffer and advances the buffer.
* It also swaps the bytes against little depending on the platform. * It also swaps the bytes against little depending on the platform.
* *
* @param val The value to write to the buffer * @param val The value to write to the buffer
*/ */
void writeInt64Little(int64_t val) { void writeInt64Little(atInt64 val) {
utility::LittleInt64(val); utility::LittleInt64(val);
writeBytes(&val, sizeof(val)); writeBytes(&val, sizeof(val));
} }
void writeValLittle(int64_t val) { writeInt64Little(val); } void writeValLittle(atInt64 val) { writeInt64Little(val); }
/** @brief Writes an Int64 to the buffer and advances the buffer. /** @brief Writes an Int64 to the buffer and advances the buffer.
* It also swaps the bytes against big depending on the platform. * It also swaps the bytes against big depending on the platform.
* *
* @param val The value to write to the buffer * @param val The value to write to the buffer
*/ */
void writeInt64Big(int64_t val) { void writeInt64Big(atInt64 val) {
utility::BigInt64(val); utility::BigInt64(val);
writeBytes(&val, sizeof(val)); writeBytes(&val, sizeof(val));
} }
void writeValBig(int64_t val) { writeInt64Big(val); } void writeValBig(atInt64 val) { writeInt64Big(val); }
/** @brief Writes an Uint64 to the buffer and advances the buffer. /** @brief Writes an Uint64 to the buffer and advances the buffer.
* It also swaps the bytes depending on the platform and Stream settings. * It also swaps the bytes depending on the platform and Stream settings.
* *
* @param val The value to write to the buffer * @param val The value to write to the buffer
*/ */
void writeUint64(uint64_t val) { writeInt64(val); } void writeUint64(atUint64 val) { writeInt64(val); }
void writeVal(uint64_t val) { writeUint64(val); } void writeVal(atUint64 val) { writeUint64(val); }
/** @brief Writes an Uint64 to the buffer and advances the buffer. /** @brief Writes an Uint64 to the buffer and advances the buffer.
* It also swaps the bytes against little depending on the platform. * It also swaps the bytes against little depending on the platform.
* *
* @param val The value to write to the buffer * @param val The value to write to the buffer
*/ */
void writeUint64Little(uint64_t val) { writeInt64Little(val); } void writeUint64Little(atUint64 val) { writeInt64Little(val); }
void writeValLittle(uint64_t val) { writeUint64Little(val); } void writeValLittle(atUint64 val) { writeUint64Little(val); }
/** @brief Writes an Uint64 to the buffer and advances the buffer. /** @brief Writes an Uint64 to the buffer and advances the buffer.
* It also swaps the bytes against big depending on the platform. * It also swaps the bytes against big depending on the platform.
* *
* @param val The value to write to the buffer * @param val The value to write to the buffer
*/ */
void writeUint64Big(uint64_t val) { writeInt64Big(val); } void writeUint64Big(atUint64 val) { writeInt64Big(val); }
void writeValBig(uint64_t val) { writeUint64Big(val); } void writeValBig(atUint64 val) { writeUint64Big(val); }
/** @brief Writes an float to the buffer and advances the buffer. /** @brief Writes an float to the buffer and advances the buffer.
* It also swaps the bytes depending on the platform and Stream settings. * It also swaps the bytes depending on the platform and Stream settings.
@@ -348,7 +348,7 @@ public:
* @param val The value to write to the buffer * @param val The value to write to the buffer
*/ */
void writeBool(bool val) { void writeBool(bool val) {
const auto u8Value = uint8_t(val); const auto u8Value = atUint8(val);
writeUBytes(&u8Value, sizeof(u8Value)); writeUBytes(&u8Value, sizeof(u8Value));
} }
void writeVal(bool val) { writeBool(val); } void writeVal(bool val) { writeBool(val); }
@@ -651,7 +651,7 @@ public:
* *
* Endianness is set with setEndian * Endianness is set with setEndian
*/ */
void writeStringAsWString(std::string_view str, int32_t fixedLen = -1) { void writeStringAsWString(std::string_view str, atInt32 fixedLen = -1) {
if (fixedLen == 0) if (fixedLen == 0)
return; return;
std::string tmpStr = std::string("\xEF\xBB\xBF") + str.data(); std::string tmpStr = std::string("\xEF\xBB\xBF") + str.data();
@@ -661,21 +661,21 @@ public:
utf8proc_int32_t wc; utf8proc_int32_t wc;
utf8proc_ssize_t len = utf8proc_iterate(buf, -1, &wc); utf8proc_ssize_t len = utf8proc_iterate(buf, -1, &wc);
if (len < 0) { if (len < 0) {
atWarning("invalid UTF-8 character while decoding"); atWarning(FMT_STRING("invalid UTF-8 character while decoding"));
return; return;
} }
buf += len; buf += len;
if (wc != 0xFEFF) if (wc != 0xFEFF)
writeUint16(uint16_t(wc)); writeUint16(atUint16(wc));
} }
writeUint16(0); writeUint16(0);
} else { } else {
for (int32_t i = 0; i < fixedLen; ++i) { for (atInt32 i = 0; i < fixedLen; ++i) {
utf8proc_int32_t wc = 0; utf8proc_int32_t wc = 0;
if (*buf) { if (*buf) {
utf8proc_ssize_t len = utf8proc_iterate(buf, -1, &wc); utf8proc_ssize_t len = utf8proc_iterate(buf, -1, &wc);
if (len < 0) { if (len < 0) {
atWarning("invalid UTF-8 character while decoding"); atWarning(FMT_STRING("invalid UTF-8 character while decoding"));
return; return;
} }
buf += len; buf += len;
@@ -686,7 +686,7 @@ public:
continue; continue;
} }
writeUint16(uint16_t(wc)); writeUint16(atUint16(wc));
} }
} }
} }
@@ -699,7 +699,7 @@ public:
* *
* Endianness is little * Endianness is little
*/ */
void writeStringAsWStringLittle(std::string_view str, int32_t fixedLen = -1) { void writeStringAsWStringLittle(std::string_view str, atInt32 fixedLen = -1) {
if (fixedLen == 0) if (fixedLen == 0)
return; return;
std::string tmpStr = std::string("\xEF\xBB\xBF") + str.data(); std::string tmpStr = std::string("\xEF\xBB\xBF") + str.data();
@@ -709,21 +709,21 @@ public:
utf8proc_int32_t wc; utf8proc_int32_t wc;
utf8proc_ssize_t len = utf8proc_iterate(buf, -1, &wc); utf8proc_ssize_t len = utf8proc_iterate(buf, -1, &wc);
if (len < 0) { if (len < 0) {
atWarning("invalid UTF-8 character while decoding"); atWarning(FMT_STRING("invalid UTF-8 character while decoding"));
return; return;
} }
buf += len; buf += len;
if (wc != 0xFEFF) if (wc != 0xFEFF)
writeUint16Little(uint16_t(wc)); writeUint16Little(atUint16(wc));
} }
writeUint16Little(0); writeUint16Little(0);
} else { } else {
for (int32_t i = 0; i < fixedLen; ++i) { for (atInt32 i = 0; i < fixedLen; ++i) {
utf8proc_int32_t wc = 0; utf8proc_int32_t wc = 0;
if (*buf) { if (*buf) {
utf8proc_ssize_t len = utf8proc_iterate(buf, -1, &wc); utf8proc_ssize_t len = utf8proc_iterate(buf, -1, &wc);
if (len < 0) { if (len < 0) {
atWarning("invalid UTF-8 character while decoding"); atWarning(FMT_STRING("invalid UTF-8 character while decoding"));
return; return;
} }
buf += len; buf += len;
@@ -734,7 +734,7 @@ public:
continue; continue;
} }
writeUint16Little(uint16_t(wc)); writeUint16Little(atUint16(wc));
} }
} }
} }
@@ -747,7 +747,7 @@ public:
* *
* Endianness is big * Endianness is big
*/ */
void writeStringAsWStringBig(std::string_view str, int32_t fixedLen = -1) { void writeStringAsWStringBig(std::string_view str, atInt32 fixedLen = -1) {
if (fixedLen == 0) if (fixedLen == 0)
return; return;
@@ -758,21 +758,21 @@ public:
utf8proc_int32_t wc; utf8proc_int32_t wc;
utf8proc_ssize_t len = utf8proc_iterate(buf, -1, &wc); utf8proc_ssize_t len = utf8proc_iterate(buf, -1, &wc);
if (len < 0) { if (len < 0) {
atWarning("invalid UTF-8 character while decoding"); atWarning(FMT_STRING("invalid UTF-8 character while decoding"));
return; return;
} }
buf += len; buf += len;
if (wc != 0xFEFF) if (wc != 0xFEFF)
writeUint16Big(uint16_t(wc)); writeUint16Big(atUint16(wc));
} }
writeUint16Big(0); writeUint16Big(0);
} else { } else {
for (int32_t i = 0; i < fixedLen; ++i) { for (atInt32 i = 0; i < fixedLen; ++i) {
utf8proc_int32_t wc = 0; utf8proc_int32_t wc = 0;
if (*buf) { if (*buf) {
utf8proc_ssize_t len = utf8proc_iterate(buf, -1, &wc); utf8proc_ssize_t len = utf8proc_iterate(buf, -1, &wc);
if (len < 0) { if (len < 0) {
atWarning("invalid UTF-8 character while decoding"); atWarning(FMT_STRING("invalid UTF-8 character while decoding"));
return; return;
} }
buf += len; buf += len;
@@ -783,7 +783,7 @@ public:
continue; continue;
} }
writeUint16Big(uint16_t(wc)); writeUint16Big(atUint16(wc));
} }
} }
} }
@@ -793,12 +793,12 @@ public:
* @param str The string to write to the buffer * @param str The string to write to the buffer
* @param fixedLen If not -1, the number of characters to zero-fill string to * @param fixedLen If not -1, the number of characters to zero-fill string to
*/ */
void writeString(std::string_view str, int32_t fixedLen = -1) { void writeString(std::string_view str, atInt32 fixedLen = -1) {
if (fixedLen == 0) if (fixedLen == 0)
return; return;
if (fixedLen < 0) { if (fixedLen < 0) {
for (uint8_t c : str) { for (atUint8 c : str) {
writeUByte(c); writeUByte(c);
if (c == '\0') if (c == '\0')
@@ -807,8 +807,8 @@ public:
writeUByte(0); writeUByte(0);
} else { } else {
auto it = str.begin(); auto it = str.begin();
for (int32_t i = 0; i < fixedLen; ++i) { for (atInt32 i = 0; i < fixedLen; ++i) {
uint8_t chr; atUint8 chr;
if (it == str.end()) if (it == str.end())
chr = 0; chr = 0;
else else
@@ -826,12 +826,12 @@ public:
* *
* Endianness is set with setEndian * Endianness is set with setEndian
*/ */
void writeWString(std::wstring_view str, int32_t fixedLen = -1) { void writeWString(std::wstring_view str, atInt32 fixedLen = -1) {
if (fixedLen == 0) if (fixedLen == 0)
return; return;
if (fixedLen < 0) { if (fixedLen < 0) {
for (uint16_t c : str) { for (atUint16 c : str) {
writeUint16(c); writeUint16(c);
if (c == L'\0') if (c == L'\0')
@@ -840,8 +840,8 @@ public:
writeUint16(0); writeUint16(0);
} else { } else {
auto it = str.begin(); auto it = str.begin();
for (int32_t i = 0; i < fixedLen; ++i) { for (atInt32 i = 0; i < fixedLen; ++i) {
uint16_t chr; atUint16 chr;
if (it == str.end()) if (it == str.end())
chr = 0; chr = 0;
else else
@@ -859,12 +859,12 @@ public:
* *
* Endianness is little * Endianness is little
*/ */
void writeWStringLittle(std::wstring_view str, int32_t fixedLen = -1) { void writeWStringLittle(std::wstring_view str, atInt32 fixedLen = -1) {
if (fixedLen == 0) if (fixedLen == 0)
return; return;
if (fixedLen < 0) { if (fixedLen < 0) {
for (uint16_t c : str) { for (atUint16 c : str) {
writeUint16Little(c); writeUint16Little(c);
if (c == L'\0') if (c == L'\0')
@@ -873,8 +873,8 @@ public:
writeUint16Little(0); writeUint16Little(0);
} else { } else {
auto it = str.begin(); auto it = str.begin();
for (int32_t i = 0; i < fixedLen; ++i) { for (atInt32 i = 0; i < fixedLen; ++i) {
uint16_t chr; atUint16 chr;
if (it == str.end()) if (it == str.end())
chr = 0; chr = 0;
else else
@@ -892,7 +892,7 @@ public:
* *
* Endianness is big * Endianness is big
*/ */
void writeWStringBig(std::wstring_view str, int32_t fixedLen = -1) { void writeWStringBig(std::wstring_view str, atInt32 fixedLen = -1) {
if (fixedLen == 0) if (fixedLen == 0)
return; return;
@@ -906,7 +906,7 @@ public:
writeUint16Big(0); writeUint16Big(0);
} else { } else {
auto it = str.begin(); auto it = str.begin();
for (int32_t i = 0; i < fixedLen; ++i) { for (atInt32 i = 0; i < fixedLen; ++i) {
wchar_t chr; wchar_t chr;
if (it == str.end()) if (it == str.end())
chr = 0; chr = 0;
@@ -925,7 +925,7 @@ public:
* *
* Endianness is big * Endianness is big
*/ */
void writeU16StringBig(std::u16string_view str, int32_t fixedLen = -1) { void writeU16StringBig(std::u16string_view str, atInt32 fixedLen = -1) {
if (fixedLen == 0) if (fixedLen == 0)
return; return;
@@ -939,7 +939,7 @@ public:
writeUint16Big(0); writeUint16Big(0);
} else { } else {
auto it = str.begin(); auto it = str.begin();
for (int32_t i = 0; i < fixedLen; ++i) { for (atInt32 i = 0; i < fixedLen; ++i) {
char16_t chr; char16_t chr;
if (it == str.end()) if (it == str.end())
chr = 0; chr = 0;
@@ -958,7 +958,7 @@ public:
* *
* Endianness is big * Endianness is big
*/ */
void writeU32StringBig(std::u32string_view str, int32_t fixedLen = -1) { void writeU32StringBig(std::u32string_view str, atInt32 fixedLen = -1) {
if (fixedLen == 0) if (fixedLen == 0)
return; return;
@@ -972,7 +972,7 @@ public:
writeUint32Big(0); writeUint32Big(0);
} else { } else {
auto it = str.begin(); auto it = str.begin();
for (int32_t i = 0; i < fixedLen; ++i) { for (atInt32 i = 0; i < fixedLen; ++i) {
char32_t chr; char32_t chr;
if (it == str.end()) if (it == str.end())
chr = 0; chr = 0;
@@ -984,15 +984,15 @@ public:
} }
void writeValBig(std::u32string_view val) { writeU32StringBig(val); } void writeValBig(std::u32string_view val) { writeU32StringBig(val); }
void fill(uint8_t val, uint64_t length) { void fill(atUint8 val, atUint64 length) {
if (length == 0) if (length == 0)
return; return;
const std::vector<uint8_t> tmp(length, val); const std::vector<atUint8> tmp(length, val);
writeUBytes(tmp.data(), length); writeUBytes(tmp.data(), length);
} }
void fill(int8_t val, uint64_t length) { fill((uint8_t)val, length); } void fill(atInt8 val, atUint64 length) { fill((atUint8)val, length); }
/** @brief Performs automatic std::vector enumeration writes using numeric type T /** @brief Performs automatic std::vector enumeration writes using numeric type T
* @param vector The std::vector read from when writing data * @param vector The std::vector read from when writing data

View File

@@ -19,7 +19,7 @@ public:
MCFile(); MCFile();
static uint8_t* unscramble(uint8_t* data, uint64_t length); static atUint8* unscramble(atUint8* data, atUint64 length);
private: private:
MCSlot* m_slots[3]; MCSlot* m_slots[3];

View File

@@ -23,7 +23,7 @@ public:
* \param data The existing buffer * \param data The existing buffer
* \param length The length of the existing buffer * \param length The length of the existing buffer
*/ */
MCFileReader(uint8_t*, uint64_t); MCFileReader(atUint8*, atUint64);
/*! /*!
* \brief This constructor creates an instance from a file on disk. * \brief This constructor creates an instance from a file on disk.

View File

@@ -24,7 +24,7 @@ public:
* \param data The existing buffer * \param data The existing buffer
* \param length The length of the existing buffer * \param length The length of the existing buffer
*/ */
MCFileWriter(uint8_t*, uint64_t); MCFileWriter(atUint8*, atUint64);
/*! /*!
* \brief This constructor creates an instance from a file on disk. * \brief This constructor creates an instance from a file on disk.
@@ -40,10 +40,10 @@ public:
*/ */
void writeFile(MCFile* file); void writeFile(MCFile* file);
static uint16_t calculateChecksum(uint8_t* data, uint32_t length); static atUint16 calculateChecksum(atUint8* data, atUint32 length);
private: private:
uint16_t calculateSlotChecksum(uint32_t game); atUint16 calculateSlotChecksum(atUint32 game);
}; };
} // namespace io } // namespace io

View File

@@ -6,7 +6,7 @@
namespace athena { namespace athena {
class MCSlot : public ZQuestFile { class MCSlot : public ZQuestFile {
public: public:
MCSlot(std::unique_ptr<uint8_t[]>&& data, uint32_t length); MCSlot(std::unique_ptr<atUint8[]>&& data, atUint32 length);
}; };
} // namespace athena } // namespace athena

View File

@@ -28,26 +28,26 @@ public:
* \param takeOwnership Memory will be freed with the reader if set. * \param takeOwnership Memory will be freed with the reader if set.
* \param globalErr Whether or not global errors are enabled. * \param globalErr Whether or not global errors are enabled.
*/ */
explicit MemoryReader(const void* data, uint64_t length, bool takeOwnership = false, bool globalErr = true); explicit MemoryReader(const void* data, atUint64 length, bool takeOwnership = false, bool globalErr = true);
/*! \brief Sets the buffers position relative to the specified position.<br /> /*! \brief Sets the buffers position relative to the specified position.<br />
* It seeks relative to the current position by default. * It seeks relative to the current position by default.
* \param position where in the buffer to seek * \param position where in the buffer to seek
* \param origin The Origin to seek \sa SeekOrigin * \param origin The Origin to seek \sa SeekOrigin
*/ */
void seek(int64_t position, SeekOrigin origin = SeekOrigin::Current) override; void seek(atInt64 position, SeekOrigin origin = SeekOrigin::Current) override;
/*! \brief Returns the current position in the stream. /*! \brief Returns the current position in the stream.
* *
* \return Int64 The current position in the stream. * \return Int64 The current position in the stream.
*/ */
uint64_t position() const override { return m_position; } atUint64 position() const override { return m_position; }
/*! \brief Returns whether or not the stream is at the end. /*! \brief Returns whether or not the stream is at the end.
* *
* \return bool True if at end; False otherwise. * \return bool True if at end; False otherwise.
*/ */
uint64_t length() const override { return m_length; } atUint64 length() const override { return m_length; }
/*! \brief Sets the buffer to the given one, deleting the current one.<br /> /*! \brief Sets the buffer to the given one, deleting the current one.<br />
* <b>BEWARE:</b> As this deletes the current buffer it WILL cause a loss of data * <b>BEWARE:</b> As this deletes the current buffer it WILL cause a loss of data
@@ -59,7 +59,7 @@ public:
* \param takeOwnership Memory will be freed with the reader if set * \param takeOwnership Memory will be freed with the reader if set
* \throw IOException * \throw IOException
*/ */
void setData(const uint8_t* data, uint64_t length, bool takeOwnership = false); void setData(const atUint8* data, atUint64 length, bool takeOwnership = false);
/*! \brief Returns a copy of the current buffer.<br /> /*! \brief Returns a copy of the current buffer.<br />
* Changes to the copy do not affect the buffer so it's perfectly safe to * Changes to the copy do not affect the buffer so it's perfectly safe to
@@ -68,19 +68,19 @@ public:
* as Stream now owns the address, this is done to keep memory usage down. * as Stream now owns the address, this is done to keep memory usage down.
* \return Uint8* The copy of the buffer. * \return Uint8* The copy of the buffer.
*/ */
uint8_t* data() const; atUint8* data() const;
/*! \brief Reads a specified number of bytes to user-allocated buffer /*! \brief Reads a specified number of bytes to user-allocated buffer
* \param buf User-allocated buffer pointer * \param buf User-allocated buffer pointer
* \param len Length to read * \param len Length to read
* \return Number of bytes read * \return Number of bytes read
*/ */
uint64_t readUBytesToBuf(void* buf, uint64_t len) override; atUint64 readUBytesToBuf(void* buf, atUint64 len) override;
protected: protected:
const void* m_data = nullptr; const void* m_data = nullptr;
uint64_t m_length = 0; atUint64 m_length = 0;
uint64_t m_position = 0; atUint64 m_position = 0;
bool m_owns = false; bool m_owns = false;
bool m_globalErr = true; bool m_globalErr = true;
}; };
@@ -92,7 +92,7 @@ public:
* \param data The existing buffer * \param data The existing buffer
* \param length The length of the existing buffer * \param length The length of the existing buffer
*/ */
explicit MemoryCopyReader(const void* data, uint64_t length); explicit MemoryCopyReader(const void* data, atUint64 length);
/*! \brief This constructor creates an instance from a file on disk. /*! \brief This constructor creates an instance from a file on disk.
* *
@@ -100,11 +100,11 @@ public:
*/ */
explicit MemoryCopyReader(const std::string& filename) : m_filepath(filename) { loadData(); } explicit MemoryCopyReader(const std::string& filename) : m_filepath(filename) { loadData(); }
void setData(const uint8_t* data, uint64_t length); void setData(const atUint8* data, atUint64 length);
protected: protected:
void loadData(); void loadData();
std::unique_ptr<uint8_t[]> m_dataCopy; std::unique_ptr<atUint8[]> m_dataCopy;
std::string m_filepath; //!< Path to the target file std::string m_filepath; //!< Path to the target file
}; };

View File

@@ -26,26 +26,26 @@ public:
* @param takeOwnership Whether or not this writer takes ownership of the supplied data buffer. * @param takeOwnership Whether or not this writer takes ownership of the supplied data buffer.
* If true, the buffer will be deleted by this when the destructor executes. * If true, the buffer will be deleted by this when the destructor executes.
*/ */
explicit MemoryWriter(uint8_t* data, uint64_t length, bool takeOwnership = false); explicit MemoryWriter(atUint8* data, atUint64 length, bool takeOwnership = false);
/*! @brief Sets the buffers position relative to the specified position.<br /> /*! @brief Sets the buffers position relative to the specified position.<br />
* It seeks relative to the current position by default. * It seeks relative to the current position by default.
* @param position where in the buffer to seek * @param position where in the buffer to seek
* @param origin The Origin to seek @sa SeekOrigin * @param origin The Origin to seek @sa SeekOrigin
*/ */
void seek(int64_t position, SeekOrigin origin = SeekOrigin::Current) override; void seek(atInt64 position, SeekOrigin origin = SeekOrigin::Current) override;
/*! @brief Returns the current position in the stream. /*! @brief Returns the current position in the stream.
* *
* @return Int64 The current position in the stream. * @return Int64 The current position in the stream.
*/ */
uint64_t position() const override { return m_position; } atUint64 position() const override { return m_position; }
/*! @brief Returns the length of the stream. /*! @brief Returns the length of the stream.
* *
* @return Int64 The length of the stream. * @return Int64 The length of the stream.
*/ */
uint64_t length() const override { return m_length; } atUint64 length() const override { return m_length; }
bool isOpen() const { return true; } bool isOpen() const { return true; }
@@ -54,14 +54,14 @@ public:
* @param length The length of the new buffer. * @param length The length of the new buffer.
* @param takeOwnership Whether the Stream now owns the buffer. * @param takeOwnership Whether the Stream now owns the buffer.
*/ */
void setData(uint8_t* data, uint64_t length, bool takeOwnership = false); void setData(atUint8* data, atUint64 length, bool takeOwnership = false);
/*! @brief Returns a copy of the current buffer.<br /> /*! @brief Returns a copy of the current buffer.<br />
* Changes to the copy do not affect the buffer so it's perfectly safe to * Changes to the copy do not affect the buffer so it's perfectly safe to
* directly edit the buffer and use setData to set the new information.<br /> * directly edit the buffer and use setData to set the new information.<br />
* @return Uint8* The copy of the buffer. * @return Uint8* The copy of the buffer.
*/ */
uint8_t* data() const; atUint8* data() const;
/*! @brief Sets the target file /*! @brief Sets the target file
* *
@@ -87,13 +87,13 @@ public:
* @param data The buffer to write * @param data The buffer to write
* @param length The amount to write * @param length The amount to write
*/ */
void writeUBytes(const uint8_t* data, uint64_t length) override; void writeUBytes(const atUint8* data, atUint64 length) override;
protected: protected:
MemoryWriter() = default; MemoryWriter() = default;
uint8_t* m_data = nullptr; atUint8* m_data = nullptr;
uint64_t m_length = 0; atUint64 m_length = 0;
uint64_t m_position = 0; atUint64 m_position = 0;
bool m_bufferOwned = false; bool m_bufferOwned = false;
std::string m_filepath; //!< Path to the target file std::string m_filepath; //!< Path to the target file
}; };
@@ -105,7 +105,7 @@ public:
* @param data The existing buffer * @param data The existing buffer
* @param length The length of the existing buffer * @param length The length of the existing buffer
*/ */
explicit MemoryCopyWriter(uint8_t* data = nullptr, uint64_t length = 0x10); explicit MemoryCopyWriter(atUint8* data = nullptr, atUint64 length = 0x10);
/*! @brief This constructor creates an instance from a file on disk. /*! @brief This constructor creates an instance from a file on disk.
* *
@@ -118,7 +118,7 @@ public:
* @param position where in the buffer to seek * @param position where in the buffer to seek
* @param origin The Origin to seek @sa SeekOrigin * @param origin The Origin to seek @sa SeekOrigin
*/ */
void seek(int64_t position, SeekOrigin origin = SeekOrigin::Current) override; void seek(atInt64 position, SeekOrigin origin = SeekOrigin::Current) override;
/*! @brief Sets the buffer to the given one, deleting the current one.<br /> /*! @brief Sets the buffer to the given one, deleting the current one.<br />
* <b>BEWARE:</b> As this deletes the current buffer it WILL cause a loss of data * <b>BEWARE:</b> As this deletes the current buffer it WILL cause a loss of data
@@ -129,7 +129,7 @@ public:
* @param length The length of the new buffer. * @param length The length of the new buffer.
* @throw IOException * @throw IOException
*/ */
void setData(const uint8_t* data, uint64_t length); void setData(const atUint8* data, atUint64 length);
/*! @brief Writes the given buffer with the specified length, buffers can be bigger than the length /*! @brief Writes the given buffer with the specified length, buffers can be bigger than the length
* however it's undefined behavior to try and write a buffer which is smaller than the given length. * however it's undefined behavior to try and write a buffer which is smaller than the given length.
@@ -137,13 +137,13 @@ public:
* @param data The buffer to write * @param data The buffer to write
* @param length The amount to write * @param length The amount to write
*/ */
void writeUBytes(const uint8_t* data, uint64_t length) override; void writeUBytes(const atUint8* data, atUint64 length) override;
protected: protected:
std::unique_ptr<uint8_t[]> m_dataCopy; std::unique_ptr<atUint8[]> m_dataCopy;
private: private:
void resize(uint64_t newSize); void resize(atUint64 newSize);
}; };
} // namespace athena::io } // namespace athena::io

View File

@@ -19,7 +19,7 @@ public:
~SkywardSwordFile(); ~SkywardSwordFile();
void addQuest(SkywardSwordQuest* q); void addQuest(SkywardSwordQuest* q);
SkywardSwordQuest* quest(uint32_t id); SkywardSwordQuest* quest(atUint32 id);
std::vector<SkywardSwordQuest*> questList() const; std::vector<SkywardSwordQuest*> questList() const;
void setRegion(Region region); void setRegion(Region region);
@@ -29,7 +29,7 @@ private:
Region m_region; Region m_region;
// A vector is a bit overkill // A vector is a bit overkill
std::vector<SkywardSwordQuest*> m_quests; std::vector<SkywardSwordQuest*> m_quests;
uint32_t m_numQuests; atUint32 m_numQuests;
}; };
} // namespace athena } // namespace athena

View File

@@ -7,7 +7,7 @@ class SkywardSwordFile;
namespace io { namespace io {
class SkywardSwordFileReader : public MemoryCopyReader { class SkywardSwordFileReader : public MemoryCopyReader {
public: public:
SkywardSwordFileReader(uint8_t* data, uint64_t length); SkywardSwordFileReader(atUint8* data, atUint64 length);
SkywardSwordFileReader(const std::string& filename); SkywardSwordFileReader(const std::string& filename);
SkywardSwordFile* read(); SkywardSwordFile* read();

View File

@@ -9,7 +9,7 @@ namespace io {
class SkywardSwordFileWriter : public MemoryCopyWriter { class SkywardSwordFileWriter : public MemoryCopyWriter {
public: public:
SkywardSwordFileWriter(uint8_t* data, uint64_t len); SkywardSwordFileWriter(atUint8* data, atUint64 len);
SkywardSwordFileWriter(const std::string& filename); SkywardSwordFileWriter(const std::string& filename);
void write(SkywardSwordFile* file); void write(SkywardSwordFile* file);

View File

@@ -11,40 +11,40 @@ class SkywardSwordQuest : public ZQuestFile {
public: public:
enum AmmoType { Arrows, Bombs, Seeds }; enum AmmoType { Arrows, Bombs, Seeds };
SkywardSwordQuest(std::unique_ptr<uint8_t[]>&& data, uint32_t len); SkywardSwordQuest(std::unique_ptr<atUint8[]>&& data, atUint32 len);
void setPlayerName(const std::string& name); void setPlayerName(const std::string& name);
std::string playerName() const; std::string playerName() const;
void setRupeeCount(uint16_t value); void setRupeeCount(atUint16 value);
uint16_t rupeeCount(); atUint16 rupeeCount();
void setAmmoCount(AmmoType type, uint32_t count); void setAmmoCount(AmmoType type, atUint32 count);
uint32_t ammoCount(AmmoType type); atUint32 ammoCount(AmmoType type);
void setMaxHP(uint16_t val); void setMaxHP(atUint16 val);
uint16_t maxHP(); atUint16 maxHP();
float maxHearts(); float maxHearts();
void setSpawnHP(uint16_t val); void setSpawnHP(atUint16 val);
uint16_t spawnHP(); atUint16 spawnHP();
float spawnHearts(); float spawnHearts();
void setCurrentHP(uint16_t val); void setCurrentHP(atUint16 val);
uint16_t currentHP(); atUint16 currentHP();
float currentHearts(); float currentHearts();
std::string currentLocation(); std::string currentLocation();
std::string currentArea(); std::string currentArea();
std::string currentLocationCopy(); std::string currentLocationCopy();
void setSkipData(std::unique_ptr<uint8_t[]>&& data); void setSkipData(std::unique_ptr<atUint8[]>&& data);
uint8_t* skipData() const; atUint8* skipData() const;
uint32_t slotChecksum(); atUint32 slotChecksum();
uint32_t skipChecksum(); atUint32 skipChecksum();
void fixChecksums(); void fixChecksums();
void setNew(bool isNew); void setNew(bool isNew);
bool isNew() const; bool isNew() const;
private: private:
std::unique_ptr<uint8_t[]> m_skipData; std::unique_ptr<atUint8[]> m_skipData;
}; };
} // namespace athena } // namespace athena

View File

@@ -30,23 +30,23 @@ public:
int stateId(int index) const; int stateId(int index) const;
void setStateIds(std::vector<int> ids); void setStateIds(std::vector<int> ids);
std::vector<int> stateIds() const; std::vector<int> stateIds() const;
uint32_t stateCount() const; atUint32 stateCount() const;
void setCurrentState(uint32_t id); void setCurrentState(atUint32 id);
uint32_t currentState() const; atUint32 currentState() const;
bool addFrame(SpriteFrame* Frame); bool addFrame(SpriteFrame* Frame);
bool removeFrame(SpriteFrame* Frame); bool removeFrame(SpriteFrame* Frame);
SpriteFrame* Frame(uint32_t id); SpriteFrame* Frame(atUint32 id);
void setFrame(uint32_t id); void setFrame(atUint32 id);
void setFrames(std::vector<SpriteFrame*> frames); void setFrames(std::vector<SpriteFrame*> frames);
uint32_t frameCount() const; atUint32 frameCount() const;
std::vector<SpriteFrame*> frames() const; std::vector<SpriteFrame*> frames() const;
SpriteFile* container() const; SpriteFile* container() const;
void setCurrentFrame(SpriteFrame* frame); void setCurrentFrame(SpriteFrame* frame);
void setCurrentFrame(uint32_t id); void setCurrentFrame(atUint32 id);
SpriteFrame* currentFrame() const; SpriteFrame* currentFrame() const;
void advanceFrame(); void advanceFrame();
@@ -61,8 +61,8 @@ private:
Vector2Df m_position; Vector2Df m_position;
std::vector<int> m_stateIds; //!< Stores the texture id's for each state. std::vector<int> m_stateIds; //!< Stores the texture id's for each state.
std::vector<SpriteFrame*> m_frames; std::vector<SpriteFrame*> m_frames;
uint32_t m_currentState; atUint32 m_currentState;
uint32_t m_currentFrame; atUint32 m_currentFrame;
}; };
} // namespace athena::Sakura } // namespace athena::Sakura

View File

@@ -19,32 +19,32 @@ public:
/*! /*!
* \brief Major * \brief Major
*/ */
static const uint32_t Major; static const atUint32 Major;
/*! /*!
* \brief Minor * \brief Minor
*/ */
static const uint32_t Minor; static const atUint32 Minor;
/*! /*!
* \brief Revision * \brief Revision
*/ */
static const uint32_t Revision; static const atUint32 Revision;
/*! /*!
* \brief Patch * \brief Patch
*/ */
static const uint32_t Build; static const atUint32 Build;
/*! /*!
* \brief Version * \brief Version
*/ */
static const uint32_t Version; static const atUint32 Version;
/*! /*!
* \brief Magic * \brief Magic
*/ */
static const uint32_t Magic; static const atUint32 Magic;
/*! /*!
* \brief SSprite * \brief SSprite
@@ -58,7 +58,7 @@ public:
* \param originX * \param originX
* \param originY * \param originY
*/ */
SpriteFile(uint32_t width, uint32_t height, float originX, float originY); SpriteFile(atUint32 width, atUint32 height, float originX, float originY);
/*! /*!
* \brief SSpriteFile * \brief SSpriteFile
@@ -84,7 +84,7 @@ public slots:
* \param width * \param width
* \param height * \param height
*/ */
void setSize(uint32_t width, uint32_t height); void setSize(atUint32 width, atUint32 height);
/*! /*!
* \brief setSize * \brief setSize
@@ -102,13 +102,13 @@ public slots:
* \brief width * \brief width
* \return * \return
*/ */
uint32_t width() const; atUint32 width() const;
/*! /*!
* \brief height * \brief height
* \return * \return
*/ */
uint32_t height() const; atUint32 height() const;
/*! /*!
* \brief setOrigin * \brief setOrigin
@@ -158,10 +158,10 @@ public slots:
* \param id * \param id
* \return * \return
*/ */
STexture* texture(uint32_t id); STexture* texture(atUint32 id);
std::vector<STexture*> textures() const; std::vector<STexture*> textures() const;
uint32_t textureCount() const; atUint32 textureCount() const;
/*! /*!
* \brief setTextures * \brief setTextures
* \param textures * \param textures
@@ -177,7 +177,7 @@ public slots:
Sprite* sprite(const std::string& name); Sprite* sprite(const std::string& name);
std::unordered_map<std::string, Sprite*> sprites() const; std::unordered_map<std::string, Sprite*> sprites() const;
uint32_t spriteCount() const; atUint32 spriteCount() const;
private: private:
std::vector<STexture*> m_textures; std::vector<STexture*> m_textures;

View File

@@ -11,7 +11,7 @@ namespace io {
class SpriteFileReader : public MemoryCopyReader { class SpriteFileReader : public MemoryCopyReader {
public: public:
SpriteFileReader(uint8_t* data, uint64_t length); SpriteFileReader(atUint8* data, atUint64 length);
SpriteFileReader(const std::string& filepath); SpriteFileReader(const std::string& filepath);
Sakura::SpriteFile* readFile(); Sakura::SpriteFile* readFile();

View File

@@ -11,7 +11,7 @@ namespace io {
class SpriteFileWriter : public MemoryCopyWriter { class SpriteFileWriter : public MemoryCopyWriter {
public: public:
SpriteFileWriter(uint8_t* data, uint64_t length); SpriteFileWriter(atUint8* data, atUint64 length);
SpriteFileWriter(std::string_view filepath); SpriteFileWriter(std::string_view filepath);

View File

@@ -31,7 +31,7 @@ public:
void setParts(std::vector<SpritePart*> parts); void setParts(std::vector<SpritePart*> parts);
std::vector<SpritePart*> parts() const; std::vector<SpritePart*> parts() const;
uint32_t partCount() const; atUint32 partCount() const;
void setRoot(Sprite* root); void setRoot(Sprite* root);
Sprite* root() const; Sprite* root() const;

View File

@@ -56,7 +56,7 @@ public:
* \param width * \param width
* \param height * \param height
*/ */
void setSize(uint32_t width, uint32_t height); void setSize(atUint32 width, atUint32 height);
/*! /*!
* \brief setSize * \brief setSize
@@ -105,6 +105,6 @@ private:
Vector2Di m_size; Vector2Di m_size;
bool m_flippedH; bool m_flippedH;
bool m_flippedV; bool m_flippedV;
uint32_t m_frameIndex; atUint32 m_frameIndex;
}; };
} // namespace athena::Sakura } // namespace athena::Sakura

View File

@@ -3,6 +3,15 @@
#include <cinttypes> #include <cinttypes>
#include <cstdint> #include <cstdint>
using atInt8 = std::int8_t;
using atUint8 = std::uint8_t;
using atInt16 = std::int16_t;
using atUint16 = std::uint16_t;
using atInt32 = std::int32_t;
using atUint32 = std::uint32_t;
using atInt64 = std::int64_t;
using atUint64 = std::uint64_t;
// Vector types // Vector types
#include "simd/simd.hpp" #include "simd/simd.hpp"
struct atVec2f { struct atVec2f {

View File

@@ -10,7 +10,7 @@
#include "athena/Types.hpp" #include "athena/Types.hpp"
namespace athena::utility { namespace athena::utility {
inline bool isEmpty(int8_t* buf, uint32_t size) { return !std::memcmp(buf, buf + 1, size - 1); } inline bool isEmpty(atInt8* buf, atUint32 size) { return !std::memcmp(buf, buf + 1, size - 1); }
#if _WIN32 #if _WIN32
constexpr bool isSystemBigEndian() { return false; } constexpr bool isSystemBigEndian() { return false; }
#else #else
@@ -25,7 +25,7 @@ constexpr ::athena::Endian NotSystemEndian = isSystemBigEndian() ? ::athena::End
#define BSWAP_CONSTEXPR constexpr #define BSWAP_CONSTEXPR constexpr
#endif #endif
BSWAP_CONSTEXPR int16_t swap16(int16_t val) { BSWAP_CONSTEXPR atInt16 swap16(atInt16 val) {
#if __GNUC__ #if __GNUC__
return __builtin_bswap16(val); return __builtin_bswap16(val);
#elif _MSC_VER #elif _MSC_VER
@@ -34,8 +34,8 @@ BSWAP_CONSTEXPR int16_t swap16(int16_t val) {
return (val = (val << 8) | ((val >> 8) & 0xFF)); return (val = (val << 8) | ((val >> 8) & 0xFF));
#endif #endif
} }
BSWAP_CONSTEXPR uint16_t swapU16(uint16_t val) { return (uint16_t)swap16(val); } BSWAP_CONSTEXPR atUint16 swapU16(atUint16 val) { return (atUint16)swap16(val); }
BSWAP_CONSTEXPR int32_t swap32(int32_t val) { BSWAP_CONSTEXPR atInt32 swap32(atInt32 val) {
#if __GNUC__ #if __GNUC__
return __builtin_bswap32(val); return __builtin_bswap32(val);
#elif _MSC_VER #elif _MSC_VER
@@ -46,8 +46,8 @@ BSWAP_CONSTEXPR int32_t swap32(int32_t val) {
return val; return val;
#endif #endif
} }
BSWAP_CONSTEXPR uint32_t swapU32(uint32_t val) { return (uint32_t)swap32(val); } BSWAP_CONSTEXPR atUint32 swapU32(atUint32 val) { return (atUint32)swap32(val); }
BSWAP_CONSTEXPR int64_t swap64(int64_t val) { BSWAP_CONSTEXPR atInt64 swap64(atInt64 val) {
#if __GNUC__ #if __GNUC__
return __builtin_bswap64(val); return __builtin_bswap64(val);
#elif _MSC_VER #elif _MSC_VER
@@ -60,90 +60,90 @@ BSWAP_CONSTEXPR int64_t swap64(int64_t val) {
(((atInt64)(val)&0x000000000000FF00ULL) << 40) | (((atInt64)(val)&0x00000000000000FFULL) << 56)))); (((atInt64)(val)&0x000000000000FF00ULL) << 40) | (((atInt64)(val)&0x00000000000000FFULL) << 56))));
#endif #endif
} }
BSWAP_CONSTEXPR uint64_t swapU64(uint64_t val) { return (uint64_t)swap64(val); } BSWAP_CONSTEXPR atUint64 swapU64(atUint64 val) { return (atUint64)swap64(val); }
BSWAP_CONSTEXPR float swapFloat(float val) { BSWAP_CONSTEXPR float swapFloat(float val) {
union { float f; int32_t i; } uval1 = {val}; union { float f; atInt32 i; } uval1 = {val};
union { int32_t i; float f; } uval2 = {swap32(uval1.i)}; union { atInt32 i; float f; } uval2 = {swap32(uval1.i)};
return uval2.f; return uval2.f;
} }
BSWAP_CONSTEXPR double swapDouble(double val) { BSWAP_CONSTEXPR double swapDouble(double val) {
union { double f; int64_t i; } uval1 = {val}; union { double f; atInt64 i; } uval1 = {val};
union { int64_t i; double f; } uval2 = {swap64(uval1.i)}; union { atInt64 i; double f; } uval2 = {swap64(uval1.i)};
return uval2.f; return uval2.f;
} }
BSWAP_CONSTEXPR int16_t LittleInt16(int16_t& val) { BSWAP_CONSTEXPR atInt16 LittleInt16(atInt16& val) {
if constexpr (athena::utility::isSystemBigEndian()) if constexpr (athena::utility::isSystemBigEndian())
val = athena::utility::swap16(val); val = athena::utility::swap16(val);
return val; return val;
} }
BSWAP_CONSTEXPR uint16_t LittleUint16(uint16_t& val) { BSWAP_CONSTEXPR atUint16 LittleUint16(atUint16& val) {
int16_t ret = val; atInt16 ret = val;
LittleInt16(ret); LittleInt16(ret);
val = ret; val = ret;
return val; return val;
} }
BSWAP_CONSTEXPR int16_t BigInt16(int16_t& val) { BSWAP_CONSTEXPR atInt16 BigInt16(atInt16& val) {
if constexpr (!athena::utility::isSystemBigEndian()) if constexpr (!athena::utility::isSystemBigEndian())
val = athena::utility::swap16(val); val = athena::utility::swap16(val);
return val; return val;
} }
BSWAP_CONSTEXPR uint16_t BigUint16(uint16_t& val) { BSWAP_CONSTEXPR atUint16 BigUint16(atUint16& val) {
int16_t ret = val; atInt16 ret = val;
BigInt16(ret); BigInt16(ret);
val = ret; val = ret;
return val; return val;
} }
BSWAP_CONSTEXPR int32_t LittleInt32(int32_t& val) { BSWAP_CONSTEXPR atInt32 LittleInt32(atInt32& val) {
if constexpr (athena::utility::isSystemBigEndian()) if constexpr (athena::utility::isSystemBigEndian())
val = athena::utility::swap32(val); val = athena::utility::swap32(val);
return val; return val;
} }
BSWAP_CONSTEXPR uint32_t LittleUint32(uint32_t& val) { BSWAP_CONSTEXPR atUint32 LittleUint32(atUint32& val) {
int32_t ret = val; atInt32 ret = val;
LittleInt32(ret); LittleInt32(ret);
val = ret; val = ret;
return val; return val;
} }
BSWAP_CONSTEXPR int32_t BigInt32(int32_t& val) { BSWAP_CONSTEXPR atInt32 BigInt32(atInt32& val) {
if constexpr (!athena::utility::isSystemBigEndian()) if constexpr (!athena::utility::isSystemBigEndian())
val = athena::utility::swap32(val); val = athena::utility::swap32(val);
return val; return val;
} }
BSWAP_CONSTEXPR uint32_t BigUint32(uint32_t& val) { BSWAP_CONSTEXPR atUint32 BigUint32(atUint32& val) {
int32_t ret = val; atInt32 ret = val;
BigInt32(ret); BigInt32(ret);
val = ret; val = ret;
return val; return val;
} }
BSWAP_CONSTEXPR int64_t LittleInt64(int64_t& val) { BSWAP_CONSTEXPR atInt64 LittleInt64(atInt64& val) {
if constexpr (athena::utility::isSystemBigEndian()) if constexpr (athena::utility::isSystemBigEndian())
val = athena::utility::swap64(val); val = athena::utility::swap64(val);
return val; return val;
} }
BSWAP_CONSTEXPR uint64_t LittleUint64(uint64_t& val) { BSWAP_CONSTEXPR atUint64 LittleUint64(atUint64& val) {
int64_t ret = val; atInt64 ret = val;
LittleInt64(ret); LittleInt64(ret);
val = ret; val = ret;
return val; return val;
} }
BSWAP_CONSTEXPR int64_t BigInt64(int64_t& val) { BSWAP_CONSTEXPR atInt64 BigInt64(atInt64& val) {
if constexpr (!athena::utility::isSystemBigEndian()) if constexpr (!athena::utility::isSystemBigEndian())
val = athena::utility::swap64(val); val = athena::utility::swap64(val);
return val; return val;
} }
BSWAP_CONSTEXPR uint64_t BigUint64(uint64_t& val) { BSWAP_CONSTEXPR atUint64 BigUint64(atUint64& val) {
int64_t ret = val; atInt64 ret = val;
BigInt64(ret); BigInt64(ret);
val = ret; val = ret;
@@ -175,9 +175,9 @@ BSWAP_CONSTEXPR double BigDouble(double val) {
return val; return val;
} }
void fillRandom(uint8_t* rndArea, uint64_t count); void fillRandom(atUint8* rndArea, atUint64 count);
std::vector<std::string> split(std::string_view s, char delim); std::vector<std::string> split(std::string_view s, char delim);
uint64_t rand64(); atUint64 rand64();
std::string join(const std::vector<std::string>& elems, std::string_view delims); std::string join(const std::vector<std::string>& elems, std::string_view delims);
void tolower(std::string& str); void tolower(std::string& str);
void toupper(std::string& str); void toupper(std::string& str);
@@ -193,9 +193,9 @@ std::string& rtrim(std::string& s);
// trim from both ends // trim from both ends
std::string& trim(std::string& s); std::string& trim(std::string& s);
uint64_t fileSize(std::string_view filename); atUint64 fileSize(std::string_view filename);
#ifdef _WIN32 #ifdef _WIN32
uint64_t fileSize(std::wstring_view filename); atUint64 fileSize(std::wstring_view filename);
#endif #endif
std::string wideToUtf8(std::wstring_view src); std::string wideToUtf8(std::wstring_view src);

View File

@@ -22,19 +22,19 @@ public:
* @param position where in the buffer to seek * @param position where in the buffer to seek
* @param origin The Origin to seek @sa SeekOrigin * @param origin The Origin to seek @sa SeekOrigin
*/ */
void seek(int64_t position, SeekOrigin origin = SeekOrigin::Current) override; void seek(atInt64 position, SeekOrigin origin = SeekOrigin::Current) override;
/*! @brief Returns the current position in the stream. /*! @brief Returns the current position in the stream.
* *
* @return Int64 The current position in the stream. * @return Int64 The current position in the stream.
*/ */
uint64_t position() const override { return m_position; } atUint64 position() const override { return m_position; }
/*! @brief Returns the length of the stream. /*! @brief Returns the length of the stream.
* *
* @return Int64 The length of the stream. * @return Int64 The length of the stream.
*/ */
uint64_t length() const override { return m_data.size(); } atUint64 length() const override { return m_data.size(); }
bool isOpen() const { return true; } bool isOpen() const { return true; }
@@ -48,11 +48,11 @@ public:
* @param data The buffer to write * @param data The buffer to write
* @param length The amount to write * @param length The amount to write
*/ */
void writeUBytes(const uint8_t* data, uint64_t length) override; void writeUBytes(const atUint8* data, atUint64 length) override;
protected: protected:
std::vector<uint8_t> m_data; std::vector<uint8_t> m_data;
uint64_t m_position = 0; atUint64 m_position = 0;
}; };
} // namespace athena::io } // namespace athena::io

View File

@@ -27,7 +27,7 @@ public:
* \param m_banner * \param m_banner
* \param icons * \param icons
*/ */
WiiBanner(uint32_t gameId, const std::u16string& title, const std::u16string& subtitle, WiiImage* m_banner, WiiBanner(atUint32 gameId, const std::u16string& title, const std::u16string& subtitle, WiiImage* m_banner,
std::vector<WiiImage*> icons); std::vector<WiiImage*> icons);
virtual ~WiiBanner(); virtual ~WiiBanner();
@@ -35,13 +35,13 @@ public:
* \brief setGameID * \brief setGameID
* \param id * \param id
*/ */
void setGameID(uint64_t id); void setGameID(atUint64 id);
/*! /*!
* \brief gameID * \brief gameID
* \return * \return
*/ */
uint64_t gameID() const; atUint64 gameID() const;
/*! /*!
* \brief setBannerImage * \brief setBannerImage
@@ -59,13 +59,13 @@ public:
* \brief setBannerSize * \brief setBannerSize
* \param size * \param size
*/ */
void setBannerSize(uint32_t size); void setBannerSize(atUint32 size);
/*! /*!
* \brief bannerSize * \brief bannerSize
* \return * \return
*/ */
uint32_t bannerSize() const; atUint32 bannerSize() const;
/*! /*!
* \brief setTitle * \brief setTitle
@@ -102,14 +102,14 @@ public:
* \param id * \param id
* \param icon * \param icon
*/ */
void setIcon(uint32_t id, WiiImage* icon); void setIcon(atUint32 id, WiiImage* icon);
/*! /*!
* \brief getIcon * \brief getIcon
* \param id * \param id
* \return * \return
*/ */
WiiImage* getIcon(uint32_t id) const; WiiImage* getIcon(atUint32 id) const;
/*! /*!
* \brief icons * \brief icons
@@ -121,46 +121,46 @@ public:
* \brief setAnimationSpeed * \brief setAnimationSpeed
* \param animSpeed * \param animSpeed
*/ */
void setAnimationSpeed(uint16_t animSpeed); void setAnimationSpeed(atUint16 animSpeed);
/*! /*!
* \brief animationSpeed * \brief animationSpeed
* \return * \return
*/ */
uint16_t animationSpeed() const; atUint16 animationSpeed() const;
/*! /*!
* \brief setPermissions * \brief setPermissions
* \param permissions * \param permissions
*/ */
void setPermissions(uint8_t permissions); void setPermissions(atUint8 permissions);
/*! /*!
* \brief permissions * \brief permissions
* \return * \return
*/ */
uint8_t permissions() const; atUint8 permissions() const;
/*! /*!
* \brief setFlags * \brief setFlags
* \param flags * \param flags
*/ */
void setFlags(uint32_t flags); void setFlags(atUint32 flags);
/*! /*!
* \brief flags * \brief flags
* \return * \return
*/ */
uint32_t flags() const; atUint32 flags() const;
protected: protected:
private: private:
uint64_t m_gameId; atUint64 m_gameId;
WiiImage* m_banner; WiiImage* m_banner;
uint32_t m_animSpeed; atUint32 m_animSpeed;
uint8_t m_permissions; atUint8 m_permissions;
uint32_t m_flags; atUint32 m_flags;
uint32_t m_bannerSize; atUint32 m_bannerSize;
std::vector<WiiImage*> m_icons; std::vector<WiiImage*> m_icons;
std::u16string m_title; std::u16string m_title;
std::u16string m_subtitle; std::u16string m_subtitle;

View File

@@ -7,11 +7,11 @@
namespace athena { namespace athena {
const uint8_t SD_KEY[16] = {0xab, 0x01, 0xb9, 0xd8, 0xe1, 0x62, 0x2b, 0x08, const atUint8 SD_KEY[16] = {0xab, 0x01, 0xb9, 0xd8, 0xe1, 0x62, 0x2b, 0x08,
0xaf, 0xba, 0xd8, 0x4d, 0xbf, 0xc2, 0xa5, 0x5d}; 0xaf, 0xba, 0xd8, 0x4d, 0xbf, 0xc2, 0xa5, 0x5d};
const uint8_t SD_IV[16] = {0x21, 0x67, 0x12, 0xe6, 0xaa, 0x1f, 0x68, 0x9f, const atUint8 SD_IV[16] = {0x21, 0x67, 0x12, 0xe6, 0xaa, 0x1f, 0x68, 0x9f,
0x95, 0xc5, 0xa2, 0x23, 0x24, 0xdc, 0x6a, 0x98}; 0x95, 0xc5, 0xa2, 0x23, 0x24, 0xdc, 0x6a, 0x98};
const uint8_t MD5_BLANKER[16] = {0x0e, 0x65, 0x37, 0x81, 0x99, 0xbe, 0x45, 0x17, const atUint8 MD5_BLANKER[16] = {0x0e, 0x65, 0x37, 0x81, 0x99, 0xbe, 0x45, 0x17,
0xab, 0x06, 0xec, 0x22, 0x45, 0x1a, 0x57, 0x93}; 0xab, 0x06, 0xec, 0x22, 0x45, 0x1a, 0x57, 0x93};
/*! \class WiiFile /*! \class WiiFile
@@ -59,7 +59,7 @@ public:
* \param data * \param data
* \param length * \param length
*/ */
WiiFile(const std::string& filename, uint8_t permissions, const uint8_t* data, uint32_t length); WiiFile(const std::string& filename, atUint8 permissions, const atUint8* data, atUint32 length);
virtual ~WiiFile(); virtual ~WiiFile();
/*! /*!
@@ -78,12 +78,12 @@ public:
* \brief setData * \brief setData
* \param data * \param data
*/ */
void setData(const uint8_t* data); void setData(const atUint8* data);
/*! /*!
* \brief data * \brief data
* \return * \return
*/ */
uint8_t* data() const; atUint8* data() const;
/*! /*!
* \brief setLength * \brief setLength
@@ -101,25 +101,25 @@ public:
* \brief setPermissions * \brief setPermissions
* \param permissions * \param permissions
*/ */
void setPermissions(const uint8_t permissions); void setPermissions(const atUint8 permissions);
/*! /*!
* \brief permissions * \brief permissions
* \return * \return
*/ */
uint8_t permissions() const; atUint8 permissions() const;
/*! /*!
* \brief setAttributes * \brief setAttributes
* \param attr * \param attr
*/ */
void setAttributes(const uint8_t attr); void setAttributes(const atUint8 attr);
/*! /*!
* \brief attributes * \brief attributes
* \return * \return
*/ */
uint8_t attributes() const; atUint8 attributes() const;
/*! /*!
* \brief setType * \brief setType
@@ -188,7 +188,7 @@ public:
* \brief fileCount * \brief fileCount
* \return * \return
*/ */
uint32_t fileCount(); atUint32 fileCount();
/*! /*!
* \brief allChildren * \brief allChildren
@@ -204,12 +204,12 @@ public:
protected: protected:
private: private:
uint8_t m_permissions; atUint8 m_permissions;
uint8_t m_attributes; atUint8 m_attributes;
Type m_type; Type m_type;
std::string m_filename; std::string m_filename;
int m_fileLen; int m_fileLen;
uint8_t* m_fileData; atUint8* m_fileData;
WiiFile* m_parent; WiiFile* m_parent;
std::vector<WiiFile*> m_children; std::vector<WiiFile*> m_children;
}; };

View File

@@ -20,54 +20,54 @@ public:
* \param height * \param height
* \param data * \param data
*/ */
WiiImage(uint32_t width, uint32_t height, std::unique_ptr<uint8_t[]>&& data); WiiImage(atUint32 width, atUint32 height, std::unique_ptr<atUint8[]>&& data);
/*! /*!
* \brief setWidth * \brief setWidth
* \param width * \param width
*/ */
void setWidth(const uint32_t width); void setWidth(const atUint32 width);
/*! /*!
* \brief width * \brief width
* \return * \return
*/ */
uint32_t width() const; atUint32 width() const;
/*! /*!
* \brief setHeight * \brief setHeight
* \param height * \param height
*/ */
void setHeight(const uint32_t height); void setHeight(const atUint32 height);
/*! /*!
* \brief height * \brief height
* \return * \return
*/ */
uint32_t height() const; atUint32 height() const;
/*! /*!
* \brief setData * \brief setData
* \param data * \param data
*/ */
void setData(const uint8_t* data); void setData(const atUint8* data);
/*! /*!
* \brief data * \brief data
* \return * \return
*/ */
uint8_t* data(); atUint8* data();
/*! /*!
* \brief toRGBA * \brief toRGBA
* \return * \return
*/ */
uint8_t* toRGBA(); atUint8* toRGBA();
private: private:
uint32_t m_width; atUint32 m_width;
uint32_t m_height; atUint32 m_height;
std::unique_ptr<uint8_t[]> m_data; std::unique_ptr<atUint8[]> m_data;
}; };
} // namespace athena } // namespace athena

View File

@@ -48,7 +48,7 @@ public:
*/ */
WiiFile* file(const std::string& filename); WiiFile* file(const std::string& filename);
uint32_t fileCount() const; atUint32 fileCount() const;
/*! /*!
* \brief fileList * \brief fileList
* \return * \return

View File

@@ -25,7 +25,7 @@ public:
* \param data The existing buffer * \param data The existing buffer
* \param length The length of the existing buffer * \param length The length of the existing buffer
*/ */
WiiSaveReader(const uint8_t*, uint64_t); WiiSaveReader(const atUint8*, atUint64);
/*! \brief This constructor creates an instance from a file on disk. /*! \brief This constructor creates an instance from a file on disk.
* *
@@ -42,8 +42,8 @@ public:
private: private:
WiiBanner* readBanner(); WiiBanner* readBanner();
WiiFile* readFile(); WiiFile* readFile();
WiiImage* readImage(uint32_t width, uint32_t height); WiiImage* readImage(atUint32 width, atUint32 height);
void readCerts(uint32_t totalSize); void readCerts(atUint32 totalSize);
WiiFile* buildTree(std::vector<WiiFile*> files); WiiFile* buildTree(std::vector<WiiFile*> files);
}; };

View File

@@ -36,14 +36,14 @@ public:
* \param filepath * \param filepath
* \return * \return
*/ */
bool writeSave(WiiSave* save, uint8_t* macAddress, uint32_t ngId, uint8_t* ngPriv, uint8_t* ngSig, uint32_t ngKeyId, bool writeSave(WiiSave* save, atUint8* macAddress, atUint32 ngId, atUint8* ngPriv, atUint8* ngSig, atUint32 ngKeyId,
const std::string& filepath = ""); const std::string& filepath = "");
private: private:
void writeBanner(WiiBanner* banner); void writeBanner(WiiBanner* banner);
uint32_t writeFile(WiiFile* file); atUint32 writeFile(WiiFile* file);
void writeImage(WiiImage* image); void writeImage(WiiImage* image);
void writeCerts(uint32_t filesSize, uint32_t ngId, uint8_t* ngPriv, uint8_t* ngSig, uint32_t ngKeyId); void writeCerts(atUint32 filesSize, atUint32 ngId, atUint8* ngPriv, atUint8* ngSig, atUint32 ngKeyId);
}; };
} // namespace io } // namespace io

View File

@@ -61,6 +61,12 @@ public:
RecordRAII enterSubRecord(std::string_view name = {}); RecordRAII enterSubRecord(std::string_view name = {});
template <class T>
void enumerate(std::string_view name, T& record, std::enable_if_t<__IsDNARecord_v<T>>* = nullptr) {
if (auto rec = enterSubRecord(name))
record.read(*this);
}
class VectorRAII { class VectorRAII {
friend class YAMLDocReader; friend class YAMLDocReader;
YAMLDocReader* m_r = nullptr; YAMLDocReader* m_r = nullptr;

View File

@@ -47,6 +47,12 @@ public:
RecordRAII enterSubRecord(std::string_view name = {}); RecordRAII enterSubRecord(std::string_view name = {});
template <class T>
void enumerate(std::string_view name, T& record, std::enable_if_t<__IsDNARecord_v<T>>* = nullptr) {
if (auto rec = enterSubRecord(name))
record.write(*this);
}
class VectorRAII { class VectorRAII {
friend class YAMLDocWriter; friend class YAMLDocWriter;
YAMLDocWriter* m_w = nullptr; YAMLDocWriter* m_w = nullptr;

View File

@@ -18,24 +18,24 @@ public:
/*! /*!
* \brief The current major version of the ZQuest format * \brief The current major version of the ZQuest format
*/ */
static const uint32_t Major; static const atUint32 Major;
/*! /*!
* \brief The current minor version of the ZQuest format * \brief The current minor version of the ZQuest format
*/ */
static const uint32_t Minor; static const atUint32 Minor;
/*! /*!
* \brief The current revision of the ZQuest format * \brief The current revision of the ZQuest format
*/ */
static const uint32_t Revision; static const atUint32 Revision;
/*! /*!
* \brief The current version of the ZQuest format * \brief The current version of the ZQuest format
*/ */
static const uint32_t Version; static const atUint32 Version;
/*! /*!
* \brief The magic number used to identify the file e.g. "ZQS1" * \brief The magic number used to identify the file e.g. "ZQS1"
*/ */
static const uint32_t Magic; static const atUint32 Magic;
/*! /*!
* \enum Game * \enum Game
@@ -79,7 +79,7 @@ public:
* \param data * \param data
* \param length * \param length
*/ */
ZQuestFile(Game game, Endian endian, std::unique_ptr<uint8_t[]>&& data, uint32_t length, ZQuestFile(Game game, Endian endian, std::unique_ptr<atUint8[]>&& data, atUint32 length,
const std::string& gameString = std::string()); const std::string& gameString = std::string());
/*! /*!
@@ -111,19 +111,19 @@ public:
* \param data The data to assign * \param data The data to assign
* \param length The length of the data * \param length The length of the data
*/ */
void setData(std::unique_ptr<uint8_t[]>&& data, uint32_t length); void setData(std::unique_ptr<atUint8[]>&& data, atUint32 length);
/*! /*!
* \brief data * \brief data
* \return * \return
*/ */
uint8_t* data() const; atUint8* data() const;
/*! /*!
* \brief length * \brief length
* \return * \return
*/ */
uint32_t length() const; atUint32 length() const;
void setGameString(const std::string& gameString); void setGameString(const std::string& gameString);
/*! /*!
@@ -138,8 +138,8 @@ protected:
Game m_game; Game m_game;
std::string m_gameString; std::string m_gameString;
Endian m_endian; Endian m_endian;
std::unique_ptr<uint8_t[]> m_data; std::unique_ptr<atUint8[]> m_data;
uint32_t m_length; atUint32 m_length;
// Game strings support // Game strings support
}; };

View File

@@ -20,7 +20,7 @@ public:
* \param data * \param data
* \param length * \param length
*/ */
ZQuestFileReader(uint8_t* data, uint64_t length); ZQuestFileReader(atUint8* data, atUint64 length);
/*! /*!
* \brief ZQuestFileReader * \brief ZQuestFileReader

View File

@@ -19,7 +19,7 @@ public:
* \param data * \param data
* \param length * \param length
*/ */
ZQuestFileWriter(uint8_t* data, uint64_t length); ZQuestFileWriter(atUint8* data, atUint64 length);
/*! /*!
* \brief ZQuestFileWriter * \brief ZQuestFileWriter

View File

@@ -20,6 +20,7 @@
* DEALINGS IN THE SOFTWARE. * DEALINGS IN THE SOFTWARE.
*/ */
/** /**
* @mainpage * @mainpage
* *
@@ -35,11 +36,9 @@
* The features of utf8proc include: * The features of utf8proc include:
* *
* - Transformation of strings (@ref utf8proc_map) to: * - Transformation of strings (@ref utf8proc_map) to:
* - decompose (@ref UTF8PROC_DECOMPOSE) or compose (@ref UTF8PROC_COMPOSE) Unicode combining characters * - decompose (@ref UTF8PROC_DECOMPOSE) or compose (@ref UTF8PROC_COMPOSE) Unicode combining characters (http://en.wikipedia.org/wiki/Combining_character)
* (http://en.wikipedia.org/wiki/Combining_character)
* - canonicalize Unicode compatibility characters (@ref UTF8PROC_COMPAT) * - canonicalize Unicode compatibility characters (@ref UTF8PROC_COMPAT)
* - strip "ignorable" (@ref UTF8PROC_IGNORE) characters, control characters (@ref UTF8PROC_STRIPCC), or combining * - strip "ignorable" (@ref UTF8PROC_IGNORE) characters, control characters (@ref UTF8PROC_STRIPCC), or combining characters such as accents (@ref UTF8PROC_STRIPMARK)
* characters such as accents (@ref UTF8PROC_STRIPMARK)
* - case-folding (@ref UTF8PROC_CASEFOLD) * - case-folding (@ref UTF8PROC_CASEFOLD)
* - Unicode normalization: @ref utf8proc_NFD, @ref utf8proc_NFC, @ref utf8proc_NFKD, @ref utf8proc_NFKC * - Unicode normalization: @ref utf8proc_NFD, @ref utf8proc_NFC, @ref utf8proc_NFKD, @ref utf8proc_NFKC
* - Detecting grapheme boundaries (@ref utf8proc_grapheme_break and @ref UTF8PROC_CHARBOUND) * - Detecting grapheme boundaries (@ref utf8proc_grapheme_break and @ref UTF8PROC_CHARBOUND)
@@ -84,25 +83,26 @@ typedef short utf8proc_int16_t;
typedef unsigned short utf8proc_uint16_t; typedef unsigned short utf8proc_uint16_t;
typedef int utf8proc_int32_t; typedef int utf8proc_int32_t;
typedef unsigned int utf8proc_uint32_t; typedef unsigned int utf8proc_uint32_t;
#ifdef _WIN64 # ifdef _WIN64
typedef __int64 utf8proc_ssize_t; typedef __int64 utf8proc_ssize_t;
typedef unsigned __int64 utf8proc_size_t; typedef unsigned __int64 utf8proc_size_t;
#else # else
typedef int utf8proc_ssize_t; typedef int utf8proc_ssize_t;
typedef unsigned int utf8proc_size_t; typedef unsigned int utf8proc_size_t;
#endif # endif
#ifndef __cplusplus # ifndef __cplusplus
typedef unsigned char utf8proc_bool; typedef unsigned char utf8proc_bool;
enum { false, true }; enum {false, true};
#else # else
typedef bool utf8proc_bool; typedef bool utf8proc_bool;
#endif # endif
#else #else
#ifdef __cplusplus #ifdef __cplusplus
#include <cinttypes> # include <cstdbool>
# include <cinttypes>
#else #else
#include <stdbool.h> # include <stdbool.h>
#include <inttypes.h> # include <inttypes.h>
#endif #endif
typedef int8_t utf8proc_int8_t; typedef int8_t utf8proc_int8_t;
typedef uint8_t utf8proc_uint8_t; typedef uint8_t utf8proc_uint8_t;
@@ -115,9 +115,9 @@ typedef ssize_t utf8proc_ssize_t;
typedef bool utf8proc_bool; typedef bool utf8proc_bool;
#endif #endif
#ifdef __cplusplus #ifdef __cplusplus
#include <climits> # include <climits>
#else #else
#include <limits.h> # include <limits.h>
#endif #endif
/** @name Error codes /** @name Error codes
@@ -136,7 +136,7 @@ typedef bool utf8proc_bool;
#define UTF8PROC_ERROR_INVALIDOPTS -5 #define UTF8PROC_ERROR_INVALIDOPTS -5
/** @} */ /** @} */
#define UTF8PROC_cont(ch) (((ch) & 0xc0) == 0x80) #define UTF8PROC_cont(ch) (((ch) & 0xc0) == 0x80)
/** /**
* Reads a single codepoint from the UTF-8 sequence being pointed to by `str`. * Reads a single codepoint from the UTF-8 sequence being pointed to by `str`.
@@ -148,14 +148,14 @@ typedef bool utf8proc_bool;
* In case of success, the number of bytes read is returned; otherwise, a * In case of success, the number of bytes read is returned; otherwise, a
* negative error code is returned. * negative error code is returned.
*/ */
static inline utf8proc_ssize_t utf8proc_iterate(const utf8proc_uint8_t* str, utf8proc_ssize_t strlen, static inline utf8proc_ssize_t utf8proc_iterate(
utf8proc_int32_t* dst) { const utf8proc_uint8_t *str, utf8proc_ssize_t strlen, utf8proc_int32_t *dst
) {
utf8proc_uint32_t uc; utf8proc_uint32_t uc;
const utf8proc_uint8_t* end; const utf8proc_uint8_t *end;
*dst = -1; *dst = -1;
if (!strlen) if (!strlen) return 0;
return 0;
end = str + ((strlen < 0) ? 4 : strlen); end = str + ((strlen < 0) ? 4 : strlen);
uc = *str++; uc = *str++;
if (uc < 0x80) { if (uc < 0x80) {
@@ -163,40 +163,36 @@ static inline utf8proc_ssize_t utf8proc_iterate(const utf8proc_uint8_t* str, utf
return 1; return 1;
} }
// Must be between 0xc2 and 0xf4 inclusive to be valid // Must be between 0xc2 and 0xf4 inclusive to be valid
if ((uc - 0xc2) > (0xf4 - 0xc2)) if ((uc - 0xc2) > (0xf4-0xc2)) return UTF8PROC_ERROR_INVALIDUTF8;
return UTF8PROC_ERROR_INVALIDUTF8; if (uc < 0xe0) { // 2-byte sequence
if (uc < 0xe0) { // 2-byte sequence // Must have valid continuation character
// Must have valid continuation character if (!UTF8PROC_cont(*str)) return UTF8PROC_ERROR_INVALIDUTF8;
if (!UTF8PROC_cont(*str)) *dst = ((uc & 0x1f)<<6) | (*str & 0x3f);
return UTF8PROC_ERROR_INVALIDUTF8; return 2;
*dst = ((uc & 0x1f) << 6) | (*str & 0x3f);
return 2;
} }
if (uc < 0xf0) { // 3-byte sequence if (uc < 0xf0) { // 3-byte sequence
if ((str + 1 >= end) || !UTF8PROC_cont(*str) || !UTF8PROC_cont(str[1])) if ((str + 1 >= end) || !UTF8PROC_cont(*str) || !UTF8PROC_cont(str[1]))
return UTF8PROC_ERROR_INVALIDUTF8; return UTF8PROC_ERROR_INVALIDUTF8;
// Check for surrogate chars // Check for surrogate chars
if (uc == 0xed && *str > 0x9f) if (uc == 0xed && *str > 0x9f)
return UTF8PROC_ERROR_INVALIDUTF8; return UTF8PROC_ERROR_INVALIDUTF8;
uc = ((uc & 0xf) << 12) | ((*str & 0x3f) << 6) | (str[1] & 0x3f); uc = ((uc & 0xf)<<12) | ((*str & 0x3f)<<6) | (str[1] & 0x3f);
if (uc < 0x800) if (uc < 0x800)
return UTF8PROC_ERROR_INVALIDUTF8; return UTF8PROC_ERROR_INVALIDUTF8;
*dst = uc; *dst = uc;
return 3; return 3;
} }
// 4-byte sequence // 4-byte sequence
// Must have 3 valid continuation characters // Must have 3 valid continuation characters
if ((str + 2 >= end) || !UTF8PROC_cont(*str) || !UTF8PROC_cont(str[1]) || !UTF8PROC_cont(str[2])) if ((str + 2 >= end) || !UTF8PROC_cont(*str) || !UTF8PROC_cont(str[1]) || !UTF8PROC_cont(str[2]))
return UTF8PROC_ERROR_INVALIDUTF8; return UTF8PROC_ERROR_INVALIDUTF8;
// Make sure in correct range (0x10000 - 0x10ffff) // Make sure in correct range (0x10000 - 0x10ffff)
if (uc == 0xf0) { if (uc == 0xf0) {
if (*str < 0x90) if (*str < 0x90) return UTF8PROC_ERROR_INVALIDUTF8;
return UTF8PROC_ERROR_INVALIDUTF8;
} else if (uc == 0xf4) { } else if (uc == 0xf4) {
if (*str > 0x8f) if (*str > 0x8f) return UTF8PROC_ERROR_INVALIDUTF8;
return UTF8PROC_ERROR_INVALIDUTF8;
} }
*dst = ((uc & 7) << 18) | ((*str & 0x3f) << 12) | ((str[1] & 0x3f) << 6) | (str[2] & 0x3f); *dst = ((uc & 7)<<18) | ((*str & 0x3f)<<12) | ((str[1] & 0x3f)<<6) | (str[2] & 0x3f);
return 4; return 4;
} }
@@ -209,7 +205,7 @@ static inline utf8proc_ssize_t utf8proc_iterate(const utf8proc_uint8_t* str, utf
* *
* This function does not check whether `codepoint` is valid Unicode. * This function does not check whether `codepoint` is valid Unicode.
*/ */
static inline utf8proc_ssize_t utf8proc_encode_char(utf8proc_int32_t uc, utf8proc_uint8_t* dst) { static inline utf8proc_ssize_t utf8proc_encode_char(utf8proc_int32_t uc, utf8proc_uint8_t *dst) {
if (uc < 0x00) { if (uc < 0x00) {
return 0; return 0;
} else if (uc < 0x80) { } else if (uc < 0x80) {
@@ -219,8 +215,8 @@ static inline utf8proc_ssize_t utf8proc_encode_char(utf8proc_int32_t uc, utf8pro
dst[0] = 0xC0 + (uc >> 6); dst[0] = 0xC0 + (uc >> 6);
dst[1] = 0x80 + (uc & 0x3F); dst[1] = 0x80 + (uc & 0x3F);
return 2; return 2;
// Note: we allow encoding 0xd800-0xdfff here, so as not to change // Note: we allow encoding 0xd800-0xdfff here, so as not to change
// the API, however, these are actually invalid in UTF-8 // the API, however, these are actually invalid in UTF-8
} else if (uc < 0x10000) { } else if (uc < 0x10000) {
dst[0] = 0xE0 + (uc >> 12); dst[0] = 0xE0 + (uc >> 12);
dst[1] = 0x80 + ((uc >> 6) & 0x3F); dst[1] = 0x80 + ((uc >> 6) & 0x3F);
@@ -232,69 +228,81 @@ static inline utf8proc_ssize_t utf8proc_encode_char(utf8proc_int32_t uc, utf8pro
dst[2] = 0x80 + ((uc >> 6) & 0x3F); dst[2] = 0x80 + ((uc >> 6) & 0x3F);
dst[3] = 0x80 + (uc & 0x3F); dst[3] = 0x80 + (uc & 0x3F);
return 4; return 4;
} else } else return 0;
return 0;
} }
#ifdef __cplusplus #ifdef __cplusplus
#include <iterator> #include <iterator>
#include <string> #include <string>
class UTF8Iterator { class UTF8Iterator
std::string_view::const_iterator m_it; {
std::string_view::const_iterator m_it;
public: public:
using iterator_category = std::forward_iterator_tag; using iterator_category = std::forward_iterator_tag;
using value_type = uint32_t; using value_type = uint32_t;
using difference_type = std::ptrdiff_t; using difference_type = std::ptrdiff_t;
using pointer = uint32_t*; using pointer = uint32_t*;
using reference = uint32_t&; using reference = uint32_t&;
UTF8Iterator(const std::string_view::const_iterator& it) : m_it(it) {} UTF8Iterator(const std::string_view::const_iterator& it) : m_it(it) {}
UTF8Iterator& operator+=(size_t v) { UTF8Iterator& operator+=(size_t v)
for (size_t i = 0; i < v; ++i) { {
utf8proc_int32_t dummy; for (size_t i=0 ; i<v ; ++i)
utf8proc_ssize_t sz = utf8proc_iterate(reinterpret_cast<const utf8proc_uint8_t*>(&*m_it), -1, &dummy); {
utf8proc_int32_t dummy;
utf8proc_ssize_t sz = utf8proc_iterate(reinterpret_cast<const utf8proc_uint8_t*>(&*m_it), -1, &dummy);
#ifndef NDEBUG #ifndef NDEBUG
if (*m_it == '\0') { if (*m_it == '\0')
fprintf(stderr, "ERROR! UTF8-iterator null-term fail\n"); {
abort(); fprintf(stderr, "ERROR! UTF8-iterator null-term fail\n");
} else if (sz > 0) abort();
m_it += sz; }
else { else if (sz > 0)
fprintf(stderr, "ERROR! UTF8Iterator character fail"); m_it += sz;
abort(); else
} {
fprintf(stderr, "ERROR! UTF8Iterator character fail");
abort();
}
#else #else
if (sz > 0) if (sz > 0)
m_it += sz; m_it += sz;
#endif #endif
}
return *this;
} }
return *this; UTF8Iterator& operator++()
} {
UTF8Iterator& operator++() { return this->operator+=(1); } return this->operator+=(1);
UTF8Iterator operator+(size_t v) const { }
UTF8Iterator ret(m_it); UTF8Iterator operator+(size_t v) const
ret += v; {
return ret; UTF8Iterator ret(m_it);
} ret += v;
uint32_t operator*() const { return ret;
utf8proc_int32_t ret; }
utf8proc_iterate(reinterpret_cast<const utf8proc_uint8_t*>(&*m_it), -1, &ret); uint32_t operator*() const
return ret; {
} utf8proc_int32_t ret;
std::string_view::const_iterator iter() const { return m_it; } utf8proc_iterate(reinterpret_cast<const utf8proc_uint8_t*>(&*m_it), -1, &ret);
size_t countTo(std::string_view::const_iterator end) const { return ret;
UTF8Iterator it(m_it); }
size_t ret = 0; std::string_view::const_iterator iter() const {return m_it;}
while (it.iter() < end && *it != '\0') { size_t countTo(std::string_view::const_iterator end) const
++ret; {
++it; UTF8Iterator it(m_it);
size_t ret = 0;
while (it.iter() < end && *it != '\0')
{
++ret;
++it;
}
return ret;
} }
return ret;
}
}; };
#endif #endif
#endif #endif

View File

@@ -2,10 +2,10 @@
#include "athena/Types.hpp" #include "athena/Types.hpp"
namespace bignum { namespace bignum {
int compare(const uint8_t* a, const uint8_t* b, uint32_t n); int compare(const atUint8* a, const atUint8* b, atUint32 n);
void subModulus(uint8_t* a, const uint8_t* N, uint32_t n); void subModulus(atUint8* a, const atUint8* N, atUint32 n);
void add(uint8_t* d, uint8_t* a, const uint8_t* b, const uint8_t* N, uint32_t n); void add(atUint8* d, atUint8* a, const atUint8* b, const atUint8* N, atUint32 n);
void mul(uint8_t* d, uint8_t* a, const uint8_t* b, const uint8_t* N, uint32_t n); void mul(atUint8* d, atUint8* a, const atUint8* b, const atUint8* N, atUint32 n);
void exp(uint8_t* d, const uint8_t* a, const uint8_t* N, uint32_t n, uint8_t* e, uint32_t en); void exp(atUint8* d, const atUint8* a, const atUint8* N, atUint32 n, atUint8* e, atUint32 en);
void inv(uint8_t* d, uint8_t* a, const uint8_t* N, uint32_t n); void inv(atUint8* d, atUint8* a, const atUint8* N, atUint32 n);
} // namespace bignum } // namespace bignum

View File

@@ -2,7 +2,7 @@
#include "athena/Types.hpp" #include "athena/Types.hpp"
namespace ecc { namespace ecc {
void checkEC(uint8_t* ng, uint8_t* ap, uint8_t* sig, uint8_t* sigHash, bool& apValid, bool& ngValid); void checkEC(atUint8* ng, atUint8* ap, atUint8* sig, atUint8* sigHash, bool& apValid, bool& ngValid);
void makeECCert(uint8_t* cert, uint8_t* sig, const char* signer, const char* name, uint8_t* priv, uint32_t keyId); void makeECCert(atUint8* cert, atUint8* sig, const char* signer, const char* name, atUint8* priv, atUint32 keyId);
void createECDSA(uint8_t* R, uint8_t* S, uint8_t* k, uint8_t* hash); void createECDSA(atUint8* R, atUint8* S, atUint8* k, atUint8* hash);
} // namespace ecc } // namespace ecc

View File

@@ -37,7 +37,7 @@ void SHA1Input(SHA1Context*,
uint8_t* getSha1(uint8_t* stuff, uint32_t stuff_size); atUint8* getSha1(atUint8* stuff, atUint32 stuff_size);
#ifdef __cplusplus #ifdef __cplusplus
} }

View File

@@ -26,12 +26,12 @@ int subMatch(const uint8_t* str1, const uint8_t* str2, const int len) {
// Up to 4096 bytes Up to 18 bytes // Up to 4096 bytes Up to 18 bytes
// Sliding Window // Sliding Window
// Up to 4114 bytes // Up to 4114 bytes
LZLengthOffset windowSearch(const uint8_t* beginSearchPtr, const uint8_t* searchPosPtr, const uint8_t* endLABufferPtr, LZLengthOffset windowSearch(const atUint8* beginSearchPtr, const atUint8* searchPosPtr, const atUint8* endLABufferPtr,
const uint8_t* startLBPtr) { const atUint8* startLBPtr) {
int32_t size = (uint32_t)(endLABufferPtr - beginSearchPtr); // Size of the entire sliding window atInt32 size = (atUint32)(endLABufferPtr - beginSearchPtr); // Size of the entire sliding window
int32_t n = (uint32_t)(endLABufferPtr - searchPosPtr); atInt32 n = (atUint32)(endLABufferPtr - searchPosPtr);
LZLengthOffset result = {0, 0}; LZLengthOffset result = {0, 0};
int32_t temp = 0; atInt32 temp = 0;
if (n > size) // If the string that is being looked for is bigger than the string that is being searched if (n > size) // If the string that is being looked for is bigger than the string that is being searched
return result; return result;
@@ -44,12 +44,12 @@ LZLengthOffset windowSearch(const uint8_t* beginSearchPtr, const uint8_t* search
do { do {
temp = subMatch(startLBPtr, searchPosPtr, n); temp = subMatch(startLBPtr, searchPosPtr, n);
if (result.length < (uint32_t)temp) { if (result.length < (atUint32)temp) {
result.length = temp; result.length = temp;
result.offset = (int32_t)(searchPosPtr - startLBPtr); result.offset = (atInt32)(searchPosPtr - startLBPtr);
} }
if (result.length == (uint32_t)n) if (result.length == (atUint32)n)
return result; return result;
// ReadAheadBuffer is the maximum size of a character match // ReadAheadBuffer is the maximum size of a character match
@@ -60,7 +60,7 @@ LZLengthOffset windowSearch(const uint8_t* beginSearchPtr, const uint8_t* search
} }
} // Anonymous namespace } // Anonymous namespace
LZBase::LZBase(int32_t minimumOffset, int32_t slidingWindow, int32_t minimumMatch, int32_t blockSize) LZBase::LZBase(atInt32 minimumOffset, atInt32 slidingWindow, atInt32 minimumMatch, atInt32 blockSize)
: m_slidingWindow(slidingWindow) : m_slidingWindow(slidingWindow)
, m_readAheadBuffer(minimumMatch) , m_readAheadBuffer(minimumMatch)
, m_minMatch(minimumMatch) , m_minMatch(minimumMatch)
@@ -69,25 +69,25 @@ LZBase::LZBase(int32_t minimumOffset, int32_t slidingWindow, int32_t minimumMatc
LZBase::~LZBase() = default; LZBase::~LZBase() = default;
void LZBase::setSlidingWindow(int32_t slidingWindow) { m_slidingWindow = slidingWindow; } void LZBase::setSlidingWindow(atInt32 slidingWindow) { m_slidingWindow = slidingWindow; }
int32_t LZBase::slidingWindow() const { return m_slidingWindow; } atInt32 LZBase::slidingWindow() const { return m_slidingWindow; }
void LZBase::setReadAheadBuffer(int32_t readAheadBuffer) { m_readAheadBuffer = readAheadBuffer; } void LZBase::setReadAheadBuffer(atInt32 readAheadBuffer) { m_readAheadBuffer = readAheadBuffer; }
int32_t LZBase::readAheadBuffer() const { return m_readAheadBuffer; } atInt32 LZBase::readAheadBuffer() const { return m_readAheadBuffer; }
void LZBase::setMinMatch(int32_t minimumMatch) { m_minMatch = minimumMatch; } void LZBase::setMinMatch(atInt32 minimumMatch) { m_minMatch = minimumMatch; }
int32_t LZBase::minMatch() const { return m_minMatch; } atInt32 LZBase::minMatch() const { return m_minMatch; }
void LZBase::setBlockSize(int32_t blockSize) { m_blockSize = blockSize; } void LZBase::setBlockSize(atInt32 blockSize) { m_blockSize = blockSize; }
int32_t LZBase::blockSize() const { return m_blockSize; } atInt32 LZBase::blockSize() const { return m_blockSize; }
void LZBase::setMinimumOffset(uint32_t minimumOffset) { m_minOffset = minimumOffset; } void LZBase::setMinimumOffset(atUint32 minimumOffset) { m_minOffset = minimumOffset; }
uint32_t LZBase::minimumOffset() const { return m_minOffset; } atUint32 LZBase::minimumOffset() const { return m_minOffset; }
/* /*
DerricMc: DerricMc:
@@ -100,7 +100,7 @@ uint32_t LZBase::minimumOffset() const { return m_minOffset; }
and 17 bytes did match then 17 bytes match is return). and 17 bytes did match then 17 bytes match is return).
*/ */
LZLengthOffset LZBase::search(const uint8_t* posPtr, const uint8_t* dataBegin, const uint8_t* dataEnd) const { LZLengthOffset LZBase::search(const atUint8* posPtr, const atUint8* dataBegin, const atUint8* dataEnd) const {
LZLengthOffset results = {0, 0}; LZLengthOffset results = {0, 0};
// Returns negative 1 for Search failures since the current position is passed the size to be compressed // Returns negative 1 for Search failures since the current position is passed the size to be compressed
@@ -109,7 +109,7 @@ LZLengthOffset LZBase::search(const uint8_t* posPtr, const uint8_t* dataBegin, c
return results; return results;
} }
const uint8_t* searchWindow; const atUint8* searchWindow;
// LookAheadBuffer is ReadAheadBuffer Size if there are more bytes than ReadAheadBufferSize waiting // LookAheadBuffer is ReadAheadBuffer Size if there are more bytes than ReadAheadBufferSize waiting
// to be compressed else the number of remaining bytes is the LookAheadBuffer // to be compressed else the number of remaining bytes is the LookAheadBuffer
const int lookAheadBuffer_len = const int lookAheadBuffer_len =
@@ -121,7 +121,7 @@ LZLengthOffset LZBase::search(const uint8_t* posPtr, const uint8_t* dataBegin, c
else else
searchWindow = dataBegin; searchWindow = dataBegin;
const uint8_t* endPos = posPtr + lookAheadBuffer_len; const atUint8* endPos = posPtr + lookAheadBuffer_len;
if (!((posPtr - dataBegin < 1) || (dataEnd - posPtr < m_minMatch))) if (!((posPtr - dataBegin < 1) || (dataEnd - posPtr < m_minMatch)))
results = windowSearch(searchWindow, posPtr, endPos, posPtr - m_minOffset); results = windowSearch(searchWindow, posPtr, endPos, posPtr - m_minOffset);

View File

@@ -3,7 +3,7 @@
LZLookupTable::LZLookupTable() : m_buffer(m_minimumMatch) {} LZLookupTable::LZLookupTable() : m_buffer(m_minimumMatch) {}
LZLookupTable::LZLookupTable(int32_t minimumMatch, int32_t slidingWindow, int32_t lookAheadWindow) { LZLookupTable::LZLookupTable(atInt32 minimumMatch, atInt32 slidingWindow, atInt32 lookAheadWindow) {
if (minimumMatch > 0) if (minimumMatch > 0)
m_minimumMatch = minimumMatch; m_minimumMatch = minimumMatch;
else else
@@ -21,14 +21,14 @@ LZLookupTable::LZLookupTable(int32_t minimumMatch, int32_t slidingWindow, int32_
LZLookupTable::~LZLookupTable() = default; LZLookupTable::~LZLookupTable() = default;
void LZLookupTable::setLookAheadWindow(int32_t lookAheadWindow) { void LZLookupTable::setLookAheadWindow(atInt32 lookAheadWindow) {
if (lookAheadWindow > 0) if (lookAheadWindow > 0)
m_lookAheadWindow = lookAheadWindow; m_lookAheadWindow = lookAheadWindow;
else else
m_lookAheadWindow = 18; m_lookAheadWindow = 18;
} }
LZLengthOffset LZLookupTable::search(const uint8_t* curPos, const uint8_t* dataBegin, const uint8_t* dataEnd) { LZLengthOffset LZLookupTable::search(const atUint8* curPos, const atUint8* dataBegin, const atUint8* dataEnd) {
LZLengthOffset loPair = {0, 0}; LZLengthOffset loPair = {0, 0};
// Returns negative 1 for search failures since the current position is passed the size to be compressed // Returns negative 1 for search failures since the current position is passed the size to be compressed
@@ -38,7 +38,7 @@ LZLengthOffset LZLookupTable::search(const uint8_t* curPos, const uint8_t* dataB
} }
std::copy(curPos, curPos + m_minimumMatch, m_buffer.begin()); std::copy(curPos, curPos + m_minimumMatch, m_buffer.begin());
int32_t currentOffset = static_cast<int32_t>(curPos - dataBegin); int32_t currentOffset = static_cast<atInt32>(curPos - dataBegin);
// Find code // Find code
if (currentOffset > 0 && (dataEnd - curPos) >= m_minimumMatch) { if (currentOffset > 0 && (dataEnd - curPos) >= m_minimumMatch) {
@@ -60,13 +60,13 @@ LZLengthOffset LZLookupTable::search(const uint8_t* curPos, const uint8_t* dataB
// Store the longest match found so far into length_offset struct. // Store the longest match found so far into length_offset struct.
// When lengths are the same the closer offset to the lookahead buffer wins // When lengths are the same the closer offset to the lookahead buffer wins
if (loPair.length < (uint32_t)matchLength) { if (loPair.length < (atUint32)matchLength) {
loPair.length = matchLength; loPair.length = matchLength;
loPair.offset = currentOffset - iter->second; loPair.offset = currentOffset - iter->second;
} }
// Found the longest match so break out of loop // Found the longest match so break out of loop
if (loPair.length == (uint32_t)m_lookAheadWindow) if (loPair.length == (atUint32)m_lookAheadWindow)
break; break;
} }
} }
@@ -75,7 +75,7 @@ LZLengthOffset LZLookupTable::search(const uint8_t* curPos, const uint8_t* dataB
// Insert code // Insert code
table.insert(std::make_pair(m_buffer, currentOffset)); table.insert(std::make_pair(m_buffer, currentOffset));
for (uint32_t i = 1; i < loPair.length; i++) { for (atUint32 i = 1; i < loPair.length; i++) {
if (dataEnd - (curPos + i) < m_minimumMatch) if (dataEnd - (curPos + i) < m_minimumMatch)
break; break;

View File

@@ -8,46 +8,46 @@
#include <athena/MemoryWriter.hpp> #include <athena/MemoryWriter.hpp>
LZType10::LZType10(int32_t MinimumOffset, int32_t SlidingWindow, int32_t MinimumMatch, int32_t BlockSize) LZType10::LZType10(atInt32 MinimumOffset, atInt32 SlidingWindow, atInt32 MinimumMatch, atInt32 BlockSize)
: LZBase(MinimumOffset, SlidingWindow, MinimumMatch, BlockSize) { : LZBase(MinimumOffset, SlidingWindow, MinimumMatch, BlockSize) {
// ReadAheadBuffer is normalize between (minumum match) and(minimum match + 15) so that matches fit within // ReadAheadBuffer is normalize between (minumum match) and(minimum match + 15) so that matches fit within
// 4-bits. // 4-bits.
m_readAheadBuffer = m_minMatch + 0xF; m_readAheadBuffer = m_minMatch + 0xF;
} }
uint32_t LZType10::compress(const uint8_t* src, uint8_t** dstBuf, uint32_t srcLength) { atUint32 LZType10::compress(const atUint8* src, atUint8** dstBuf, atUint32 srcLength) {
uint32_t encodeSize = (srcLength << 8) | (0x10); atUint32 encodeSize = (srcLength << 8) | (0x10);
encodeSize = athena::utility::LittleUint32(encodeSize); // File size needs to be written as little endian always encodeSize = athena::utility::LittleUint32(encodeSize); // File size needs to be written as little endian always
athena::io::MemoryCopyWriter outbuf("tmp"); athena::io::MemoryCopyWriter outbuf("tmp");
outbuf.writeUint32(encodeSize); outbuf.writeUint32(encodeSize);
const uint8_t* ptrStart = src; const atUint8* ptrStart = src;
const uint8_t* ptrEnd = src + srcLength; const atUint8* ptrEnd = src + srcLength;
// At most their will be two bytes written if the bytes can be compressed. So if all bytes in the block can be // At most their will be two bytes written if the bytes can be compressed. So if all bytes in the block can be
// compressed it would take blockSize*2 bytes // compressed it would take blockSize*2 bytes
auto compressedBytes = std::unique_ptr<uint8_t[]>(new uint8_t[m_blockSize * 2]); // Holds the compressed bytes yet to be written auto compressedBytes = std::unique_ptr<atUint8[]>(new atUint8[m_blockSize * 2]); // Holds the compressed bytes yet to be written
while (ptrStart < ptrEnd) { while (ptrStart < ptrEnd) {
uint8_t blockLen = 0; atUint8 blockLen = 0;
// In Binary represents 1 if byte is compressed or 0 if not compressed // In Binary represents 1 if byte is compressed or 0 if not compressed
// For example 01001000 means that the second and fifth byte in the blockSize from the left is compressed // For example 01001000 means that the second and fifth byte in the blockSize from the left is compressed
uint8_t* ptrBytes = compressedBytes.get(); atUint8* ptrBytes = compressedBytes.get();
for (int32_t i = 0; i < m_blockSize; i++) { for (atInt32 i = 0; i < m_blockSize; i++) {
// length_offset searchResult=Search(ptrStart, filedata, ptrEnd); // length_offset searchResult=Search(ptrStart, filedata, ptrEnd);
const LZLengthOffset searchResult = m_lookupTable.search(ptrStart, src, ptrEnd); const LZLengthOffset searchResult = m_lookupTable.search(ptrStart, src, ptrEnd);
// If the number of bytes to be compressed is at least the size of the Minimum match // If the number of bytes to be compressed is at least the size of the Minimum match
if (searchResult.length >= static_cast<uint32_t>(m_minMatch)) { if (searchResult.length >= static_cast<atUint32>(m_minMatch)) {
// Gotta swap the bytes since system is wii is big endian and most computers are little endian // Gotta swap the bytes since system is wii is big endian and most computers are little endian
uint16_t lenOff = (((searchResult.length - m_minMatch) & 0xF) << 12) | ((searchResult.offset - 1) & 0xFFF); atUint16 lenOff = (((searchResult.length - m_minMatch) & 0xF) << 12) | ((searchResult.offset - 1) & 0xFFF);
athena::utility::BigUint16(lenOff); athena::utility::BigUint16(lenOff);
memcpy(ptrBytes, &lenOff, sizeof(uint16_t)); memcpy(ptrBytes, &lenOff, sizeof(atUint16));
ptrBytes += sizeof(uint16_t); ptrBytes += sizeof(atUint16);
ptrStart += searchResult.length; ptrStart += searchResult.length;
@@ -60,7 +60,7 @@ uint32_t LZType10::compress(const uint8_t* src, uint8_t** dstBuf, uint32_t srcLe
} }
outbuf.writeByte(blockLen); outbuf.writeByte(blockLen);
outbuf.writeUBytes(compressedBytes.get(), static_cast<uint64_t>(ptrBytes - compressedBytes.get())); outbuf.writeUBytes(compressedBytes.get(), static_cast<atUint64>(ptrBytes - compressedBytes.get()));
} }
// Add zeros until the file is a multiple of 4 // Add zeros until the file is a multiple of 4
@@ -70,16 +70,16 @@ uint32_t LZType10::compress(const uint8_t* src, uint8_t** dstBuf, uint32_t srcLe
*dstBuf = outbuf.data(); *dstBuf = outbuf.data();
outbuf.save(); outbuf.save();
return static_cast<uint32_t>(outbuf.length()); return static_cast<atUint32>(outbuf.length());
} }
uint32_t LZType10::decompress(const uint8_t* src, uint8_t** dst, uint32_t srcLength) { atUint32 LZType10::decompress(const atUint8* src, atUint8** dst, atUint32 srcLength) {
if (*src != 0x10) { if (*src != 0x10) {
return 0; return 0;
} }
// Size of data when it is uncompressed // Size of data when it is uncompressed
uint32_t uncompressedSize; atUint32 uncompressedSize;
std::memcpy(&uncompressedSize, src, sizeof(uncompressedSize)); std::memcpy(&uncompressedSize, src, sizeof(uncompressedSize));
// The compressed file has the filesize encoded in little endian // The compressed file has the filesize encoded in little endian
@@ -88,28 +88,28 @@ uint32_t LZType10::decompress(const uint8_t* src, uint8_t** dst, uint32_t srcLen
// first byte is the encode flag // first byte is the encode flag
uncompressedSize = uncompressedSize >> 8; uncompressedSize = uncompressedSize >> 8;
auto uncompressedData = std::unique_ptr<uint8_t[]>(new uint8_t[uncompressedSize]); auto uncompressedData = std::unique_ptr<atUint8[]>(new atUint8[uncompressedSize]);
uint8_t* outputPtr = uncompressedData.get(); atUint8* outputPtr = uncompressedData.get();
uint8_t* outputEndPtr = uncompressedData.get() + uncompressedSize; atUint8* outputEndPtr = uncompressedData.get() + uncompressedSize;
const uint8_t* inputPtr = src + 4; const atUint8* inputPtr = src + 4;
const uint8_t* inputEndPtr = src + srcLength; const atUint8* inputEndPtr = src + srcLength;
while (inputPtr < inputEndPtr && outputPtr < outputEndPtr) { while (inputPtr < inputEndPtr && outputPtr < outputEndPtr) {
const uint8_t isCompressed = *inputPtr++; const atUint8 isCompressed = *inputPtr++;
for (uint32_t i = 0; i < static_cast<uint32_t>(m_blockSize); i++) { for (atUint32 i = 0; i < static_cast<atUint32>(m_blockSize); i++) {
// Checks to see if the next byte is compressed by looking // Checks to see if the next byte is compressed by looking
// at its binary representation - E.g 10010000 // at its binary representation - E.g 10010000
// This says that the first extracted byte and the four extracted byte is compressed // This says that the first extracted byte and the four extracted byte is compressed
if ((isCompressed >> (7 - i)) & 0x1) { if ((isCompressed >> (7 - i)) & 0x1) {
uint16_t lenOff; atUint16 lenOff;
memcpy(&lenOff, inputPtr, sizeof(uint16_t)); memcpy(&lenOff, inputPtr, sizeof(atUint16));
athena::utility::BigUint16(lenOff); athena::utility::BigUint16(lenOff);
inputPtr += sizeof(uint16_t); // Move forward two bytes inputPtr += sizeof(atUint16); // Move forward two bytes
// length offset pair has been decoded. // length offset pair has been decoded.
LZLengthOffset decoding; LZLengthOffset decoding;
decoding.length = (lenOff >> 12) + m_minMatch; decoding.length = (lenOff >> 12) + m_minMatch;
decoding.offset = static_cast<uint16_t>((lenOff & 0xFFF) + 1); decoding.offset = static_cast<atUint16>((lenOff & 0xFFF) + 1);
if ((outputPtr - decoding.offset) < uncompressedData.get()) { if ((outputPtr - decoding.offset) < uncompressedData.get()) {
// If the offset to look for uncompressed is passed the current uncompresed data then the data is not // If the offset to look for uncompressed is passed the current uncompresed data then the data is not

View File

@@ -8,41 +8,41 @@
#include <athena/MemoryWriter.hpp> #include <athena/MemoryWriter.hpp>
LZType11::LZType11(int32_t minimumOffset, int32_t slidingWindow, int32_t minimumMatch, int32_t blockSize) LZType11::LZType11(atInt32 minimumOffset, atInt32 slidingWindow, atInt32 minimumMatch, atInt32 blockSize)
: LZBase(minimumOffset, slidingWindow, minimumMatch, blockSize) { : LZBase(minimumOffset, slidingWindow, minimumMatch, blockSize) {
m_readAheadBuffer = (0xF + 0xFF + 0xFFFF + m_minMatch); m_readAheadBuffer = (0xF + 0xFF + 0xFFFF + m_minMatch);
m_lookupTable.setLookAheadWindow(m_readAheadBuffer); m_lookupTable.setLookAheadWindow(m_readAheadBuffer);
} }
uint32_t LZType11::compress(const uint8_t* src, uint8_t** dst, uint32_t srcLength) { atUint32 LZType11::compress(const atUint8* src, atUint8** dst, atUint32 srcLength) {
athena::io::MemoryCopyWriter outbuff("tmp"); athena::io::MemoryCopyWriter outbuff("tmp");
if (srcLength > 0xFFFFFF) { // If length is greater than 24 bits or 16 Megs if (srcLength > 0xFFFFFF) { // If length is greater than 24 bits or 16 Megs
uint32_t encodeFlag = 0x11; atUint32 encodeFlag = 0x11;
athena::utility::LittleUint32(encodeFlag); athena::utility::LittleUint32(encodeFlag);
athena::utility::LittleUint32(srcLength); // Filesize data is little endian athena::utility::LittleUint32(srcLength); // Filesize data is little endian
outbuff.writeUint32(encodeFlag); outbuff.writeUint32(encodeFlag);
outbuff.writeUint32(srcLength); outbuff.writeUint32(srcLength);
} else { } else {
uint32_t encodeSize = (srcLength << 8) | (0x11); atUint32 encodeSize = (srcLength << 8) | (0x11);
athena::utility::LittleUint32(encodeSize); athena::utility::LittleUint32(encodeSize);
outbuff.writeUint32(encodeSize); outbuff.writeUint32(encodeSize);
} }
const uint8_t* ptrStart = src; const atUint8* ptrStart = src;
const uint8_t* ptrEnd = src + srcLength; const atUint8* ptrEnd = src + srcLength;
// At most their will be two bytes written if the bytes can be compressed. So if all bytes in the block can be // At most their will be two bytes written if the bytes can be compressed. So if all bytes in the block can be
// compressed it would take blockSize*2 bytes // compressed it would take blockSize*2 bytes
// Holds the compressed bytes yet to be written // Holds the compressed bytes yet to be written
auto compressedBytes = std::unique_ptr<uint8_t[]>(new uint8_t[m_blockSize * 2]); auto compressedBytes = std::unique_ptr<atUint8[]>(new atUint8[m_blockSize * 2]);
const uint8_t maxTwoByteMatch = 0xF + 1; const atUint8 maxTwoByteMatch = 0xF + 1;
const uint8_t minThreeByteMatch = maxTwoByteMatch + 1; // Minimum Three byte match is maximum TwoByte match + 1 const atUint8 minThreeByteMatch = maxTwoByteMatch + 1; // Minimum Three byte match is maximum TwoByte match + 1
const uint16_t maxThreeByteMatch = 0xFF + minThreeByteMatch; const atUint16 maxThreeByteMatch = 0xFF + minThreeByteMatch;
const uint16_t minFourByteMatch = maxThreeByteMatch + 1; // Minimum Four byte match is maximum Three Byte match + 1 const atUint16 minFourByteMatch = maxThreeByteMatch + 1; // Minimum Four byte match is maximum Three Byte match + 1
const int32_t maxFourByteMatch = 0xFFFF + minFourByteMatch; const atInt32 maxFourByteMatch = 0xFFFF + minFourByteMatch;
/* /*
Normaliazation Example: If MIN_MATCH is 3 then 3 gets mapped to 2 and 16 gets mapped to 15. Normaliazation Example: If MIN_MATCH is 3 then 3 gets mapped to 2 and 16 gets mapped to 15.
@@ -59,36 +59,36 @@ uint32_t LZType11::compress(const uint8_t* src, uint8_t** dst, uint32_t srcLengt
In the four byte case the first 4 bits a 0001 In the four byte case the first 4 bits a 0001
*/ */
while (ptrStart < ptrEnd) { while (ptrStart < ptrEnd) {
uint8_t blockSize = 0; atUint8 blockSize = 0;
// In Binary represents 1 if byte is compressed or 0 if not compressed // In Binary represents 1 if byte is compressed or 0 if not compressed
// For example 01001000 means that the second and fifth byte in the blockSize from the left is compressed // For example 01001000 means that the second and fifth byte in the blockSize from the left is compressed
uint8_t* ptrBytes = compressedBytes.get(); atUint8* ptrBytes = compressedBytes.get();
for (int32_t i = 0; i < m_blockSize; i++) { for (atInt32 i = 0; i < m_blockSize; i++) {
// length_offset searchResult=Search(filedata,ptrStart,ptrEnd); // length_offset searchResult=Search(filedata,ptrStart,ptrEnd);
const LZLengthOffset searchResult = m_lookupTable.search(ptrStart, src, ptrEnd); const LZLengthOffset searchResult = m_lookupTable.search(ptrStart, src, ptrEnd);
// If the number of bytes to be compressed is at least the size of the Minimum match // If the number of bytes to be compressed is at least the size of the Minimum match
if (searchResult.length >= static_cast<uint32_t>(m_minMatch)) { if (searchResult.length >= static_cast<atUint32>(m_minMatch)) {
// Gotta swap the bytes since system is wii is big endian and most computers are little endian // Gotta swap the bytes since system is wii is big endian and most computers are little endian
if (searchResult.length <= maxTwoByteMatch) { if (searchResult.length <= maxTwoByteMatch) {
uint16_t lenOff = ((((searchResult.length - 1) & 0xF) << 12) | // Bits 15-12 atUint16 lenOff = ((((searchResult.length - 1) & 0xF) << 12) | // Bits 15-12
((searchResult.offset - 1) & 0xFFF) // Bits 11-0 ((searchResult.offset - 1) & 0xFFF) // Bits 11-0
); );
athena::utility::BigUint16(lenOff); athena::utility::BigUint16(lenOff);
memcpy(ptrBytes, &lenOff, 2); memcpy(ptrBytes, &lenOff, 2);
ptrBytes += 2; ptrBytes += 2;
} else if (searchResult.length <= maxThreeByteMatch) { } else if (searchResult.length <= maxThreeByteMatch) {
uint32_t lenOff = ((((searchResult.length - minThreeByteMatch) & 0xFF) << 12) | // Bits 20-12 atUint32 lenOff = ((((searchResult.length - minThreeByteMatch) & 0xFF) << 12) | // Bits 20-12
((searchResult.offset - 1) & 0xFFF) // Bits 11-0 ((searchResult.offset - 1) & 0xFFF) // Bits 11-0
); );
athena::utility::BigUint32(lenOff); athena::utility::BigUint32(lenOff);
memcpy(ptrBytes, reinterpret_cast<uint8_t*>(&lenOff) + 1, memcpy(ptrBytes, reinterpret_cast<atUint8*>(&lenOff) + 1,
3); // Make sure to copy the lower 24 bits. 0x12345678- This statement copies 0x123456 3); // Make sure to copy the lower 24 bits. 0x12345678- This statement copies 0x123456
ptrBytes += 3; ptrBytes += 3;
} else if (searchResult.length <= static_cast<uint32_t>(maxFourByteMatch)) { } else if (searchResult.length <= static_cast<atUint32>(maxFourByteMatch)) {
uint32_t lenOff = ((1 << 28) | // Bits 31-28 Flag to say that this is four bytes atUint32 lenOff = ((1 << 28) | // Bits 31-28 Flag to say that this is four bytes
(((searchResult.length - minFourByteMatch) & 0xFFFF) << 12) | // Bits 28-12 (((searchResult.length - minFourByteMatch) & 0xFFFF) << 12) | // Bits 28-12
((searchResult.offset - 1) & 0xFFF) // Bits 11-0 ((searchResult.offset - 1) & 0xFFF) // Bits 11-0
); );
@@ -108,7 +108,7 @@ uint32_t LZType11::compress(const uint8_t* src, uint8_t** dst, uint32_t srcLengt
} }
outbuff.writeByte(blockSize); outbuff.writeByte(blockSize);
outbuff.writeUBytes(compressedBytes.get(), static_cast<uint64_t>(ptrBytes - compressedBytes.get())); outbuff.writeUBytes(compressedBytes.get(), static_cast<atUint64>(ptrBytes - compressedBytes.get()));
} }
// Add zeros until the file is a multiple of 4 // Add zeros until the file is a multiple of 4
@@ -117,66 +117,66 @@ uint32_t LZType11::compress(const uint8_t* src, uint8_t** dst, uint32_t srcLengt
} }
*dst = outbuff.data(); *dst = outbuff.data();
return static_cast<uint32_t>(outbuff.length()); return static_cast<atUint32>(outbuff.length());
} }
uint32_t LZType11::decompress(const uint8_t* src, uint8_t** dst, uint32_t srcLength) { atUint32 LZType11::decompress(const atUint8* src, atUint8** dst, atUint32 srcLength) {
if (*src != 0x11) { if (*src != 0x11) {
return 0; return 0;
} }
uint32_t uncompressedLen; atUint32 uncompressedLen;
std::memcpy(&uncompressedLen, src, sizeof(uncompressedLen)); std::memcpy(&uncompressedLen, src, sizeof(uncompressedLen));
athena::utility::LittleUint32(uncompressedLen); // The compressed file has the filesize encoded in little endian athena::utility::LittleUint32(uncompressedLen); // The compressed file has the filesize encoded in little endian
uncompressedLen = uncompressedLen >> 8; // First byte is the encode flag uncompressedLen = uncompressedLen >> 8; // First byte is the encode flag
uint32_t currentOffset = 4; atUint32 currentOffset = 4;
// If the filesize var is zero then the true filesize is over 14MB and must be read in from the next 4 bytes // If the filesize var is zero then the true filesize is over 14MB and must be read in from the next 4 bytes
if (uncompressedLen == 0) { if (uncompressedLen == 0) {
uint32_t filesize; atUint32 filesize;
std::memcpy(&filesize, src + 4, sizeof(filesize)); std::memcpy(&filesize, src + 4, sizeof(filesize));
filesize = athena::utility::LittleUint32(filesize); filesize = athena::utility::LittleUint32(filesize);
currentOffset += 4; currentOffset += 4;
} }
auto uncompressedData = std::unique_ptr<uint8_t[]>(new uint8_t[uncompressedLen]); auto uncompressedData = std::unique_ptr<atUint8[]>(new atUint8[uncompressedLen]);
uint8_t* outputPtr = uncompressedData.get(); atUint8* outputPtr = uncompressedData.get();
uint8_t* outputEndPtr = uncompressedData.get() + uncompressedLen; atUint8* outputEndPtr = uncompressedData.get() + uncompressedLen;
const uint8_t* inputPtr = src + currentOffset; const atUint8* inputPtr = src + currentOffset;
const uint8_t* inputEndPtr = src + srcLength; const atUint8* inputEndPtr = src + srcLength;
LZLengthOffset decoding; LZLengthOffset decoding;
const uint8_t maxTwoByteMatch = 0xF + 1; const atUint8 maxTwoByteMatch = 0xF + 1;
const uint8_t threeByteDenorm = maxTwoByteMatch + 1; // Amount to add to length when compression is 3 bytes const atUint8 threeByteDenorm = maxTwoByteMatch + 1; // Amount to add to length when compression is 3 bytes
const uint16_t maxThreeByteMatch = 0xFF + threeByteDenorm; const atUint16 maxThreeByteMatch = 0xFF + threeByteDenorm;
const uint16_t fourByteDenorm = maxThreeByteMatch + 1; const atUint16 fourByteDenorm = maxThreeByteMatch + 1;
while (inputPtr < inputEndPtr && outputPtr < outputEndPtr) { while (inputPtr < inputEndPtr && outputPtr < outputEndPtr) {
const uint8_t isCompressed = *inputPtr++; const atUint8 isCompressed = *inputPtr++;
for (int32_t i = 0; i < m_blockSize; i++) { for (atInt32 i = 0; i < m_blockSize; i++) {
// Checks to see if the next byte is compressed by looking // Checks to see if the next byte is compressed by looking
// at its binary representation - E.g 10010000 // at its binary representation - E.g 10010000
// This says that the first extracted byte and the four extracted byte is compressed // This says that the first extracted byte and the four extracted byte is compressed
if ((isCompressed >> (7 - i)) & 0x1) { if ((isCompressed >> (7 - i)) & 0x1) {
const uint8_t metaDataSize = *inputPtr >> 4; // Look at the top 4 bits const atUint8 metaDataSize = *inputPtr >> 4; // Look at the top 4 bits
if (metaDataSize >= 2) { // Two Bytes of Length/Offset MetaData if (metaDataSize >= 2) { // Two Bytes of Length/Offset MetaData
uint16_t lenOff = 0; atUint16 lenOff = 0;
memcpy(&lenOff, inputPtr, 2); memcpy(&lenOff, inputPtr, 2);
inputPtr += 2; inputPtr += 2;
athena::utility::BigUint16(lenOff); athena::utility::BigUint16(lenOff);
decoding.length = (lenOff >> 12) + 1; decoding.length = (lenOff >> 12) + 1;
decoding.offset = (lenOff & 0xFFF) + 1; decoding.offset = (lenOff & 0xFFF) + 1;
} else if (metaDataSize == 0) { // Three Bytes of Length/Offset MetaData } else if (metaDataSize == 0) { // Three Bytes of Length/Offset MetaData
uint32_t lenOff = 0; atUint32 lenOff = 0;
memcpy(reinterpret_cast<uint8_t*>(&lenOff) + 1, inputPtr, 3); memcpy(reinterpret_cast<atUint8*>(&lenOff) + 1, inputPtr, 3);
inputPtr += 3; inputPtr += 3;
athena::utility::BigUint32(lenOff); athena::utility::BigUint32(lenOff);
decoding.length = (lenOff >> 12) + threeByteDenorm; decoding.length = (lenOff >> 12) + threeByteDenorm;
decoding.offset = (lenOff & 0xFFF) + 1; decoding.offset = (lenOff & 0xFFF) + 1;
} else if (metaDataSize == 1) { // Four Bytes of Length/Offset MetaData } else if (metaDataSize == 1) { // Four Bytes of Length/Offset MetaData
uint32_t lenOff = 0; atUint32 lenOff = 0;
memcpy(&lenOff, inputPtr, 4); memcpy(&lenOff, inputPtr, 4);
inputPtr += 4; inputPtr += 4;
athena::utility::BigUint32(lenOff); athena::utility::BigUint32(lenOff);

View File

@@ -7,7 +7,7 @@ ALTTPFile::ALTTPFile() {}
ALTTPFile::ALTTPFile(std::vector<ALTTPQuest*> quests, std::vector<ALTTPQuest*> backup) ALTTPFile::ALTTPFile(std::vector<ALTTPQuest*> quests, std::vector<ALTTPQuest*> backup)
: m_quests(quests), m_backup(backup) {} : m_quests(quests), m_backup(backup) {}
void ALTTPFile::setQuest(uint32_t id, ALTTPQuest* val) { void ALTTPFile::setQuest(atUint32 id, ALTTPQuest* val) {
if (id > m_quests.size()) { if (id > m_quests.size()) {
atWarning("index out of range"); atWarning("index out of range");
return; return;
@@ -17,7 +17,7 @@ void ALTTPFile::setQuest(uint32_t id, ALTTPQuest* val) {
} }
std::vector<ALTTPQuest*> ALTTPFile::questList() const { return m_quests; } std::vector<ALTTPQuest*> ALTTPFile::questList() const { return m_quests; }
ALTTPQuest* ALTTPFile::quest(uint32_t id) const { ALTTPQuest* ALTTPFile::quest(atUint32 id) const {
if (id > m_quests.size()) { if (id > m_quests.size()) {
atWarning("index out of range"); atWarning("index out of range");
return nullptr; return nullptr;
@@ -26,5 +26,5 @@ ALTTPQuest* ALTTPFile::quest(uint32_t id) const {
return m_quests[id]; return m_quests[id];
} }
uint32_t ALTTPFile::questCount() const { return (uint32_t)m_quests.size(); } atUint32 ALTTPFile::questCount() const { return (atUint32)m_quests.size(); }
} // namespace athena } // namespace athena

View File

@@ -6,7 +6,7 @@
namespace athena::io { namespace athena::io {
ALTTPFileReader::ALTTPFileReader(uint8_t* data, uint64_t length) : MemoryCopyReader(data, length) {} ALTTPFileReader::ALTTPFileReader(atUint8* data, atUint64 length) : MemoryCopyReader(data, length) {}
ALTTPFileReader::ALTTPFileReader(const std::string& filename) : MemoryCopyReader(filename) {} ALTTPFileReader::ALTTPFileReader(const std::string& filename) : MemoryCopyReader(filename) {}
@@ -14,16 +14,16 @@ ALTTPFile* ALTTPFileReader::readFile() {
std::vector<ALTTPQuest*> quests; std::vector<ALTTPQuest*> quests;
std::vector<ALTTPQuest*> backup; std::vector<ALTTPQuest*> backup;
for (uint32_t i = 0; i < 6; i++) { for (atUint32 i = 0; i < 6; i++) {
// Temporary values to use for each save // Temporary values to use for each save
ALTTPQuest* quest = new ALTTPQuest(); ALTTPQuest* quest = new ALTTPQuest();
std::vector<ALTTPRoomFlags*> roomFlags; std::vector<ALTTPRoomFlags*> roomFlags;
std::vector<ALTTPOverworldEvent*> owEvents; std::vector<ALTTPOverworldEvent*> owEvents;
std::vector<uint8_t> dungeonKeys; std::vector<atUint8> dungeonKeys;
std::vector<uint8_t> oldmanFlags; std::vector<atUint8> oldmanFlags;
std::vector<uint8_t> unknown1; std::vector<atUint8> unknown1;
std::vector<uint16_t> playerName; std::vector<atUint16> playerName;
std::vector<uint16_t> dungeonDeaths; std::vector<atUint16> dungeonDeaths;
int j = 0x140; int j = 0x140;
@@ -55,7 +55,7 @@ ALTTPFile* ALTTPFileReader::readFile() {
quest->setArrowUpgrades(readByte()); quest->setArrowUpgrades(readByte());
quest->setHealthFiller(readByte()); quest->setHealthFiller(readByte());
quest->setMagicFiller(readByte()); quest->setMagicFiller(readByte());
uint8_t pendantsByte = readUByte(); atUint8 pendantsByte = readUByte();
ALTTPPendants pendants; ALTTPPendants pendants;
pendants.Courage = pendantsByte & 1; pendants.Courage = pendantsByte & 1;
pendants.Wisdom = (pendantsByte >> 1) & 1; pendants.Wisdom = (pendantsByte >> 1) & 1;
@@ -70,7 +70,7 @@ ALTTPFile* ALTTPFileReader::readFile() {
quest->setArrowFiller(readByte()); quest->setArrowFiller(readByte());
quest->setArrows(readByte()); quest->setArrows(readByte());
seek(1); seek(1);
uint8_t abilitiesByte = readUByte(); atUint8 abilitiesByte = readUByte();
ALTTPAbilities abilities; ALTTPAbilities abilities;
abilities.Nothing = abilitiesByte & 1; abilities.Nothing = abilitiesByte & 1;
abilities.Swim = (abilitiesByte >> 1) & 1; abilities.Swim = (abilitiesByte >> 1) & 1;
@@ -154,7 +154,7 @@ ALTTPFile* ALTTPFileReader::readFile() {
ALTTPRoomFlags* ALTTPFileReader::readRoomFlags() { ALTTPRoomFlags* ALTTPFileReader::readRoomFlags() {
ALTTPRoomFlags* flags = new ALTTPRoomFlags; ALTTPRoomFlags* flags = new ALTTPRoomFlags;
uint8_t flagsByte = readUByte(); atUint8 flagsByte = readUByte();
flags->Chest1 = flagsByte & 1; flags->Chest1 = flagsByte & 1;
flags->Chest2 = (flagsByte >> 1) & 1; flags->Chest2 = (flagsByte >> 1) & 1;
flags->Chest3 = (flagsByte >> 2) & 1; flags->Chest3 = (flagsByte >> 2) & 1;
@@ -178,7 +178,7 @@ ALTTPRoomFlags* ALTTPFileReader::readRoomFlags() {
ALTTPOverworldEvent* ALTTPFileReader::readOverworldEvent() { ALTTPOverworldEvent* ALTTPFileReader::readOverworldEvent() {
ALTTPOverworldEvent* event = new ALTTPOverworldEvent; ALTTPOverworldEvent* event = new ALTTPOverworldEvent;
uint8_t flagsByte = readUByte(); atUint8 flagsByte = readUByte();
event->Unused1 = flagsByte & 1; event->Unused1 = flagsByte & 1;
event->HeartPiece = (flagsByte >> 1) & 1; event->HeartPiece = (flagsByte >> 1) & 1;
event->Overlay = (flagsByte >> 2) & 1; event->Overlay = (flagsByte >> 2) & 1;
@@ -192,7 +192,7 @@ ALTTPOverworldEvent* ALTTPFileReader::readOverworldEvent() {
ALTTPDungeonItemFlags ALTTPFileReader::readDungeonFlags() { ALTTPDungeonItemFlags ALTTPFileReader::readDungeonFlags() {
ALTTPDungeonItemFlags flags; ALTTPDungeonItemFlags flags;
uint8_t flagsByte = readUByte(); atUint8 flagsByte = readUByte();
flags.Unused1 = flagsByte & 1; flags.Unused1 = flagsByte & 1;
flags.Unused2 = (flagsByte >> 1) & 1; flags.Unused2 = (flagsByte >> 1) & 1;
flags.GanonsTower = (flagsByte >> 2) & 1; flags.GanonsTower = (flagsByte >> 2) & 1;

View File

@@ -7,14 +7,14 @@ namespace athena {
namespace io { namespace io {
ALTTPFileWriter::ALTTPFileWriter(uint8_t* data, uint64_t length) : MemoryCopyWriter(data, length) {} ALTTPFileWriter::ALTTPFileWriter(atUint8* data, atUint64 length) : MemoryCopyWriter(data, length) {}
ALTTPFileWriter::ALTTPFileWriter(const std::string& filename) : MemoryCopyWriter(filename) {} ALTTPFileWriter::ALTTPFileWriter(const std::string& filename) : MemoryCopyWriter(filename) {}
void ALTTPFileWriter::writeFile(ALTTPFile* file) { void ALTTPFileWriter::writeFile(ALTTPFile* file) {
ALTTPQuest* quest = NULL; ALTTPQuest* quest = NULL;
for (uint32_t i = 0; i < 6; i++) { for (atUint32 i = 0; i < 6; i++) {
if (i < 3) if (i < 3)
quest = file->quest(i); quest = file->quest(i);
else else
@@ -28,7 +28,7 @@ void ALTTPFileWriter::writeFile(ALTTPFile* file) {
writeOverworldEvent(quest->overworldEvent(j)); writeOverworldEvent(quest->overworldEvent(j));
} }
writeBytes((int8_t*)&quest->inventory(), sizeof(ALTTPInventory)); writeBytes((atInt8*)&quest->inventory(), sizeof(ALTTPInventory));
writeUint16(quest->rupeeMax()); writeUint16(quest->rupeeMax());
writeUint16(quest->rupeeCurrent()); writeUint16(quest->rupeeCurrent());
writeDungeonItems(quest->compasses()); writeDungeonItems(quest->compasses());
@@ -44,7 +44,7 @@ void ALTTPFileWriter::writeFile(ALTTPFile* file) {
writeByte(quest->healthFiller()); writeByte(quest->healthFiller());
writeByte(quest->magicFiller()); writeByte(quest->magicFiller());
ALTTPPendants pendants = quest->pendants(); ALTTPPendants pendants = quest->pendants();
uint8_t pendantsByte = 0; atUint8 pendantsByte = 0;
pendantsByte |= pendants.Courage; pendantsByte |= pendants.Courage;
pendantsByte |= pendants.Wisdom << 1; pendantsByte |= pendants.Wisdom << 1;
pendantsByte |= pendants.Power << 2; pendantsByte |= pendants.Power << 2;
@@ -54,7 +54,7 @@ void ALTTPFileWriter::writeFile(ALTTPFile* file) {
writeByte(quest->arrows()); writeByte(quest->arrows());
seek(1); seek(1);
ALTTPAbilities abilities = quest->abilityFlags(); ALTTPAbilities abilities = quest->abilityFlags();
uint8_t abilitiesByte = 0; atUint8 abilitiesByte = 0;
abilitiesByte |= abilities.Nothing; abilitiesByte |= abilities.Nothing;
abilitiesByte |= abilities.Swim << 1; abilitiesByte |= abilities.Swim << 1;
abilitiesByte |= abilities.Dash << 2; abilitiesByte |= abilities.Dash << 2;
@@ -65,23 +65,23 @@ void ALTTPFileWriter::writeFile(ALTTPFile* file) {
abilitiesByte |= abilities.Unknown2 << 7; abilitiesByte |= abilities.Unknown2 << 7;
writeUByte(abilitiesByte); writeUByte(abilitiesByte);
ALTTPCrystals crystals = quest->crystals(); ALTTPCrystals crystals = quest->crystals();
writeBytes((int8_t*)&crystals, sizeof(ALTTPCrystals)); writeBytes((atInt8*)&crystals, sizeof(ALTTPCrystals));
ALTTPMagicUsage magicUsage = quest->magicUsage(); ALTTPMagicUsage magicUsage = quest->magicUsage();
writeBytes((int8_t*)&magicUsage, sizeof(ALTTPMagicUsage)); writeBytes((atInt8*)&magicUsage, sizeof(ALTTPMagicUsage));
for (int j = 0; j < 0x010; j++) for (int j = 0; j < 0x010; j++)
writeByte(quest->dungeonKeys(j)); writeByte(quest->dungeonKeys(j));
seek(0x039); seek(0x039);
writeByte((int8_t)quest->progressIndicator()); writeByte((atInt8)quest->progressIndicator());
ALTTPProgressFlags1 progress1 = quest->progressFlags1(); ALTTPProgressFlags1 progress1 = quest->progressFlags1();
writeBytes((int8_t*)&progress1, sizeof(ALTTPProgressFlags1)); writeBytes((atInt8*)&progress1, sizeof(ALTTPProgressFlags1));
writeByte(quest->mapIcon()); writeByte(quest->mapIcon());
writeByte(quest->startLocation()); writeByte(quest->startLocation());
ALTTPProgressFlags2 progress2 = quest->progressFlags2(); ALTTPProgressFlags2 progress2 = quest->progressFlags2();
writeBytes((int8_t*)&progress2, sizeof(ALTTPProgressFlags2)); writeBytes((atInt8*)&progress2, sizeof(ALTTPProgressFlags2));
ALTTPLightDarkWorldIndicator indicator = quest->lightDarkWorldIndicator(); ALTTPLightDarkWorldIndicator indicator = quest->lightDarkWorldIndicator();
writeBytes((int8_t*)&indicator, 1); writeBytes((atInt8*)&indicator, 1);
seek(1); seek(1);
writeByte(quest->tagAlong()); writeByte(quest->tagAlong());
@@ -111,7 +111,7 @@ void ALTTPFileWriter::writeFile(ALTTPFile* file) {
} }
void ALTTPFileWriter::writeRoomFlags(ALTTPRoomFlags* flags) { void ALTTPFileWriter::writeRoomFlags(ALTTPRoomFlags* flags) {
uint8_t flagsByte = 0; atUint8 flagsByte = 0;
flagsByte |= flags->Chest1; flagsByte |= flags->Chest1;
flagsByte |= flags->Chest2 << 1; flagsByte |= flags->Chest2 << 1;
flagsByte |= flags->Chest3 << 2; flagsByte |= flags->Chest3 << 2;
@@ -134,7 +134,7 @@ void ALTTPFileWriter::writeRoomFlags(ALTTPRoomFlags* flags) {
} }
void ALTTPFileWriter::writeOverworldEvent(ALTTPOverworldEvent* event) { void ALTTPFileWriter::writeOverworldEvent(ALTTPOverworldEvent* event) {
uint8_t flagsByte = 0; atUint8 flagsByte = 0;
flagsByte |= event->Unused1; flagsByte |= event->Unused1;
flagsByte |= event->HeartPiece << 1; flagsByte |= event->HeartPiece << 1;
flagsByte |= event->Overlay << 2; flagsByte |= event->Overlay << 2;
@@ -147,7 +147,7 @@ void ALTTPFileWriter::writeOverworldEvent(ALTTPOverworldEvent* event) {
} }
void ALTTPFileWriter::writeDungeonItems(ALTTPDungeonItemFlags flags) { void ALTTPFileWriter::writeDungeonItems(ALTTPDungeonItemFlags flags) {
uint8_t flagsByte = 0; atUint8 flagsByte = 0;
flagsByte |= flags.Unused1; flagsByte |= flags.Unused1;
flagsByte |= flags.Unused2 << 1; flagsByte |= flags.Unused2 << 1;
flagsByte |= flags.GanonsTower << 2; flagsByte |= flags.GanonsTower << 2;
@@ -168,7 +168,7 @@ void ALTTPFileWriter::writeDungeonItems(ALTTPDungeonItemFlags flags) {
writeUByte(flagsByte); writeUByte(flagsByte);
} }
uint16_t ALTTPFileWriter::calculateChecksum(uint32_t game) { atUint16 ALTTPFileWriter::calculateChecksum(atUint32 game) {
/* /*
* ALTTP's checksum is very basic * ALTTP's checksum is very basic
* It adds each word up and then subtracts the sum from 0x5a5a * It adds each word up and then subtracts the sum from 0x5a5a
@@ -185,11 +185,11 @@ uint16_t ALTTPFileWriter::calculateChecksum(uint32_t game) {
*/ */
// First we start at 0 // First we start at 0
uint16_t sum = 0; atUint16 sum = 0;
for (uint32_t i = 0; i < 0x4FE; i += 2) for (atUint32 i = 0; i < 0x4FE; i += 2)
// Add each word one by one // Add each word one by one
sum += *(uint16_t*)(m_data + (i + (0x500 * game))); sum += *(atUint16*)(m_data + (i + (0x500 * game)));
// Subtract it from 0x5a5a to get our true checksum // Subtract it from 0x5a5a to get our true checksum
return (0x5a5a - sum); return (0x5a5a - sum);

View File

@@ -15,19 +15,19 @@ ALTTPQuest::~ALTTPQuest() {
void ALTTPQuest::setRoomFlags(std::vector<ALTTPRoomFlags*> rf) { m_roomFlags = rf; } void ALTTPQuest::setRoomFlags(std::vector<ALTTPRoomFlags*> rf) { m_roomFlags = rf; }
void ALTTPQuest::setRoomFlags(ALTTPRoomFlags* rf, uint32_t id) { m_roomFlags[id] = rf; } void ALTTPQuest::setRoomFlags(ALTTPRoomFlags* rf, atUint32 id) { m_roomFlags[id] = rf; }
std::vector<ALTTPRoomFlags*> ALTTPQuest::roomFlags() { return m_roomFlags; } std::vector<ALTTPRoomFlags*> ALTTPQuest::roomFlags() { return m_roomFlags; }
ALTTPRoomFlags* ALTTPQuest::roomFlags(uint32_t id) { return m_roomFlags[id]; } ALTTPRoomFlags* ALTTPQuest::roomFlags(atUint32 id) { return m_roomFlags[id]; }
void ALTTPQuest::setOverworldEvents(std::vector<ALTTPOverworldEvent*> ow) { m_overworldEvents = ow; } void ALTTPQuest::setOverworldEvents(std::vector<ALTTPOverworldEvent*> ow) { m_overworldEvents = ow; }
void ALTTPQuest::setOverworldEvents(ALTTPOverworldEvent* ow, uint32_t id) { m_overworldEvents[id] = ow; } void ALTTPQuest::setOverworldEvents(ALTTPOverworldEvent* ow, atUint32 id) { m_overworldEvents[id] = ow; }
std::vector<ALTTPOverworldEvent*> ALTTPQuest::overworldEvents() const { return m_overworldEvents; } std::vector<ALTTPOverworldEvent*> ALTTPQuest::overworldEvents() const { return m_overworldEvents; }
ALTTPOverworldEvent* ALTTPQuest::overworldEvent(uint32_t id) const { ALTTPOverworldEvent* ALTTPQuest::overworldEvent(atUint32 id) const {
if (id > m_overworldEvents.size() - 1) { if (id > m_overworldEvents.size() - 1) {
atWarning("index out of range"); atWarning("index out of range");
return nullptr; return nullptr;
@@ -40,13 +40,13 @@ void ALTTPQuest::setInventory(const ALTTPInventory& inv) { m_inventory = inv; }
const ALTTPInventory& ALTTPQuest::inventory() const { return m_inventory; } const ALTTPInventory& ALTTPQuest::inventory() const { return m_inventory; }
void ALTTPQuest::setRupeeMax(uint16_t val) { m_rupeeMax = val; } void ALTTPQuest::setRupeeMax(atUint16 val) { m_rupeeMax = val; }
uint16_t ALTTPQuest::rupeeMax() const { return m_rupeeMax; } atUint16 ALTTPQuest::rupeeMax() const { return m_rupeeMax; }
void ALTTPQuest::setRupeeCurrent(uint16_t val) { m_rupeeCurrent = val; } void ALTTPQuest::setRupeeCurrent(atUint16 val) { m_rupeeCurrent = val; }
uint16_t ALTTPQuest::rupeeCurrent() const { return m_rupeeCurrent; } atUint16 ALTTPQuest::rupeeCurrent() const { return m_rupeeCurrent; }
void ALTTPQuest::setCompasses(ALTTPDungeonItemFlags flags) { m_compasses = flags; } void ALTTPQuest::setCompasses(ALTTPDungeonItemFlags flags) { m_compasses = flags; }
@@ -60,55 +60,55 @@ void ALTTPQuest::setDungeonMaps(ALTTPDungeonItemFlags flags) { m_dungeonMaps = f
ALTTPDungeonItemFlags ALTTPQuest::dungeonMaps() const { return m_dungeonMaps; } ALTTPDungeonItemFlags ALTTPQuest::dungeonMaps() const { return m_dungeonMaps; }
void ALTTPQuest::setWishingPond(uint16_t val) { m_wishingPond = val; } void ALTTPQuest::setWishingPond(atUint16 val) { m_wishingPond = val; }
uint16_t ALTTPQuest::wishingPond() const { return m_wishingPond; } atUint16 ALTTPQuest::wishingPond() const { return m_wishingPond; }
void ALTTPQuest::setHealthMax(uint8_t val) { m_healthMax = val; } void ALTTPQuest::setHealthMax(atUint8 val) { m_healthMax = val; }
uint8_t ALTTPQuest::healthMax() const { return m_healthMax; } atUint8 ALTTPQuest::healthMax() const { return m_healthMax; }
void ALTTPQuest::setHealth(uint8_t val) { m_health = val; } void ALTTPQuest::setHealth(atUint8 val) { m_health = val; }
uint8_t ALTTPQuest::health() const { return m_health; } atUint8 ALTTPQuest::health() const { return m_health; }
void ALTTPQuest::setMagicPower(uint8_t val) { m_magicPower = val; } void ALTTPQuest::setMagicPower(atUint8 val) { m_magicPower = val; }
uint8_t ALTTPQuest::magicPower() const { return m_magicPower; } atUint8 ALTTPQuest::magicPower() const { return m_magicPower; }
void ALTTPQuest::setKeys(uint8_t val) { m_keys = val; } void ALTTPQuest::setKeys(atUint8 val) { m_keys = val; }
uint8_t ALTTPQuest::keys() const { return m_keys; } atUint8 ALTTPQuest::keys() const { return m_keys; }
void ALTTPQuest::setBombUpgrades(uint8_t val) { m_bombUpgrades = val; } void ALTTPQuest::setBombUpgrades(atUint8 val) { m_bombUpgrades = val; }
uint8_t ALTTPQuest::bombUpgrades() const { return m_bombUpgrades; } atUint8 ALTTPQuest::bombUpgrades() const { return m_bombUpgrades; }
void ALTTPQuest::setArrowUpgrades(uint8_t val) { m_arrowUpgrades = val; } void ALTTPQuest::setArrowUpgrades(atUint8 val) { m_arrowUpgrades = val; }
uint8_t ALTTPQuest::arrowUpgrades() const { return m_arrowUpgrades; } atUint8 ALTTPQuest::arrowUpgrades() const { return m_arrowUpgrades; }
void ALTTPQuest::setHealthFiller(uint8_t val) { m_heartFiller = val; } void ALTTPQuest::setHealthFiller(atUint8 val) { m_heartFiller = val; }
uint8_t ALTTPQuest::healthFiller() const { return m_heartFiller; } atUint8 ALTTPQuest::healthFiller() const { return m_heartFiller; }
void ALTTPQuest::setMagicFiller(uint8_t val) { m_heartFiller = val; } void ALTTPQuest::setMagicFiller(atUint8 val) { m_heartFiller = val; }
uint8_t ALTTPQuest::magicFiller() const { return m_heartFiller; } atUint8 ALTTPQuest::magicFiller() const { return m_heartFiller; }
void ALTTPQuest::setPendants(ALTTPPendants val) { m_pendants = val; } void ALTTPQuest::setPendants(ALTTPPendants val) { m_pendants = val; }
ALTTPPendants ALTTPQuest::pendants() const { return m_pendants; } ALTTPPendants ALTTPQuest::pendants() const { return m_pendants; }
void ALTTPQuest::setBombFiller(uint8_t val) { m_bombFiller = val; } void ALTTPQuest::setBombFiller(atUint8 val) { m_bombFiller = val; }
uint8_t ALTTPQuest::bombFiller() const { return m_bombFiller; } atUint8 ALTTPQuest::bombFiller() const { return m_bombFiller; }
void ALTTPQuest::setArrowFiller(uint8_t val) { m_arrowFiller = val; } void ALTTPQuest::setArrowFiller(atUint8 val) { m_arrowFiller = val; }
uint8_t ALTTPQuest::arrowFiller() const { return m_arrowFiller; } atUint8 ALTTPQuest::arrowFiller() const { return m_arrowFiller; }
void ALTTPQuest::setArrows(uint8_t val) { m_arrows = val; } void ALTTPQuest::setArrows(atUint8 val) { m_arrows = val; }
uint8_t ALTTPQuest::arrows() const { return m_arrows; } atUint8 ALTTPQuest::arrows() const { return m_arrows; }
void ALTTPQuest::setAbilityFlags(ALTTPAbilities val) { m_abilityFlags = val; } void ALTTPQuest::setAbilityFlags(ALTTPAbilities val) { m_abilityFlags = val; }
@@ -122,9 +122,9 @@ void ALTTPQuest::setMagicUsage(ALTTPMagicUsage val) { m_magicUsage = val; }
ALTTPMagicUsage ALTTPQuest::magicUsage() const { return m_magicUsage; } ALTTPMagicUsage ALTTPQuest::magicUsage() const { return m_magicUsage; }
void ALTTPQuest::setDungeonKeys(std::vector<uint8_t> val) { m_dungeonKeys = val; } void ALTTPQuest::setDungeonKeys(std::vector<atUint8> val) { m_dungeonKeys = val; }
void ALTTPQuest::setDungeonKeys(uint32_t id, uint8_t val) { void ALTTPQuest::setDungeonKeys(atUint32 id, atUint8 val) {
if (id > m_dungeonKeys.size() - 1) { if (id > m_dungeonKeys.size() - 1) {
atWarning("index out of range"); atWarning("index out of range");
return; return;
@@ -133,7 +133,7 @@ void ALTTPQuest::setDungeonKeys(uint32_t id, uint8_t val) {
m_dungeonKeys[id] = val; m_dungeonKeys[id] = val;
} }
uint8_t ALTTPQuest::dungeonKeys(uint32_t id) const { atUint8 ALTTPQuest::dungeonKeys(atUint32 id) const {
if (id > m_dungeonKeys.size() - 1) { if (id > m_dungeonKeys.size() - 1) {
atWarning("index out of range"); atWarning("index out of range");
return 0; return 0;
@@ -142,7 +142,7 @@ uint8_t ALTTPQuest::dungeonKeys(uint32_t id) const {
return m_dungeonKeys[id]; return m_dungeonKeys[id];
} }
uint32_t ALTTPQuest::dungeonCount() const { return (uint32_t)m_dungeonKeys.size(); } atUint32 ALTTPQuest::dungeonCount() const { return (atUint32)m_dungeonKeys.size(); }
void ALTTPQuest::setProgressIndicator(ALTTPProgressIndicator val) { m_progressIndicator = val; } void ALTTPQuest::setProgressIndicator(ALTTPProgressIndicator val) { m_progressIndicator = val; }
@@ -172,9 +172,9 @@ void ALTTPQuest::setTagAlong(ALTTPTagAlong val) { m_tagAlong = val; }
ALTTPTagAlong ALTTPQuest::tagAlong() const { return m_tagAlong; } ALTTPTagAlong ALTTPQuest::tagAlong() const { return m_tagAlong; }
void ALTTPQuest::setOldManFlags(std::vector<uint8_t> flags) { m_oldManFlags = flags; } void ALTTPQuest::setOldManFlags(std::vector<atUint8> flags) { m_oldManFlags = flags; }
void ALTTPQuest::setOldManFlag(uint32_t id, uint8_t val) { void ALTTPQuest::setOldManFlag(atUint32 id, atUint8 val) {
if (id > m_oldManFlags.size() - 1) { if (id > m_oldManFlags.size() - 1) {
atWarning("index out of range"); atWarning("index out of range");
return; return;
@@ -183,7 +183,7 @@ void ALTTPQuest::setOldManFlag(uint32_t id, uint8_t val) {
m_oldManFlags[id] = val; m_oldManFlags[id] = val;
} }
uint8_t ALTTPQuest::oldManFlag(uint32_t id) { atUint8 ALTTPQuest::oldManFlag(atUint32 id) {
if (id > m_oldManFlags.size() - 1) { if (id > m_oldManFlags.size() - 1) {
atWarning("index out of range"); atWarning("index out of range");
return 0; return 0;
@@ -191,15 +191,15 @@ uint8_t ALTTPQuest::oldManFlag(uint32_t id) {
return m_oldManFlags[id]; return m_oldManFlags[id];
} }
uint32_t ALTTPQuest::oldManFlagCount() const { return (uint32_t)m_oldManFlags.size(); } atUint32 ALTTPQuest::oldManFlagCount() const { return (atUint32)m_oldManFlags.size(); }
void ALTTPQuest::setBombFlag(uint8_t flag) { m_bombFlag = flag; } void ALTTPQuest::setBombFlag(atUint8 flag) { m_bombFlag = flag; }
uint8_t ALTTPQuest::bombFlag() const { return m_bombFlag; } atUint8 ALTTPQuest::bombFlag() const { return m_bombFlag; }
void ALTTPQuest::setUnknown1(std::vector<uint8_t> flags) { m_unknown1 = flags; } void ALTTPQuest::setUnknown1(std::vector<atUint8> flags) { m_unknown1 = flags; }
void ALTTPQuest::setUnknown1(uint32_t id, uint8_t val) { void ALTTPQuest::setUnknown1(atUint32 id, atUint8 val) {
if (id > m_unknown1.size()) { if (id > m_unknown1.size()) {
atWarning("index out of range"); atWarning("index out of range");
return; return;
@@ -208,7 +208,7 @@ void ALTTPQuest::setUnknown1(uint32_t id, uint8_t val) {
m_unknown1[id] = val; m_unknown1[id] = val;
} }
uint8_t ALTTPQuest::unknown1(uint32_t id) { atUint8 ALTTPQuest::unknown1(atUint32 id) {
if (id > m_unknown1.size()) { if (id > m_unknown1.size()) {
atWarning("index out of range"); atWarning("index out of range");
return 0; return 0;
@@ -217,9 +217,9 @@ uint8_t ALTTPQuest::unknown1(uint32_t id) {
return m_unknown1[id]; return m_unknown1[id];
} }
uint32_t ALTTPQuest::unknown1Count() const { return (uint32_t)m_unknown1.size(); } atUint32 ALTTPQuest::unknown1Count() const { return (atUint32)m_unknown1.size(); }
void ALTTPQuest::setPlayerName(std::vector<uint16_t> playerName) { m_playerName = playerName; } void ALTTPQuest::setPlayerName(std::vector<atUint16> playerName) { m_playerName = playerName; }
void ALTTPQuest::setPlayerName(const std::string& playerName) { void ALTTPQuest::setPlayerName(const std::string& playerName) {
if (playerName == std::string() || playerName.size() > 6) { if (playerName == std::string() || playerName.size() > 6) {
@@ -229,9 +229,9 @@ void ALTTPQuest::setPlayerName(const std::string& playerName) {
m_playerName.clear(); m_playerName.clear();
for (uint32_t i = 0; i < 6; i++) { for (atUint32 i = 0; i < 6; i++) {
if (i > playerName.size() - 1) { if (i > playerName.size() - 1) {
m_playerName.push_back((uint16_t)0xA9); m_playerName.push_back((atUint16)0xA9);
continue; continue;
} }
@@ -239,19 +239,19 @@ void ALTTPQuest::setPlayerName(const std::string& playerName) {
if (c >= 'A' && c <= 'P' && c != 'I') { if (c >= 'A' && c <= 'P' && c != 'I') {
m_playerName.push_back((uint16_t)(c - 'A')); m_playerName.push_back((atUint16)(c - 'A'));
continue; continue;
} }
if (c >= 'Q' && c <= 'Z') { if (c >= 'Q' && c <= 'Z') {
std::cout << std::hex << (uint16_t)((c - 'Q') + 0x20) << std::endl; std::cout << std::hex << (atUint16)((c - 'Q') + 0x20) << std::endl;
m_playerName.push_back((uint16_t)((c - 'Q') + 0x20)); m_playerName.push_back((atUint16)((c - 'Q') + 0x20));
continue; continue;
} }
if (c >= 'a' && c <= 'f') { if (c >= 'a' && c <= 'f') {
std::cout << std::hex << (uint16_t)((c - 'a') + 0x2A) << std::endl; std::cout << std::hex << (atUint16)((c - 'a') + 0x2A) << std::endl;
m_playerName.push_back((uint16_t)((c - 'a') + 0x2A)); m_playerName.push_back((atUint16)((c - 'a') + 0x2A));
continue; continue;
} }
@@ -266,22 +266,22 @@ void ALTTPQuest::setPlayerName(const std::string& playerName) {
continue; continue;
} }
m_playerName.push_back((uint16_t)((c - 'g') + 0x40)); m_playerName.push_back((atUint16)((c - 'g') + 0x40));
continue; continue;
} }
if (c >= 'w' && c <= 'z') { if (c >= 'w' && c <= 'z') {
m_playerName.push_back((uint16_t)((c - 'w') + 0x60)); m_playerName.push_back((atUint16)((c - 'w') + 0x60));
continue; continue;
} }
if (c >= '0' && c <= '9') { if (c >= '0' && c <= '9') {
m_playerName.push_back((uint16_t)((c - '0') + 0x64)); m_playerName.push_back((atUint16)((c - '0') + 0x64));
continue; continue;
} }
if (c == '-' || c == '.') { if (c == '-' || c == '.') {
m_playerName.push_back((uint16_t)(c - '-') + 0x80); m_playerName.push_back((atUint16)(c - '-') + 0x80);
continue; continue;
} }
@@ -313,12 +313,12 @@ void ALTTPQuest::setPlayerName(const std::string& playerName) {
} }
} }
std::vector<uint16_t> ALTTPQuest::playerName() const { return m_playerName; } std::vector<atUint16> ALTTPQuest::playerName() const { return m_playerName; }
std::string ALTTPQuest::playerNameToString() const { std::string ALTTPQuest::playerNameToString() const {
std::string ret; std::string ret;
for (int16_t c : m_playerName) { for (atInt16 c : m_playerName) {
if (c >= 0x00 && c <= 0x0F) { if (c >= 0x00 && c <= 0x0F) {
ret.push_back((char)('A' + c)); ret.push_back((char)('A' + c));
continue; continue;
@@ -397,9 +397,9 @@ void ALTTPQuest::setValid(bool val) { m_valid = val; }
bool ALTTPQuest::valid() { return m_valid; } bool ALTTPQuest::valid() { return m_valid; }
void ALTTPQuest::setDungeonDeathTotals(std::vector<uint16_t> val) { m_dungeonDeathTotals = val; } void ALTTPQuest::setDungeonDeathTotals(std::vector<atUint16> val) { m_dungeonDeathTotals = val; }
void ALTTPQuest::setDungeonDeathTotal(uint32_t id, uint16_t val) { void ALTTPQuest::setDungeonDeathTotal(atUint32 id, atUint16 val) {
if (id > m_dungeonDeathTotals.size()) { if (id > m_dungeonDeathTotals.size()) {
atWarning("index out of range"); atWarning("index out of range");
return; return;
@@ -408,7 +408,7 @@ void ALTTPQuest::setDungeonDeathTotal(uint32_t id, uint16_t val) {
m_dungeonDeathTotals[id] = val; m_dungeonDeathTotals[id] = val;
} }
uint16_t ALTTPQuest::dungeonDeathTotal(uint32_t id) const { atUint16 ALTTPQuest::dungeonDeathTotal(atUint32 id) const {
if (id > m_dungeonDeathTotals.size()) { if (id > m_dungeonDeathTotals.size()) {
atWarning("index out of range"); atWarning("index out of range");
return 0; return 0;
@@ -417,21 +417,21 @@ uint16_t ALTTPQuest::dungeonDeathTotal(uint32_t id) const {
return m_dungeonDeathTotals[id]; return m_dungeonDeathTotals[id];
} }
uint16_t ALTTPQuest::dungeonDeathTotalCount() const { return (uint16_t)m_dungeonDeathTotals.size(); } atUint16 ALTTPQuest::dungeonDeathTotalCount() const { return (atUint16)m_dungeonDeathTotals.size(); }
void ALTTPQuest::setUnknown2(uint16_t val) { m_unknown2 = val; } void ALTTPQuest::setUnknown2(atUint16 val) { m_unknown2 = val; }
uint16_t ALTTPQuest::unknown2() const { return m_unknown2; } atUint16 ALTTPQuest::unknown2() const { return m_unknown2; }
void ALTTPQuest::setDeathSaveCount(uint16_t val) { m_deathSaveCount = val; } void ALTTPQuest::setDeathSaveCount(atUint16 val) { m_deathSaveCount = val; }
uint16_t ALTTPQuest::deathSaveCount() const { return m_deathSaveCount; } atUint16 ALTTPQuest::deathSaveCount() const { return m_deathSaveCount; }
void ALTTPQuest::setPostGameDeathCounter(int16_t val) { m_postGameDeathCounter = val; } void ALTTPQuest::setPostGameDeathCounter(atInt16 val) { m_postGameDeathCounter = val; }
int16_t ALTTPQuest::postGameDeathCounter() const { return m_postGameDeathCounter; } atInt16 ALTTPQuest::postGameDeathCounter() const { return m_postGameDeathCounter; }
void ALTTPQuest::setChecksum(uint16_t checksum) { m_checksum = checksum; } void ALTTPQuest::setChecksum(atUint16 checksum) { m_checksum = checksum; }
uint16_t ALTTPQuest::checksum() const { return m_checksum; } atUint16 ALTTPQuest::checksum() const { return m_checksum; }
} // namespace athena } // namespace athena

View File

@@ -1,8 +1,8 @@
#include "athena/Checksums.hpp" #include "athena/Checksums.hpp"
namespace athena::checksums { namespace athena::checksums {
uint64_t crc64(const uint8_t* data, uint64_t length, uint64_t seed, uint64_t final) { atUint64 crc64(const atUint8* data, atUint64 length, atUint64 seed, atUint64 final) {
static const uint64_t crc64Table[256] = { static const atUint64 crc64Table[256] = {
0x0000000000000000, 0x42F0E1EBA9EA3693, 0x85E1C3D753D46D26, 0xC711223CFA3E5BB5, 0x493366450E42ECDF, 0x0000000000000000, 0x42F0E1EBA9EA3693, 0x85E1C3D753D46D26, 0xC711223CFA3E5BB5, 0x493366450E42ECDF,
0x0BC387AEA7A8DA4C, 0xCCD2A5925D9681F9, 0x8E224479F47CB76A, 0x9266CC8A1C85D9BE, 0xD0962D61B56FEF2D, 0x0BC387AEA7A8DA4C, 0xCCD2A5925D9681F9, 0x8E224479F47CB76A, 0x9266CC8A1C85D9BE, 0xD0962D61B56FEF2D,
0x17870F5D4F51B498, 0x5577EEB6E6BB820B, 0xDB55AACF12C73561, 0x99A54B24BB2D03F2, 0x5EB4691841135847, 0x17870F5D4F51B498, 0x5577EEB6E6BB820B, 0xDB55AACF12C73561, 0x99A54B24BB2D03F2, 0x5EB4691841135847,
@@ -60,7 +60,7 @@ uint64_t crc64(const uint8_t* data, uint64_t length, uint64_t seed, uint64_t fin
if (!data) if (!data)
return seed; return seed;
uint64_t checksum = seed; atUint64 checksum = seed;
int pos = 0; int pos = 0;
while (length--) while (length--)
@@ -69,8 +69,8 @@ uint64_t crc64(const uint8_t* data, uint64_t length, uint64_t seed, uint64_t fin
return checksum ^ final; return checksum ^ final;
} }
uint32_t crc32(const uint8_t* data, uint64_t length, uint32_t seed, uint32_t final) { atUint32 crc32(const atUint8* data, atUint64 length, atUint32 seed, atUint32 final) {
static const uint32_t crc32Table[256] = { static const atUint32 crc32Table[256] = {
0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832,
0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2,
0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A,
@@ -104,7 +104,7 @@ uint32_t crc32(const uint8_t* data, uint64_t length, uint32_t seed, uint32_t fin
if (!data) if (!data)
return seed; return seed;
uint32_t checksum = seed; atUint32 checksum = seed;
int pos = 0; int pos = 0;
while (length--) while (length--)
@@ -113,8 +113,8 @@ uint32_t crc32(const uint8_t* data, uint64_t length, uint32_t seed, uint32_t fin
return checksum ^ final; return checksum ^ final;
} }
uint16_t crc16CCITT(const uint8_t* data, uint64_t length, uint16_t seed, uint16_t final) { atUint16 crc16CCITT(const atUint8* data, atUint64 length, atUint16 seed, atUint16 final) {
static const uint16_t crc16CCITTTable[256] = { static const atUint16 crc16CCITTTable[256] = {
0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad,
0xe1ce, 0xf1ef, 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a, 0xe1ce, 0xf1ef, 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a,
0xd3bd, 0xc39c, 0xf3ff, 0xe3de, 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, 0xa56a, 0xb54b, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, 0xa56a, 0xb54b,
@@ -135,7 +135,7 @@ uint16_t crc16CCITT(const uint8_t* data, uint64_t length, uint16_t seed, uint16_
0x1ce0, 0x0cc1, 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x1ce0, 0x0cc1, 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, 0x4e55, 0x5e74,
0x2e93, 0x3eb2, 0x0ed1, 0x1ef0}; 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0};
uint16_t checksum = seed; atUint16 checksum = seed;
int pos = 0; int pos = 0;
while (length--) while (length--)
@@ -144,12 +144,12 @@ uint16_t crc16CCITT(const uint8_t* data, uint64_t length, uint16_t seed, uint16_
return checksum ^ final; return checksum ^ final;
} }
uint16_t crc16(const uint8_t* data, uint64_t length, uint16_t seed, uint64_t final) { atUint16 crc16(const atUint8* data, atUint64 length, atUint16 seed, atUint64 final) {
if (data == nullptr) { if (data == nullptr) {
return seed; return seed;
} }
static const uint16_t crc16Table[256] = { static const atUint16 crc16Table[256] = {
0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241, 0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241, 0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1,
0xC481, 0x0440, 0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40, 0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC481, 0x0440, 0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40, 0x0A00, 0xCAC1, 0xCB81, 0x0B40,
0xC901, 0x09C0, 0x0880, 0xC841, 0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40, 0x1E00, 0xDEC1, 0xC901, 0x09C0, 0x0880, 0xC841, 0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40, 0x1E00, 0xDEC1,
@@ -170,8 +170,8 @@ uint16_t crc16(const uint8_t* data, uint64_t length, uint16_t seed, uint64_t fin
0x4C80, 0x8C41, 0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641, 0x8201, 0x42C0, 0x4380, 0x8341, 0x4C80, 0x8C41, 0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641, 0x8201, 0x42C0, 0x4380, 0x8341,
0x4100, 0x81C1, 0x8081, 0x4040}; 0x4100, 0x81C1, 0x8081, 0x4040};
int32_t pos = 0; atInt32 pos = 0;
uint16_t checksum = seed; atUint16 checksum = seed;
while (length--) while (length--)
checksum = (crc16Table[(checksum ^ data[pos++]) & 0xFF] ^ (checksum >> 8)); checksum = (crc16Table[(checksum ^ data[pos++]) & 0xFF] ^ (checksum >> 8));

View File

@@ -10,7 +10,8 @@
namespace athena::io::Compression { namespace athena::io::Compression {
void zlibInitZStrm(const uint8_t* src, uint32_t srcLen, uint8_t* dst, uint32_t dstLen, z_stream& strm) { atInt32 decompressZlib(const atUint8* src, atUint32 srcLen, atUint8* dst, atUint32 dstLen) {
z_stream strm = {};
strm.avail_in = srcLen; strm.avail_in = srcLen;
strm.avail_out = dstLen; strm.avail_out = dstLen;
strm.next_in = const_cast<Bytef*>(src); strm.next_in = const_cast<Bytef*>(src);
@@ -18,38 +19,22 @@ void zlibInitZStrm(const uint8_t* src, uint32_t srcLen, uint8_t* dst, uint32_t d
strm.zalloc = Z_NULL; strm.zalloc = Z_NULL;
strm.zfree = Z_NULL; strm.zfree = Z_NULL;
strm.opaque = Z_NULL; strm.opaque = Z_NULL;
}
int32_t zlibInflate(z_stream& strm, int32_t bits) { atInt32 ret;
int32_t ret = inflateInit2(&strm, bits); // 15 window bits, and the | 16 tells zlib to to detect if using gzip or zlib
ret = inflateInit2(&strm, MAX_WBITS | 16);
if (ret == Z_OK) { if (ret == Z_OK) {
ret = inflate(&strm, Z_FINISH); ret = inflate(&strm, Z_FINISH);
if (ret == Z_STREAM_END) { if (ret == Z_STREAM_END) {
ret = strm.total_out; ret = strm.total_out;
} }
} }
return ret;
}
int32_t decompressZlib(const uint8_t* src, uint32_t srcLen, uint8_t* dst, uint32_t dstLen) {
z_stream strm = {};
zlibInitZStrm(src, srcLen, dst, dstLen, strm);
// 15 window bits, and the | 16 tells zlib to to detect if using gzip or zlib
int32_t ret = zlibInflate(strm, MAX_WBITS | 16);
if (ret != Z_STREAM_END) {
// Try again without gzip
zlibInitZStrm(src, srcLen, dst, dstLen, strm);
ret = zlibInflate(strm, MAX_WBITS);
if (ret == Z_STREAM_END) {
ret = strm.total_out;
}
} else {
ret = strm.total_out;
}
inflateEnd(&strm); inflateEnd(&strm);
return ret; return ret;
} }
int32_t compressZlib(const uint8_t* src, uint32_t srcLen, uint8_t* dst, uint32_t dstLen) { atInt32 compressZlib(const atUint8* src, atUint32 srcLen, atUint8* dst, atUint32 dstLen) {
z_stream strm = {}; z_stream strm = {};
strm.total_in = strm.avail_in = srcLen; strm.total_in = strm.avail_in = srcLen;
strm.total_out = strm.avail_out = dstLen; strm.total_out = strm.avail_out = dstLen;
@@ -60,8 +45,8 @@ int32_t compressZlib(const uint8_t* src, uint32_t srcLen, uint8_t* dst, uint32_t
strm.zfree = Z_NULL; strm.zfree = Z_NULL;
strm.opaque = Z_NULL; strm.opaque = Z_NULL;
int32_t err = -1; atInt32 err = -1;
int32_t ret = -1; atInt32 ret = -1;
err = deflateInit(&strm, Z_BEST_COMPRESSION); err = deflateInit(&strm, Z_BEST_COMPRESSION);
@@ -97,11 +82,11 @@ atInt32 decompressLZO(const atUint8* source, const atInt32 sourceSize, atUint8*
// src points to the yaz0 source data (to the "real" source data, not at the header!) // src points to the yaz0 source data (to the "real" source data, not at the header!)
// dst points to a buffer uncompressedSize bytes large (you get uncompressedSize from // dst points to a buffer uncompressedSize bytes large (you get uncompressedSize from
// the second 4 bytes in the Yaz0 header). // the second 4 bytes in the Yaz0 header).
uint32_t yaz0Decode(const uint8_t* src, uint8_t* dst, uint32_t uncompressedSize) { atUint32 yaz0Decode(const atUint8* src, atUint8* dst, atUint32 uncompressedSize) {
uint32_t srcPlace = 0, dstPlace = 0; // current read/write positions atUint32 srcPlace = 0, dstPlace = 0; // current read/write positions
int32_t validBitCount = 0; // number of valid bits left in "code" byte atInt32 validBitCount = 0; // number of valid bits left in "code" byte
uint8_t currCodeByte; atUint8 currCodeByte;
while (dstPlace < uncompressedSize) { while (dstPlace < uncompressedSize) {
// read new "code" byte if the current one is used up // read new "code" byte if the current one is used up
@@ -118,14 +103,14 @@ uint32_t yaz0Decode(const uint8_t* src, uint8_t* dst, uint32_t uncompressedSize)
srcPlace++; srcPlace++;
} else { } else {
// RLE part // RLE part
uint8_t byte1 = src[srcPlace]; atUint8 byte1 = src[srcPlace];
uint8_t byte2 = src[srcPlace + 1]; atUint8 byte2 = src[srcPlace + 1];
srcPlace += 2; srcPlace += 2;
uint32_t dist = ((byte1 & 0xF) << 8) | byte2; atUint32 dist = ((byte1 & 0xF) << 8) | byte2;
uint32_t copySource = dstPlace - (dist + 1); atUint32 copySource = dstPlace - (dist + 1);
uint32_t numBytes = byte1 >> 4; atUint32 numBytes = byte1 >> 4;
if (numBytes == 0) { if (numBytes == 0) {
numBytes = src[srcPlace] + 0x12; numBytes = src[srcPlace] + 0x12;
@@ -134,7 +119,7 @@ uint32_t yaz0Decode(const uint8_t* src, uint8_t* dst, uint32_t uncompressedSize)
numBytes += 2; numBytes += 2;
// copy run // copy run
for (uint32_t i = 0; i < numBytes; ++i) { for (atUint32 i = 0; i < numBytes; ++i) {
dst[dstPlace] = dst[copySource]; dst[dstPlace] = dst[copySource];
copySource++; copySource++;
dstPlace++; dstPlace++;
@@ -151,25 +136,25 @@ uint32_t yaz0Decode(const uint8_t* src, uint8_t* dst, uint32_t uncompressedSize)
// Yaz0 encode // Yaz0 encode
typedef struct { typedef struct {
uint32_t srcPos, dstPos; atUint32 srcPos, dstPos;
} yaz0_Ret; } yaz0_Ret;
uint32_t simpleEnc(const uint8_t* src, int32_t size, int32_t pos, uint32_t* pMatchPos); atUint32 simpleEnc(const atUint8* src, atInt32 size, atInt32 pos, atUint32* pMatchPos);
uint32_t nintendoEnc(const uint8_t* src, int32_t size, int32_t pos, uint32_t* pMatchPos); atUint32 nintendoEnc(const atUint8* src, atInt32 size, atInt32 pos, atUint32* pMatchPos);
uint32_t yaz0Encode(const uint8_t* src, uint32_t srcSize, uint8_t* data) { atUint32 yaz0Encode(const atUint8* src, atUint32 srcSize, atUint8* data) {
yaz0_Ret r = {0, 0}; yaz0_Ret r = {0, 0};
int32_t pos = 0; atInt32 pos = 0;
uint8_t dst[24]; // 8 codes * 3 bytes maximum atUint8 dst[24]; // 8 codes * 3 bytes maximum
uint32_t dstSize = 0; atUint32 dstSize = 0;
uint32_t i; atUint32 i;
uint32_t validBitCount = 0; // number of valid bits left in "code" byte atUint32 validBitCount = 0; // number of valid bits left in "code" byte
uint8_t currCodeByte = 0; atUint8 currCodeByte = 0;
while (r.srcPos < srcSize) { while (r.srcPos < srcSize) {
uint32_t numBytes; atUint32 numBytes;
uint32_t matchPos; atUint32 matchPos;
numBytes = nintendoEnc(src, srcSize, r.srcPos, &matchPos); numBytes = nintendoEnc(src, srcSize, r.srcPos, &matchPos);
if (numBytes < 3) { if (numBytes < 3) {
@@ -181,8 +166,8 @@ uint32_t yaz0Encode(const uint8_t* src, uint32_t srcSize, uint8_t* data) {
currCodeByte |= (0x80 >> validBitCount); currCodeByte |= (0x80 >> validBitCount);
} else { } else {
// RLE part // RLE part
uint32_t dist = r.srcPos - matchPos - 1; atUint32 dist = r.srcPos - matchPos - 1;
uint8_t byte1, byte2, byte3; atUint8 byte1, byte2, byte3;
if (numBytes >= 0x12) // 3 byte encoding if (numBytes >= 0x12) // 3 byte encoding
{ {
@@ -244,11 +229,11 @@ uint32_t yaz0Encode(const uint8_t* src, uint32_t srcSize, uint8_t* data) {
} }
// a lookahead encoding scheme for ngc Yaz0 // a lookahead encoding scheme for ngc Yaz0
uint32_t nintendoEnc(const uint8_t* src, int32_t size, int32_t pos, uint32_t* pMatchPos) { atUint32 nintendoEnc(const atUint8* src, atInt32 size, atInt32 pos, atUint32* pMatchPos) {
uint32_t numBytes = 1; atUint32 numBytes = 1;
static uint32_t numBytes1; static atUint32 numBytes1;
static uint32_t matchPos; static atUint32 matchPos;
static int32_t prevFlag = 0; static atInt32 prevFlag = 0;
// if prevFlag is set, it means that the previous position was determined by look-ahead try. // if prevFlag is set, it means that the previous position was determined by look-ahead try.
// so just use it. this is not the best optimization, but nintendo's choice for speed. // so just use it. this is not the best optimization, but nintendo's choice for speed.
@@ -278,10 +263,10 @@ uint32_t nintendoEnc(const uint8_t* src, int32_t size, int32_t pos, uint32_t* pM
} }
// simple and straight encoding scheme for Yaz0 // simple and straight encoding scheme for Yaz0
uint32_t simpleEnc(const uint8_t* src, int32_t size, int32_t pos, uint32_t* pMatchPos) { atUint32 simpleEnc(const atUint8* src, atInt32 size, atInt32 pos, atUint32* pMatchPos) {
int startPos = pos - 0x1000, j, i; int startPos = pos - 0x1000, j, i;
uint32_t numBytes = 1; atUint32 numBytes = 1;
uint32_t matchPos = 0; atUint32 matchPos = 0;
if (startPos < 0) if (startPos < 0)
startPos = 0; startPos = 0;
@@ -292,7 +277,7 @@ uint32_t simpleEnc(const uint8_t* src, int32_t size, int32_t pos, uint32_t* pMat
break; break;
} }
if ((uint32_t)j > numBytes) { if ((atUint32)j > numBytes) {
numBytes = j; numBytes = j;
matchPos = i; matchPos = i;
} }
@@ -306,7 +291,7 @@ uint32_t simpleEnc(const uint8_t* src, int32_t size, int32_t pos, uint32_t* pMat
return numBytes; return numBytes;
} }
uint32_t decompressLZ77(const uint8_t* src, uint32_t srcLen, uint8_t** dst) { atUint32 decompressLZ77(const atUint8* src, atUint32 srcLen, atUint8** dst) {
if (*src == 0x11) { if (*src == 0x11) {
return LZType11().decompress(src, dst, srcLen); return LZType11().decompress(src, dst, srcLen);
} }
@@ -314,7 +299,7 @@ uint32_t decompressLZ77(const uint8_t* src, uint32_t srcLen, uint8_t** dst) {
return LZType10(2).decompress(src, dst, srcLen); return LZType10(2).decompress(src, dst, srcLen);
} }
uint32_t compressLZ77(const uint8_t* src, uint32_t srcLen, uint8_t** dst, bool extended) { atUint32 compressLZ77(const atUint8* src, atUint32 srcLen, atUint8** dst, bool extended) {
if (extended) if (extended)
return LZType11().compress(src, dst, srcLen); return LZType11().compress(src, dst, srcLen);

1105
src/athena/DNAYaml.cpp Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -50,8 +50,8 @@ bool Dir::rm(std::string_view path) { return !(remove((m_path + "/" + path.data(
bool Dir::touch() { bool Dir::touch() {
std::srand(std::time(nullptr)); std::srand(std::time(nullptr));
uint64_t tmp = utility::rand64(); atUint64 tmp = utility::rand64();
std::string tmpFile = std::format("{:016X}.tmp", tmp); std::string tmpFile = fmt::format(FMT_STRING("{:016X}.tmp"), tmp);
bool ret = FileInfo(m_path + "/" + tmpFile).touch(); bool ret = FileInfo(m_path + "/" + tmpFile).touch();
if (ret) if (ret)
return rm(tmpFile); return rm(tmpFile);

View File

@@ -9,7 +9,7 @@
#include "athena/FileWriter.hpp" #include "athena/FileWriter.hpp"
#include "athena/Utility.hpp" #include "athena/Utility.hpp"
#if !defined(_WIN32) || defined(__MINGW32__) #ifndef _WIN32
#include <sys/time.h> #include <sys/time.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <unistd.h> #include <unistd.h>
@@ -25,7 +25,7 @@
#include <cwchar> #include <cwchar>
#endif #endif
#if defined(_MSC_VER) || defined(__MINGW32__) #ifdef _MSC_VER
#include <functional> #include <functional>
#include <locale> #include <locale>
#define realpath(__name, __resolved) _fullpath((__resolved), (__name), 4096) #define realpath(__name, __resolved) _fullpath((__resolved), (__name), 4096)
@@ -69,7 +69,7 @@ std::string FileInfo::extension() const {
return m_path.substr(pos + 1); return m_path.substr(pos + 1);
} }
uint64_t FileInfo::size() const { return utility::fileSize(m_path); } atUint64 FileInfo::size() const { return utility::fileSize(m_path); }
bool FileInfo::exists() const { bool FileInfo::exists() const {
atStat64_t st; atStat64_t st;
@@ -78,24 +78,16 @@ bool FileInfo::exists() const {
if (e < 0) if (e < 0)
return false; return false;
return (S_ISREG(st.st_mode) return (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode));
#ifndef _WIN32
|| S_ISLNK(st.st_mode)
#endif
);
} }
bool FileInfo::isLink() const { bool FileInfo::isLink() const {
#ifndef _WIN32
atStat64_t st; atStat64_t st;
int e = atStat64(m_path.c_str(), &st); int e = atStat64(m_path.c_str(), &st);
if (e < 0) if (e < 0)
return false; return false;
return (S_ISLNK(st.st_mode)); return (S_ISLNK(st.st_mode));
#else
return false;
#endif
} }
bool FileInfo::isFile() const { bool FileInfo::isFile() const {
@@ -108,7 +100,7 @@ bool FileInfo::isFile() const {
} }
bool FileInfo::touch() const { bool FileInfo::touch() const {
#if defined(__GNUC__) && !(defined(HW_DOL) || defined(HW_RVL) || defined(GEKKO)) && !defined(__MINGW32__) #if defined(__GNUC__) && !(defined(HW_DOL) || defined(HW_RVL) || defined(GEKKO))
atStat64_t st; atStat64_t st;
if (atStat64(m_path.c_str(), &st) < 0) { if (atStat64(m_path.c_str(), &st) < 0) {
(void)athena::io::FileWriter(m_path); (void)athena::io::FileWriter(m_path);

View File

@@ -8,14 +8,14 @@
#endif #endif
namespace athena::io { namespace athena::io {
FileReader::FileReader(std::string_view filename, int32_t cacheSize, bool globalErr) FileReader::FileReader(std::string_view filename, atInt32 cacheSize, bool globalErr)
: m_fileHandle(nullptr), m_cacheData(nullptr), m_offset(0), m_globalErr(globalErr) { : m_fileHandle(nullptr), m_cacheData(nullptr), m_offset(0), m_globalErr(globalErr) {
m_filename = filename; m_filename = filename;
open(); open();
setCacheSize(cacheSize); setCacheSize(cacheSize);
} }
FileReader::FileReader(std::wstring_view filename, int32_t cacheSize, bool globalErr) FileReader::FileReader(std::wstring_view filename, atInt32 cacheSize, bool globalErr)
: m_fileHandle(nullptr), m_cacheData(nullptr), m_offset(0), m_globalErr(globalErr) { : m_fileHandle(nullptr), m_cacheData(nullptr), m_offset(0), m_globalErr(globalErr) {
m_filename = utility::wideToUtf8(filename); m_filename = utility::wideToUtf8(filename);
open(); open();
@@ -33,7 +33,7 @@ void FileReader::open() {
if (!m_fileHandle) { if (!m_fileHandle) {
std::string _filename = filename(); std::string _filename = filename();
if (m_globalErr) if (m_globalErr)
atError("File not found '{}'", _filename); atError(FMT_STRING("File not found '{}'"), _filename);
setError(); setError();
return; return;
} }
@@ -47,7 +47,7 @@ void FileReader::open() {
void FileReader::close() { void FileReader::close() {
if (!m_fileHandle) { if (!m_fileHandle) {
if (m_globalErr) if (m_globalErr)
atError("Cannot close an unopened stream"); atError(FMT_STRING("Cannot close an unopened stream"));
setError(); setError();
return; return;
} }
@@ -57,7 +57,7 @@ void FileReader::close() {
return; return;
} }
void FileReader::seek(int64_t pos, SeekOrigin origin) { void FileReader::seek(atInt64 pos, SeekOrigin origin) {
if (!isOpen()) if (!isOpen())
return; return;
@@ -76,51 +76,51 @@ void FileReader::seek(int64_t pos, SeekOrigin origin) {
} }
if (m_offset > length()) { if (m_offset > length()) {
if (m_globalErr) if (m_globalErr)
atError("Unable to seek in file"); atError(FMT_STRING("Unable to seek in file"));
setError(); setError();
return; return;
} }
size_t block = m_offset / m_blockSize; size_t block = m_offset / m_blockSize;
if (int32_t(block) != m_curBlock) { if (atInt32(block) != m_curBlock) {
fseeko64(m_fileHandle, block * m_blockSize, SEEK_SET); fseeko64(m_fileHandle, block * m_blockSize, SEEK_SET);
fread(m_cacheData.get(), 1, m_blockSize, m_fileHandle); fread(m_cacheData.get(), 1, m_blockSize, m_fileHandle);
m_curBlock = int32_t(block); m_curBlock = atInt32(block);
} }
} else if (fseeko64(m_fileHandle, pos, int(origin)) != 0) { } else if (fseeko64(m_fileHandle, pos, int(origin)) != 0) {
if (m_globalErr) if (m_globalErr)
atError("Unable to seek in file"); atError(FMT_STRING("Unable to seek in file"));
setError(); setError();
} }
} }
uint64_t FileReader::position() const { atUint64 FileReader::position() const {
if (!isOpen()) { if (!isOpen()) {
if (m_globalErr) if (m_globalErr)
atError("File not open"); atError(FMT_STRING("File not open"));
return 0; return 0;
} }
if (m_blockSize > 0) if (m_blockSize > 0)
return m_offset; return m_offset;
else else
return uint64_t(ftello64(m_fileHandle)); return atUint64(ftello64(m_fileHandle));
} }
uint64_t FileReader::length() const { atUint64 FileReader::length() const {
if (!isOpen()) { if (!isOpen()) {
if (m_globalErr) if (m_globalErr)
atError("File not open"); atError(FMT_STRING("File not open"));
return 0; return 0;
} }
return m_fileSize; return m_fileSize;
} }
uint64_t FileReader::readUBytesToBuf(void* buf, uint64_t len) { atUint64 FileReader::readUBytesToBuf(void* buf, atUint64 len) {
if (!isOpen()) { if (!isOpen()) {
if (m_globalErr) if (m_globalErr)
atError("File not open for reading"); atError(FMT_STRING("File not open for reading"));
setError(); setError();
return 0; return 0;
} }
@@ -134,20 +134,20 @@ uint64_t FileReader::readUBytesToBuf(void* buf, uint64_t len) {
len = m_fileSize - m_offset; len = m_fileSize - m_offset;
size_t block = m_offset / m_blockSize; size_t block = m_offset / m_blockSize;
uint64_t cacheOffset = m_offset % m_blockSize; atUint64 cacheOffset = m_offset % m_blockSize;
uint64_t cacheSize; atUint64 cacheSize;
uint64_t rem = len; atUint64 rem = len;
uint8_t* dst = (uint8_t*)buf; atUint8* dst = (atUint8*)buf;
while (rem) { while (rem) {
if (int32_t(block) != m_curBlock) { if (atInt32(block) != m_curBlock) {
fseeko64(m_fileHandle, block * m_blockSize, SEEK_SET); fseeko64(m_fileHandle, block * m_blockSize, SEEK_SET);
fread(m_cacheData.get(), 1, m_blockSize, m_fileHandle); fread(m_cacheData.get(), 1, m_blockSize, m_fileHandle);
m_curBlock = int32_t(block); m_curBlock = atInt32(block);
} }
cacheSize = rem; cacheSize = rem;
if (int32_t(cacheSize + cacheOffset) > m_blockSize) if (atInt32(cacheSize + cacheOffset) > m_blockSize)
cacheSize = m_blockSize - cacheOffset; cacheSize = m_blockSize - cacheOffset;
memmove(dst, m_cacheData.get() + cacheOffset, cacheSize); memmove(dst, m_cacheData.get() + cacheOffset, cacheSize);
@@ -157,20 +157,20 @@ uint64_t FileReader::readUBytesToBuf(void* buf, uint64_t len) {
++block; ++block;
} }
m_offset += len; m_offset += len;
return uint64_t(dst - reinterpret_cast<uint8_t*>(buf)); return atUint64(dst - reinterpret_cast<atUint8*>(buf));
} }
} }
void FileReader::setCacheSize(const int32_t blockSize) { void FileReader::setCacheSize(const atInt32 blockSize) {
m_blockSize = blockSize; m_blockSize = blockSize;
int32_t len = int32_t(length()); atInt32 len = atInt32(length());
if (m_blockSize > len) if (m_blockSize > len)
m_blockSize = len; m_blockSize = len;
m_curBlock = -1; m_curBlock = -1;
if (m_blockSize > 0) if (m_blockSize > 0)
m_cacheData.reset(new uint8_t[m_blockSize]); m_cacheData.reset(new atUint8[m_blockSize]);
} }
} // namespace athena::io } // namespace athena::io

View File

@@ -8,14 +8,14 @@
#include "win32_largefilewrapper.h" #include "win32_largefilewrapper.h"
namespace athena::io { namespace athena::io {
FileReader::FileReader(std::string_view filename, int32_t cacheSize, bool globalErr) FileReader::FileReader(std::string_view filename, atInt32 cacheSize, bool globalErr)
: m_fileHandle(nullptr), m_cacheData(nullptr), m_offset(0), m_globalErr(globalErr) { : m_fileHandle(nullptr), m_cacheData(nullptr), m_offset(0), m_globalErr(globalErr) {
m_filename = utility::utf8ToWide(filename); m_filename = utility::utf8ToWide(filename);
open(); open();
setCacheSize(cacheSize); setCacheSize(cacheSize);
} }
FileReader::FileReader(std::wstring_view filename, int32_t cacheSize, bool globalErr) FileReader::FileReader(std::wstring_view filename, atInt32 cacheSize, bool globalErr)
: m_fileHandle(nullptr), m_cacheData(nullptr), m_offset(0), m_globalErr(globalErr) { : m_fileHandle(nullptr), m_cacheData(nullptr), m_offset(0), m_globalErr(globalErr) {
m_filename = filename; m_filename = filename;
open(); open();
@@ -42,7 +42,7 @@ void FileReader::open() {
m_fileHandle = 0; m_fileHandle = 0;
std::string _filename = filename(); std::string _filename = filename();
if (m_globalErr) if (m_globalErr)
atError("File not found '{}'", _filename); atError(FMT_STRING("File not found '{}'"), _filename);
setError(); setError();
return; return;
} }
@@ -54,7 +54,7 @@ void FileReader::open() {
void FileReader::close() { void FileReader::close() {
if (!m_fileHandle) { if (!m_fileHandle) {
if (m_globalErr) if (m_globalErr)
atError("Cannot close an unopened stream"); atError(FMT_STRING("Cannot close an unopened stream"));
setError(); setError();
return; return;
} }
@@ -64,13 +64,13 @@ void FileReader::close() {
return; return;
} }
void FileReader::seek(int64_t pos, SeekOrigin origin) { void FileReader::seek(atInt64 pos, SeekOrigin origin) {
if (!isOpen()) if (!isOpen())
return; return;
// check block position // check block position
if (m_blockSize > 0) { if (m_blockSize > 0) {
uint64_t oldOff = m_offset; atUint64 oldOff = m_offset;
switch (origin) { switch (origin) {
case SeekOrigin::Begin: case SeekOrigin::Begin:
m_offset = pos; m_offset = pos;
@@ -85,7 +85,7 @@ void FileReader::seek(int64_t pos, SeekOrigin origin) {
if (m_offset > length()) { if (m_offset > length()) {
oldOff = m_offset; oldOff = m_offset;
if (m_globalErr) if (m_globalErr)
atError("Unable to seek in file"); atError(FMT_STRING("Unable to seek in file"));
setError(); setError();
return; return;
} }
@@ -97,23 +97,23 @@ void FileReader::seek(int64_t pos, SeekOrigin origin) {
SetFilePointerEx(m_fileHandle, li, nullptr, FILE_BEGIN); SetFilePointerEx(m_fileHandle, li, nullptr, FILE_BEGIN);
DWORD readSz; DWORD readSz;
ReadFile(m_fileHandle, m_cacheData.get(), m_blockSize, &readSz, nullptr); ReadFile(m_fileHandle, m_cacheData.get(), m_blockSize, &readSz, nullptr);
m_curBlock = (int32_t)block; m_curBlock = (atInt32)block;
} }
} else { } else {
LARGE_INTEGER li; LARGE_INTEGER li;
li.QuadPart = pos; li.QuadPart = pos;
if (!SetFilePointerEx(m_fileHandle, li, nullptr, DWORD(origin))) { if (!SetFilePointerEx(m_fileHandle, li, nullptr, DWORD(origin))) {
if (m_globalErr) if (m_globalErr)
atError("Unable to seek in file"); atError(FMT_STRING("Unable to seek in file"));
setError(); setError();
} }
} }
} }
uint64_t FileReader::position() const { atUint64 FileReader::position() const {
if (!isOpen()) { if (!isOpen()) {
if (m_globalErr) if (m_globalErr)
atError("File not open"); atError(FMT_STRING("File not open"));
return 0; return 0;
} }
@@ -127,10 +127,10 @@ uint64_t FileReader::position() const {
} }
} }
uint64_t FileReader::length() const { atUint64 FileReader::length() const {
if (!isOpen()) { if (!isOpen()) {
if (m_globalErr) if (m_globalErr)
atError("File not open"); atError(FMT_STRING("File not open"));
return 0; return 0;
} }
@@ -139,10 +139,10 @@ uint64_t FileReader::length() const {
return res.QuadPart; return res.QuadPart;
} }
uint64_t FileReader::readUBytesToBuf(void* buf, uint64_t len) { atUint64 FileReader::readUBytesToBuf(void* buf, atUint64 len) {
if (!isOpen()) { if (!isOpen()) {
if (m_globalErr) if (m_globalErr)
atError("File not open for reading"); atError(FMT_STRING("File not open for reading"));
setError(); setError();
return 0; return 0;
} }
@@ -154,16 +154,16 @@ uint64_t FileReader::readUBytesToBuf(void* buf, uint64_t len) {
} else { } else {
LARGE_INTEGER fs; LARGE_INTEGER fs;
GetFileSizeEx(m_fileHandle, &fs); GetFileSizeEx(m_fileHandle, &fs);
if (m_offset >= uint64_t(fs.QuadPart)) if (m_offset >= atUint64(fs.QuadPart))
return 0; return 0;
if (m_offset + len >= uint64_t(fs.QuadPart)) if (m_offset + len >= atUint64(fs.QuadPart))
len = fs.QuadPart - m_offset; len = fs.QuadPart - m_offset;
size_t block = m_offset / m_blockSize; size_t block = m_offset / m_blockSize;
uint64_t cacheOffset = m_offset % m_blockSize; atUint64 cacheOffset = m_offset % m_blockSize;
uint64_t cacheSize; atUint64 cacheSize;
uint64_t rem = len; atUint64 rem = len;
uint8_t* dst = (uint8_t*)buf; atUint8* dst = (atUint8*)buf;
while (rem) { while (rem) {
if (block != m_curBlock) { if (block != m_curBlock) {
@@ -172,7 +172,7 @@ uint64_t FileReader::readUBytesToBuf(void* buf, uint64_t len) {
SetFilePointerEx(m_fileHandle, li, nullptr, FILE_BEGIN); SetFilePointerEx(m_fileHandle, li, nullptr, FILE_BEGIN);
DWORD readSz; DWORD readSz;
ReadFile(m_fileHandle, m_cacheData.get(), m_blockSize, &readSz, nullptr); ReadFile(m_fileHandle, m_cacheData.get(), m_blockSize, &readSz, nullptr);
m_curBlock = (int32_t)block; m_curBlock = (atInt32)block;
} }
cacheSize = rem; cacheSize = rem;
@@ -186,19 +186,19 @@ uint64_t FileReader::readUBytesToBuf(void* buf, uint64_t len) {
++block; ++block;
} }
m_offset += len; m_offset += len;
return dst - (uint8_t*)buf; return dst - (atUint8*)buf;
} }
} }
void FileReader::setCacheSize(const int32_t blockSize) { void FileReader::setCacheSize(const atInt32 blockSize) {
m_blockSize = blockSize; m_blockSize = blockSize;
if (m_blockSize > length()) if (m_blockSize > length())
m_blockSize = (int32_t)length(); m_blockSize = (atInt32)length();
m_curBlock = -1; m_curBlock = -1;
if (m_blockSize > 0) if (m_blockSize > 0)
m_cacheData.reset(new uint8_t[m_blockSize]); m_cacheData.reset(new atUint8[m_blockSize]);
} }
} // namespace athena::io } // namespace athena::io

View File

@@ -3,7 +3,7 @@
#include <cstring> #include <cstring>
namespace athena::io { namespace athena::io {
void TransactionalFileWriter::seek(int64_t pos, SeekOrigin origin) { void TransactionalFileWriter::seek(atInt64 pos, SeekOrigin origin) {
switch (origin) { switch (origin) {
case SeekOrigin::Begin: case SeekOrigin::Begin:
m_position = pos; m_position = pos;
@@ -16,8 +16,8 @@ void TransactionalFileWriter::seek(int64_t pos, SeekOrigin origin) {
} }
} }
void TransactionalFileWriter::writeUBytes(const uint8_t* data, uint64_t len) { void TransactionalFileWriter::writeUBytes(const atUint8* data, atUint64 len) {
uint64_t neededSz = m_position + len; atUint64 neededSz = m_position + len;
if (neededSz > m_deferredBuffer.size()) { if (neededSz > m_deferredBuffer.size()) {
m_deferredBuffer.reserve(neededSz * 2); m_deferredBuffer.reserve(neededSz * 2);
m_deferredBuffer.resize(neededSz); m_deferredBuffer.resize(neededSz);

View File

@@ -48,9 +48,8 @@ void FileWriter::open(bool overwrite) {
} }
if (!m_fileHandle) { if (!m_fileHandle) {
if (m_globalErr) { if (m_globalErr)
atError("Unable to open file '{}'", m_filename); atError(FMT_STRING("Unable to open file '%s'"), filename().c_str());
}
setError(); setError();
return; return;
} }
@@ -62,7 +61,7 @@ void FileWriter::open(bool overwrite) {
void FileWriter::close() { void FileWriter::close() {
if (!m_fileHandle) { if (!m_fileHandle) {
if (m_globalErr) if (m_globalErr)
atError("Cannot close an unopened stream"); atError(FMT_STRING("Cannot close an unopened stream"));
setError(); setError();
return; return;
} }
@@ -79,36 +78,36 @@ void FileWriter::close() {
rename(tmpFilename.c_str(), m_filename.c_str()); rename(tmpFilename.c_str(), m_filename.c_str());
} }
void FileWriter::seek(int64_t pos, SeekOrigin origin) { void FileWriter::seek(atInt64 pos, SeekOrigin origin) {
if (!isOpen()) { if (!isOpen()) {
if (m_globalErr) if (m_globalErr)
atError("Unable to seek in file, not open"); atError(FMT_STRING("Unable to seek in file, not open"));
setError(); setError();
return; return;
} }
if (fseeko64(m_fileHandle, pos, int(origin)) != 0) { if (fseeko64(m_fileHandle, pos, int(origin)) != 0) {
if (m_globalErr) if (m_globalErr)
atError("Unable to seek in file"); atError(FMT_STRING("Unable to seek in file"));
setError(); setError();
} }
} }
uint64_t FileWriter::position() const { return uint64_t(ftello64(m_fileHandle)); } atUint64 FileWriter::position() const { return atUint64(ftello64(m_fileHandle)); }
uint64_t FileWriter::length() const { return utility::fileSize(m_filename); } atUint64 FileWriter::length() const { return utility::fileSize(m_filename); }
void FileWriter::writeUBytes(const uint8_t* data, uint64_t len) { void FileWriter::writeUBytes(const atUint8* data, atUint64 len) {
if (!isOpen()) { if (!isOpen()) {
if (m_globalErr) if (m_globalErr)
atError("File not open for writing"); atError(FMT_STRING("File not open for writing"));
setError(); setError();
return; return;
} }
if (fwrite(data, 1, len, m_fileHandle) != len) { if (fwrite(data, 1, len, m_fileHandle) != len) {
if (m_globalErr) if (m_globalErr)
atError("Unable to write to stream"); atError(FMT_STRING("Unable to write to stream"));
setError(); setError();
} }
} }

View File

@@ -48,10 +48,8 @@ void FileWriter::open(bool overwrite) {
if (m_fileHandle == INVALID_HANDLE_VALUE) { if (m_fileHandle == INVALID_HANDLE_VALUE) {
m_fileHandle = 0; m_fileHandle = 0;
if (m_globalErr) { if (m_globalErr)
auto _filename = filename(); atError(FMT_STRING("Unable to open file '{}'"), filename());
atError("Unable to open file '{}'", _filename);
}
setError(); setError();
return; return;
} }
@@ -63,7 +61,7 @@ void FileWriter::open(bool overwrite) {
void FileWriter::close() { void FileWriter::close() {
if (!m_fileHandle) { if (!m_fileHandle) {
if (m_globalErr) if (m_globalErr)
atError("Cannot close an unopened stream"); atError(FMT_STRING("Cannot close an unopened stream"));
setError(); setError();
return; return;
} }
@@ -76,10 +74,10 @@ void FileWriter::close() {
MoveFileExW(tmpFilename.c_str(), m_filename.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH); MoveFileExW(tmpFilename.c_str(), m_filename.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH);
} }
void FileWriter::seek(int64_t pos, SeekOrigin origin) { void FileWriter::seek(atInt64 pos, SeekOrigin origin) {
if (!isOpen()) { if (!isOpen()) {
if (m_globalErr) if (m_globalErr)
atError("Unable to seek in file, not open"); atError(FMT_STRING("Unable to seek in file, not open"));
setError(); setError();
return; return;
} }
@@ -88,37 +86,37 @@ void FileWriter::seek(int64_t pos, SeekOrigin origin) {
li.QuadPart = pos; li.QuadPart = pos;
if (!SetFilePointerEx(m_fileHandle, li, nullptr, DWORD(origin))) { if (!SetFilePointerEx(m_fileHandle, li, nullptr, DWORD(origin))) {
if (m_globalErr) if (m_globalErr)
atError("Unable to seek in file"); atError(FMT_STRING("Unable to seek in file"));
setError(); setError();
} }
} }
uint64_t FileWriter::position() const { atUint64 FileWriter::position() const {
LARGE_INTEGER li = {}; LARGE_INTEGER li = {};
LARGE_INTEGER res; LARGE_INTEGER res;
SetFilePointerEx(m_fileHandle, li, &res, FILE_CURRENT); SetFilePointerEx(m_fileHandle, li, &res, FILE_CURRENT);
return static_cast<uint64_t>(res.QuadPart); return static_cast<atUint64>(res.QuadPart);
} }
uint64_t FileWriter::length() const { return utility::fileSize(m_filename); } atUint64 FileWriter::length() const { return utility::fileSize(m_filename); }
void FileWriter::writeUBytes(const uint8_t* data, uint64_t len) { void FileWriter::writeUBytes(const atUint8* data, atUint64 len) {
if (!isOpen()) { if (!isOpen()) {
if (m_globalErr) { if (m_globalErr) {
atError("File not open for writing"); atError(FMT_STRING("File not open for writing"));
} }
setError(); setError();
return; return;
} }
uint64_t remaining = len; atUint64 remaining = len;
do { do {
const auto toWrite = static_cast<DWORD>(std::min(remaining, uint64_t{std::numeric_limits<DWORD>::max()})); const auto toWrite = static_cast<DWORD>(std::min(remaining, atUint64{std::numeric_limits<DWORD>::max()}));
DWORD written = 0; DWORD written = 0;
if (WriteFile(m_fileHandle, data, toWrite, &written, nullptr) == FALSE) { if (WriteFile(m_fileHandle, data, toWrite, &written, nullptr) == FALSE) {
if (m_globalErr) { if (m_globalErr) {
atError("Unable to write to file"); atError(FMT_STRING("Unable to write to file"));
} }
setError(); setError();
return; return;

View File

@@ -35,7 +35,7 @@ std::ostream& operator<<(std::ostream& os, const athena::Endian& endian) {
} }
static void __defaultExceptionHandler(athena::error::Level level, const char* file, const char* function, int line, static void __defaultExceptionHandler(athena::error::Level level, const char* file, const char* function, int line,
std::string_view fmt, std::format_args args) { fmt::string_view fmt, fmt::format_args args) {
std::string levelStr; std::string levelStr;
switch (level) { switch (level) {
case athena::error::Level::Warning: case athena::error::Level::Warning:
@@ -51,7 +51,7 @@ static void __defaultExceptionHandler(athena::error::Level level, const char* fi
break; break;
} }
std::string msg = std::vformat(fmt, args); std::string msg = fmt::vformat(fmt, args);
std::cerr << levelStr << " " << file << " " << function << "(" << line << "): " << msg << std::endl; std::cerr << levelStr << " " << file << " " << function << "(" << line << "): " << msg << std::endl;
} }

View File

@@ -7,9 +7,9 @@ const char MCFile::VERSION_US[33] = "AGBZELDA:THE MINISH CAP:ZELDA 5\0";
MCFile::MCFile() {} MCFile::MCFile() {}
// TODO: Rewrite this to be more optimized, the current solution takes quite a few cycles // TODO: Rewrite this to be more optimized, the current solution takes quite a few cycles
uint8_t* reverse(uint8_t* data, uint32_t length) { atUint8* reverse(atUint8* data, atUint32 length) {
uint32_t a = 0; atUint32 a = 0;
uint32_t swap; atUint32 swap;
for (; a < --length; a++) { for (; a < --length; a++) {
swap = data[a]; swap = data[a];
@@ -20,15 +20,15 @@ uint8_t* reverse(uint8_t* data, uint32_t length) {
return data; return data;
} }
uint8_t* MCFile::unscramble(uint8_t* data, uint64_t length) { atUint8* MCFile::unscramble(atUint8* data, atUint64 length) {
if (!data) if (!data)
return nullptr; return nullptr;
for (uint32_t i = 0; i < length; i += 8) { for (atUint32 i = 0; i < length; i += 8) {
uint32_t block1 = *(uint32_t*)reverse((data + i), 4); atUint32 block1 = *(atUint32*)reverse((data + i), 4);
uint32_t block2 = *(uint32_t*)reverse((data + i + 4), 4); atUint32 block2 = *(atUint32*)reverse((data + i + 4), 4);
*(uint32_t*)(data + i) = block2; *(atUint32*)(data + i) = block2;
*(uint32_t*)(data + i + 4) = block1; *(atUint32*)(data + i + 4) = block1;
} }
return data; return data;

View File

@@ -4,8 +4,8 @@ namespace athena {
namespace io { namespace io {
static const uint32_t SCRAMBLE_VALUE = 0x5A424741; static const atUint32 SCRAMBLE_VALUE = 0x5A424741;
MCFileReader::MCFileReader(uint8_t* data, uint64_t length) : MemoryCopyReader(data, length) {} MCFileReader::MCFileReader(atUint8* data, atUint64 length) : MemoryCopyReader(data, length) {}
MCFileReader::MCFileReader(const std::string& filename) : MemoryCopyReader(filename) {} MCFileReader::MCFileReader(const std::string& filename) : MemoryCopyReader(filename) {}

View File

@@ -2,19 +2,19 @@
namespace athena::io { namespace athena::io {
MCFileWriter::MCFileWriter(uint8_t* data, uint64_t length) : MemoryCopyWriter(data, length) {} MCFileWriter::MCFileWriter(atUint8* data, atUint64 length) : MemoryCopyWriter(data, length) {}
MCFileWriter::MCFileWriter(const std::string& filename) : MemoryCopyWriter(filename) {} MCFileWriter::MCFileWriter(const std::string& filename) : MemoryCopyWriter(filename) {}
// TODO: Check the implementation, it seems to work fine, however it's not exactly correct, // TODO: Check the implementation, it seems to work fine, however it's not exactly correct,
// looking at the disassembly, MC seems to do some weird checking that isn't being done with this solution // looking at the disassembly, MC seems to do some weird checking that isn't being done with this solution
// need to figure out what it's doing and whether it's relevant to the checksum. // need to figure out what it's doing and whether it's relevant to the checksum.
uint16_t MCFileWriter::calculateSlotChecksum(uint32_t game) { atUint16 MCFileWriter::calculateSlotChecksum(atUint32 game) {
uint16_t first = calculateChecksum((m_data + 0x34 + (0x10 * game)), 4); atUint16 first = calculateChecksum((m_data + 0x34 + (0x10 * game)), 4);
uint16_t second = calculateChecksum((m_data + 0x80 + (0x500 * game)), 0x500); atUint16 second = calculateChecksum((m_data + 0x80 + (0x500 * game)), 0x500);
first = (first + second) & 0xFFFF; first = (first + second) & 0xFFFF;
uint16_t result = first << 16; atUint16 result = first << 16;
second = ~first & 0xFFFF; second = ~first & 0xFFFF;
second += 1; second += 1;
result += second; result += second;
@@ -22,12 +22,12 @@ uint16_t MCFileWriter::calculateSlotChecksum(uint32_t game) {
return result; return result;
} }
uint16_t MCFileWriter::calculateChecksum(uint8_t* data, uint32_t length) { atUint16 MCFileWriter::calculateChecksum(atUint8* data, atUint32 length) {
uint16_t sum = 0; atUint16 sum = 0;
int i = length; int i = length;
for (uint32_t j = 0; j < length; j += 2) { for (atUint32 j = 0; j < length; j += 2) {
sum += *(uint16_t*)(data + j) ^ i; sum += *(atUint16*)(data + j) ^ i;
i -= 2; i -= 2;
} }

View File

@@ -2,7 +2,7 @@
namespace athena { namespace athena {
MCSlot::MCSlot(std::unique_ptr<uint8_t[]>&& data, uint32_t length) MCSlot::MCSlot(std::unique_ptr<atUint8[]>&& data, atUint32 length)
: ZQuestFile(ZQuestFile::MC, Endian::Little, std::move(data), length) {} : ZQuestFile(ZQuestFile::MC, Endian::Little, std::move(data), length) {}
} // namespace athena } // namespace athena

View File

@@ -9,11 +9,11 @@
#endif // HW_RVL #endif // HW_RVL
namespace athena::io { namespace athena::io {
MemoryReader::MemoryReader(const void* data, uint64_t length, bool takeOwnership, bool globalErr) MemoryReader::MemoryReader(const void* data, atUint64 length, bool takeOwnership, bool globalErr)
: m_data(data), m_length(length), m_position(0), m_owns(takeOwnership), m_globalErr(globalErr) { : m_data(data), m_length(length), m_position(0), m_owns(takeOwnership), m_globalErr(globalErr) {
if (!data) { if (!data) {
if (m_globalErr) if (m_globalErr)
atError("data cannot be NULL"); atError(FMT_STRING("data cannot be NULL"));
setError(); setError();
return; return;
} }
@@ -21,40 +21,40 @@ MemoryReader::MemoryReader(const void* data, uint64_t length, bool takeOwnership
MemoryReader::~MemoryReader() { MemoryReader::~MemoryReader() {
if (m_owns) if (m_owns)
delete[] static_cast<const uint8_t*>(m_data); delete[] static_cast<const atUint8*>(m_data);
} }
MemoryCopyReader::MemoryCopyReader(const void* data, uint64_t length) : MemoryReader(data, length, false) { MemoryCopyReader::MemoryCopyReader(const void* data, atUint64 length) : MemoryReader(data, length, false) {
if (!data) { if (!data) {
if (m_globalErr) if (m_globalErr)
atError("data cannot be NULL"); atError(FMT_STRING("data cannot be NULL"));
setError(); setError();
return; return;
} }
m_dataCopy.reset(new uint8_t[m_length]); m_dataCopy.reset(new atUint8[m_length]);
m_data = m_dataCopy.get(); m_data = m_dataCopy.get();
memmove(m_dataCopy.get(), data, m_length); memmove(m_dataCopy.get(), data, m_length);
} }
void MemoryReader::seek(int64_t position, SeekOrigin origin) { void MemoryReader::seek(atInt64 position, SeekOrigin origin) {
switch (origin) { switch (origin) {
case SeekOrigin::Begin: case SeekOrigin::Begin:
if ((position < 0 || int64_t(position) > int64_t(m_length))) { if ((position < 0 || atInt64(position) > atInt64(m_length))) {
if (m_globalErr) if (m_globalErr)
atFatal("Position {:08X} outside stream bounds ", position); atFatal(FMT_STRING("Position {:08X} outside stream bounds "), position);
m_position = m_length; m_position = m_length;
setError(); setError();
return; return;
} }
m_position = uint64_t(position); m_position = atUint64(position);
break; break;
case SeekOrigin::Current: case SeekOrigin::Current:
if (((int64_t(m_position) + position) < 0 || (m_position + uint64_t(position)) > m_length)) { if (((atInt64(m_position) + position) < 0 || (m_position + atUint64(position)) > m_length)) {
if (m_globalErr) if (m_globalErr)
atFatal("Position {:08X} outside stream bounds ", position); atFatal(FMT_STRING("Position {:08X} outside stream bounds "), position);
m_position = (position < 0 ? 0 : m_length); m_position = (position < 0 ? 0 : m_length);
setError(); setError();
return; return;
@@ -64,9 +64,9 @@ void MemoryReader::seek(int64_t position, SeekOrigin origin) {
break; break;
case SeekOrigin::End: case SeekOrigin::End:
if ((((int64_t)m_length - position < 0) || (m_length - position) > m_length)) { if ((((atInt64)m_length - position < 0) || (m_length - position) > m_length)) {
if (m_globalErr) if (m_globalErr)
atFatal("Position {:08X} outside stream bounds ", position); atFatal(FMT_STRING("Position {:08X} outside stream bounds "), position);
m_position = m_length; m_position = m_length;
setError(); setError();
return; return;
@@ -77,53 +77,53 @@ void MemoryReader::seek(int64_t position, SeekOrigin origin) {
} }
} }
void MemoryReader::setData(const uint8_t* data, uint64_t length, bool takeOwnership) { void MemoryReader::setData(const atUint8* data, atUint64 length, bool takeOwnership) {
if (m_owns) if (m_owns)
delete[] static_cast<const uint8_t*>(m_data); delete[] static_cast<const atUint8*>(m_data);
m_data = (uint8_t*)data; m_data = (atUint8*)data;
m_length = length; m_length = length;
m_position = 0; m_position = 0;
m_owns = takeOwnership; m_owns = takeOwnership;
} }
void MemoryCopyReader::setData(const uint8_t* data, uint64_t length) { void MemoryCopyReader::setData(const atUint8* data, atUint64 length) {
m_dataCopy.reset(new uint8_t[length]); m_dataCopy.reset(new atUint8[length]);
m_data = m_dataCopy.get(); m_data = m_dataCopy.get();
memmove(m_dataCopy.get(), data, length); memmove(m_dataCopy.get(), data, length);
m_length = length; m_length = length;
m_position = 0; m_position = 0;
} }
uint8_t* MemoryReader::data() const { atUint8* MemoryReader::data() const {
uint8_t* ret = new uint8_t[m_length]; atUint8* ret = new atUint8[m_length];
memset(ret, 0, m_length); memset(ret, 0, m_length);
memmove(ret, m_data, m_length); memmove(ret, m_data, m_length);
return ret; return ret;
} }
uint64_t MemoryReader::readUBytesToBuf(void* buf, uint64_t length) { atUint64 MemoryReader::readUBytesToBuf(void* buf, atUint64 length) {
if (m_position >= m_length) { if (m_position >= m_length) {
if (m_globalErr) if (m_globalErr)
atError("Position {:08X} outside stream bounds ", m_position); atError(FMT_STRING("Position {:08X} outside stream bounds "), m_position);
m_position = m_length; m_position = m_length;
setError(); setError();
return 0; return 0;
} }
length = std::min(length, m_length - m_position); length = std::min(length, m_length - m_position);
memmove(buf, static_cast<const uint8_t*>(m_data) + m_position, length); memmove(buf, static_cast<const atUint8*>(m_data) + m_position, length);
m_position += length; m_position += length;
return length; return length;
} }
void MemoryCopyReader::loadData() { void MemoryCopyReader::loadData() {
FILE* in; FILE* in;
uint64_t length; atUint64 length;
in = fopen(m_filepath.c_str(), "rb"); in = fopen(m_filepath.c_str(), "rb");
if (!in) { if (!in) {
if (m_globalErr) if (m_globalErr)
atError("Unable to open file '%s'", m_filepath); atError(FMT_STRING("Unable to open file '%s'"), m_filepath);
setError(); setError();
return; return;
} }
@@ -131,21 +131,21 @@ void MemoryCopyReader::loadData() {
rewind(in); rewind(in);
length = utility::fileSize(m_filepath); length = utility::fileSize(m_filepath);
m_dataCopy.reset(new uint8_t[length]); m_dataCopy.reset(new atUint8[length]);
m_data = m_dataCopy.get(); m_data = m_dataCopy.get();
uint64_t done = 0; atUint64 done = 0;
uint64_t blocksize = BLOCKSZ; atUint64 blocksize = BLOCKSZ;
do { do {
if (blocksize > length - done) if (blocksize > length - done)
blocksize = length - done; blocksize = length - done;
int64_t ret = fread(m_dataCopy.get() + done, 1, blocksize, in); atInt64 ret = fread(m_dataCopy.get() + done, 1, blocksize, in);
if (ret < 0) { if (ret < 0) {
if (m_globalErr) if (m_globalErr)
atError("Error reading data from disk"); atError(FMT_STRING("Error reading data from disk"));
setError(); setError();
return; return;
} else if (ret == 0) } else if (ret == 0)

View File

@@ -9,10 +9,10 @@
namespace athena::io { namespace athena::io {
MemoryWriter::MemoryWriter(uint8_t* data, uint64_t length, bool takeOwnership) MemoryWriter::MemoryWriter(atUint8* data, atUint64 length, bool takeOwnership)
: m_data(data), m_length(length), m_bufferOwned(takeOwnership) { : m_data(data), m_length(length), m_bufferOwned(takeOwnership) {
if (!data) { if (!data) {
atError("data cannot be NULL"); atError(FMT_STRING("data cannot be NULL"));
setError(); setError();
return; return;
} }
@@ -25,18 +25,18 @@ MemoryWriter::~MemoryWriter() {
m_length = 0; m_length = 0;
} }
MemoryCopyWriter::MemoryCopyWriter(uint8_t* data, uint64_t length) { MemoryCopyWriter::MemoryCopyWriter(atUint8* data, atUint64 length) {
m_data = data; m_data = data;
m_length = length; m_length = length;
m_position = 0; m_position = 0;
m_bufferOwned = false; m_bufferOwned = false;
if (length == 0) { if (length == 0) {
atError("length cannot be 0"); atError(FMT_STRING("length cannot be 0"));
setError(); setError();
return; return;
} }
m_dataCopy.reset(new uint8_t[length]); m_dataCopy.reset(new atUint8[length]);
m_data = m_dataCopy.get(); m_data = m_dataCopy.get();
if (data) if (data)
memmove(m_data, data, length); memmove(m_data, data, length);
@@ -46,28 +46,28 @@ MemoryCopyWriter::MemoryCopyWriter(std::string_view filename) {
m_filepath = filename; m_filepath = filename;
m_length = 0x10; m_length = 0x10;
m_position = 0; m_position = 0;
m_dataCopy.reset(new uint8_t[m_length]); m_dataCopy.reset(new atUint8[m_length]);
m_data = m_dataCopy.get(); m_data = m_dataCopy.get();
m_bufferOwned = false; m_bufferOwned = false;
if (!m_data) { if (!m_data) {
atError("Could not allocate memory!"); atError(FMT_STRING("Could not allocate memory!"));
setError(); setError();
return; return;
} }
} }
void MemoryWriter::seek(int64_t position, SeekOrigin origin) { void MemoryWriter::seek(atInt64 position, SeekOrigin origin) {
switch (origin) { switch (origin) {
case SeekOrigin::Begin: case SeekOrigin::Begin:
if (position < 0) { if (position < 0) {
atError("Position outside stream bounds"); atError(FMT_STRING("Position outside stream bounds"));
setError(); setError();
return; return;
} }
if ((uint64_t)position > m_length) { if ((atUint64)position > m_length) {
atError("data exceeds available buffer space"); atError(FMT_STRING("data exceeds available buffer space"));
setError(); setError();
return; return;
} }
@@ -76,14 +76,14 @@ void MemoryWriter::seek(int64_t position, SeekOrigin origin) {
break; break;
case SeekOrigin::Current: case SeekOrigin::Current:
if ((((int64_t)m_position + position) < 0)) { if ((((atInt64)m_position + position) < 0)) {
atError("Position outside stream bounds"); atError(FMT_STRING("Position outside stream bounds"));
setError(); setError();
return; return;
} }
if (m_position + position > m_length) { if (m_position + position > m_length) {
atError("data exceeds available buffer space"); atError(FMT_STRING("data exceeds available buffer space"));
setError(); setError();
return; return;
} }
@@ -92,14 +92,14 @@ void MemoryWriter::seek(int64_t position, SeekOrigin origin) {
break; break;
case SeekOrigin::End: case SeekOrigin::End:
if (((int64_t)m_length - position) < 0) { if (((atInt64)m_length - position) < 0) {
atError("Position outside stream bounds"); atError(FMT_STRING("Position outside stream bounds"));
setError(); setError();
return; return;
} }
if ((uint64_t)position > m_length) { if ((atUint64)position > m_length) {
atError("data exceeds available buffer space"); atError(FMT_STRING("data exceeds available buffer space"));
setError(); setError();
return; return;
} }
@@ -109,24 +109,24 @@ void MemoryWriter::seek(int64_t position, SeekOrigin origin) {
} }
} }
void MemoryCopyWriter::seek(int64_t position, SeekOrigin origin) { void MemoryCopyWriter::seek(atInt64 position, SeekOrigin origin) {
switch (origin) { switch (origin) {
case SeekOrigin::Begin: case SeekOrigin::Begin:
if (position < 0) { if (position < 0) {
atError("Position outside stream bounds"); atError(FMT_STRING("Position outside stream bounds"));
setError(); setError();
return; return;
} }
if ((uint64_t)position > m_length) if ((atUint64)position > m_length)
resize(position); resize(position);
m_position = position; m_position = position;
break; break;
case SeekOrigin::Current: case SeekOrigin::Current:
if ((((int64_t)m_position + position) < 0)) { if ((((atInt64)m_position + position) < 0)) {
atError("Position outside stream bounds"); atError(FMT_STRING("Position outside stream bounds"));
setError(); setError();
return; return;
} }
@@ -138,13 +138,13 @@ void MemoryCopyWriter::seek(int64_t position, SeekOrigin origin) {
break; break;
case SeekOrigin::End: case SeekOrigin::End:
if (((int64_t)m_length - position) < 0) { if (((atInt64)m_length - position) < 0) {
atError("Position outside stream bounds"); atError(FMT_STRING("Position outside stream bounds"));
setError(); setError();
return; return;
} }
if ((uint64_t)position > m_length) if ((atUint64)position > m_length)
resize(position); resize(position);
m_position = m_length - position; m_position = m_length - position;
@@ -152,7 +152,7 @@ void MemoryCopyWriter::seek(int64_t position, SeekOrigin origin) {
} }
} }
void MemoryWriter::setData(uint8_t* data, uint64_t length, bool takeOwnership) { void MemoryWriter::setData(atUint8* data, atUint64 length, bool takeOwnership) {
if (m_bufferOwned) if (m_bufferOwned)
delete m_data; delete m_data;
@@ -162,8 +162,8 @@ void MemoryWriter::setData(uint8_t* data, uint64_t length, bool takeOwnership) {
m_bufferOwned = takeOwnership; m_bufferOwned = takeOwnership;
} }
void MemoryCopyWriter::setData(const uint8_t* data, uint64_t length) { void MemoryCopyWriter::setData(const atUint8* data, atUint64 length) {
m_dataCopy.reset(new uint8_t[length]); m_dataCopy.reset(new atUint8[length]);
m_data = m_dataCopy.get(); m_data = m_dataCopy.get();
memmove(m_data, data, length); memmove(m_data, data, length);
m_length = length; m_length = length;
@@ -171,8 +171,8 @@ void MemoryCopyWriter::setData(const uint8_t* data, uint64_t length) {
m_bufferOwned = false; m_bufferOwned = false;
} }
uint8_t* MemoryWriter::data() const { atUint8* MemoryWriter::data() const {
uint8_t* ret = new uint8_t[m_length]; atUint8* ret = new atUint8[m_length];
memset(ret, 0, m_length); memset(ret, 0, m_length);
memmove(ret, m_data, m_length); memmove(ret, m_data, m_length);
return ret; return ret;
@@ -180,7 +180,7 @@ uint8_t* MemoryWriter::data() const {
void MemoryWriter::save(std::string_view filename) { void MemoryWriter::save(std::string_view filename) {
if (filename.empty() && m_filepath.empty()) { if (filename.empty() && m_filepath.empty()) {
atError("No file specified, cannot save."); atError(FMT_STRING("No file specified, cannot save."));
setError(); setError();
return; return;
} }
@@ -189,26 +189,25 @@ void MemoryWriter::save(std::string_view filename) {
m_filepath = filename; m_filepath = filename;
} }
auto deleter = [](FILE* f) { return std::fclose(f); }; std::unique_ptr<FILE, decltype(&std::fclose)> out{std::fopen(m_filepath.c_str(), "wb"), std::fclose};
std::unique_ptr<FILE, decltype(deleter)> out{std::fopen(m_filepath.c_str(), "wb"), deleter};
if (!out) { if (!out) {
atError("Unable to open file '{}'", m_filepath); atError(FMT_STRING("Unable to open file '{}'"), m_filepath);
setError(); setError();
return; return;
} }
uint64_t done = 0; atUint64 done = 0;
uint64_t blocksize = BLOCKSZ; atUint64 blocksize = BLOCKSZ;
do { do {
if (blocksize > m_length - done) { if (blocksize > m_length - done) {
blocksize = m_length - done; blocksize = m_length - done;
} }
const int64_t ret = std::fwrite(m_data + done, 1, blocksize, out.get()); const atInt64 ret = std::fwrite(m_data + done, 1, blocksize, out.get());
if (ret < 0) { if (ret < 0) {
atError("Error writing data to disk"); atError(FMT_STRING("Error writing data to disk"));
setError(); setError();
return; return;
} }
@@ -221,15 +220,15 @@ void MemoryWriter::save(std::string_view filename) {
} while (done < m_length); } while (done < m_length);
} }
void MemoryWriter::writeUBytes(const uint8_t* data, uint64_t length) { void MemoryWriter::writeUBytes(const atUint8* data, atUint64 length) {
if (!data) { if (!data) {
atError("data cannnot be NULL"); atError(FMT_STRING("data cannnot be NULL"));
setError(); setError();
return; return;
} }
if (m_position + length > m_length) { if (m_position + length > m_length) {
atError("data length exceeds available buffer space"); atError(FMT_STRING("data length exceeds available buffer space"));
setError(); setError();
return; return;
} }
@@ -239,9 +238,9 @@ void MemoryWriter::writeUBytes(const uint8_t* data, uint64_t length) {
m_position += length; m_position += length;
} }
void MemoryCopyWriter::writeUBytes(const uint8_t* data, uint64_t length) { void MemoryCopyWriter::writeUBytes(const atUint8* data, atUint64 length) {
if (!data) { if (!data) {
atError("data cannnot be NULL"); atError(FMT_STRING("data cannnot be NULL"));
setError(); setError();
return; return;
} }
@@ -254,14 +253,14 @@ void MemoryCopyWriter::writeUBytes(const uint8_t* data, uint64_t length) {
m_position += length; m_position += length;
} }
void MemoryCopyWriter::resize(uint64_t newSize) { void MemoryCopyWriter::resize(atUint64 newSize) {
if (newSize < m_length) { if (newSize < m_length) {
atError("New size cannot be less to the old size."); atError(FMT_STRING("New size cannot be less to the old size."));
return; return;
} }
// Allocate and copy new buffer // Allocate and copy new buffer
auto newArray = std::make_unique<uint8_t[]>(newSize); auto newArray = std::make_unique<atUint8[]>(newSize);
if (m_dataCopy) { if (m_dataCopy) {
std::memmove(newArray.get(), m_dataCopy.get(), m_length); std::memmove(newArray.get(), m_dataCopy.get(), m_length);
} }

View File

@@ -17,7 +17,7 @@ void SkywardSwordFile::addQuest(athena::SkywardSwordQuest* q) {
m_quests.push_back(q); m_quests.push_back(q);
} }
SkywardSwordQuest* SkywardSwordFile::quest(uint32_t id) { SkywardSwordQuest* SkywardSwordFile::quest(atUint32 id) {
if (id > m_quests.size() - 1) { if (id > m_quests.size() - 1) {
atWarning("index out of range"); atWarning("index out of range");
return nullptr; return nullptr;

View File

@@ -5,7 +5,7 @@
namespace athena::io { namespace athena::io {
SkywardSwordFileReader::SkywardSwordFileReader(uint8_t* data, uint64_t length) : MemoryCopyReader(data, length) { SkywardSwordFileReader::SkywardSwordFileReader(atUint8* data, atUint64 length) : MemoryCopyReader(data, length) {
setEndian(Endian::Big); setEndian(Endian::Big);
} }
@@ -21,7 +21,7 @@ SkywardSwordFile* SkywardSwordFileReader::read() {
return nullptr; return nullptr;
} }
uint32_t magic = readUint32(); atUint32 magic = readUint32();
if (magic != SkywardSwordFile::USMagic && magic != SkywardSwordFile::JAMagic && magic != SkywardSwordFile::EUMagic) { if (magic != SkywardSwordFile::USMagic && magic != SkywardSwordFile::JAMagic && magic != SkywardSwordFile::EUMagic) {
atError("Not a valid Skyward Sword save file"); atError("Not a valid Skyward Sword save file");
@@ -29,7 +29,7 @@ SkywardSwordFile* SkywardSwordFileReader::read() {
} }
seek(0x01C, SeekOrigin::Begin); seek(0x01C, SeekOrigin::Begin);
uint32_t headerSize = readUint32(); // Seems to be (headerSize - 1) atUint32 headerSize = readUint32(); // Seems to be (headerSize - 1)
if (headerSize != 0x1D) { if (headerSize != 0x1D) {
atError("Invalid header size, Corrupted data?"); atError("Invalid header size, Corrupted data?");
@@ -44,7 +44,7 @@ SkywardSwordFile* SkywardSwordFileReader::read() {
for (int i = 0; i < 3; i++) { for (int i = 0; i < 3; i++) {
SkywardSwordQuest* q = new SkywardSwordQuest(readUBytes(0x53C0), 0x53C0); SkywardSwordQuest* q = new SkywardSwordQuest(readUBytes(0x53C0), 0x53C0);
uint64_t pos = position(); atUint64 pos = position();
// seek to the skip data for this particular quest // seek to the skip data for this particular quest
seek(0xFB60 + (i * 0x24), SeekOrigin::Begin); seek(0xFB60 + (i * 0x24), SeekOrigin::Begin);
q->setSkipData(readUBytes(0x24)); q->setSkipData(readUBytes(0x24));

View File

@@ -4,7 +4,7 @@
namespace athena::io { namespace athena::io {
SkywardSwordFileWriter::SkywardSwordFileWriter(uint8_t* data, uint64_t len) : MemoryCopyWriter(data, len) { SkywardSwordFileWriter::SkywardSwordFileWriter(atUint8* data, atUint64 len) : MemoryCopyWriter(data, len) {
setEndian(Endian::Big); setEndian(Endian::Big);
} }
@@ -18,7 +18,7 @@ void SkywardSwordFileWriter::write(SkywardSwordFile* file) {
return; return;
} }
uint32_t magic = (file->region() == Region::NTSC atUint32 magic = (file->region() == Region::NTSC
? SkywardSwordFile::USMagic ? SkywardSwordFile::USMagic
: (file->region() == Region::NTSCJ ? SkywardSwordFile::JAMagic : SkywardSwordFile::EUMagic)); : (file->region() == Region::NTSCJ ? SkywardSwordFile::JAMagic : SkywardSwordFile::EUMagic));
@@ -39,7 +39,7 @@ void SkywardSwordFileWriter::write(SkywardSwordFile* file) {
q->fixChecksums(); q->fixChecksums();
// Write the save data // Write the save data
writeUBytes(q->data(), q->length()); writeUBytes(q->data(), q->length());
uint64_t pos = position(); atUint64 pos = position();
// Write the slots skip data // Write the slots skip data
seek(0xFB60 + (i * 0x24), SeekOrigin::Begin); seek(0xFB60 + (i * 0x24), SeekOrigin::Begin);
writeUBytes(q->skipData(), 0x24); writeUBytes(q->skipData(), 0x24);

Some files were not shown because too many files have changed in this diff Show More