[nostalgia] Integrate Ox Preloader

This commit is contained in:
Gary Talent 2022-11-30 01:47:33 -06:00
parent cbb496c59f
commit 090fe28b44
41 changed files with 404 additions and 159 deletions

16
.gitignore vendored
View File

@ -2,17 +2,19 @@
.clangd
.current_build
.conanbuild
.mypy_cache
.stfolder
scripts/__pycache__
compile_commands.json
CMakeLists.txt.user
ROM.oxfs
Session.vim
build
compile_commands.json
dist
tags
graph_info.json
imgui.ini
nostalgia.gba
nostalgia.sav
nostalgia_media.oxfs
media_header.txt
studio_state.json
CMakeLists.txt.user
Session.vim
ROM.oxfs
graph_info.json
tags

View File

@ -2,7 +2,7 @@
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="ClangTidy" enabled="true" level="WARNING" enabled_by_default="true">
<option name="clangTidyChecks" value="-*,bugprone-argument-comment,bugprone-assert-side-effect,bugprone-bad-signal-to-kill-thread,bugprone-branch-clone,bugprone-copy-constructor-init,bugprone-dangling-handle,bugprone-dynamic-static-initializers,bugprone-fold-init-type,bugprone-forward-declaration-namespace,bugprone-forwarding-reference-overload,bugprone-inaccurate-erase,bugprone-incorrect-roundings,bugprone-integer-division,bugprone-lambda-function-name,bugprone-macro-parentheses,bugprone-macro-repeated-side-effects,bugprone-misplaced-operator-in-strlen-in-alloc,bugprone-misplaced-pointer-arithmetic-in-alloc,bugprone-misplaced-widening-cast,bugprone-move-forwarding-reference,bugprone-multiple-statement-macro,bugprone-no-escape,bugprone-not-null-terminated-result,bugprone-parent-virtual-call,bugprone-posix-return,bugprone-reserved-identifier,bugprone-sizeof-container,bugprone-sizeof-expression,bugprone-spuriously-wake-up-functions,bugprone-string-constructor,bugprone-string-integer-assignment,bugprone-string-literal-with-embedded-nul,bugprone-suspicious-enum-usage,bugprone-suspicious-include,bugprone-suspicious-memset-usage,bugprone-suspicious-missing-comma,bugprone-suspicious-semicolon,bugprone-suspicious-string-compare,bugprone-swapped-arguments,bugprone-terminating-continue,bugprone-throw-keyword-missing,bugprone-too-small-loop-variable,bugprone-undefined-memory-manipulation,bugprone-undelegated-constructor,bugprone-unhandled-self-assignment,bugprone-unused-raii,bugprone-unused-return-value,bugprone-use-after-move,bugprone-virtual-near-miss,cert-dcl21-cpp,cert-dcl58-cpp,cert-err34-c,cert-err52-cpp,cert-err58-cpp,cert-err60-cpp,cert-flp30-c,cert-msc50-cpp,cert-msc51-cpp,cert-str34-c,cppcoreguidelines-interfaces-global-init,cppcoreguidelines-narrowing-conversions,cppcoreguidelines-pro-type-member-init,cppcoreguidelines-pro-type-static-cast-downcast,cppcoreguidelines-slicing,google-default-arguments,google-explicit-constructor,google-runtime-operator,hicpp-exception-baseclass,hicpp-multiway-paths-covered,misc-misplaced-const,misc-new-delete-overloads,misc-non-copyable-objects,misc-throw-by-value-catch-by-reference,misc-unconventional-assign-operator,misc-uniqueptr-reset-release,modernize-avoid-bind,modernize-concat-nested-namespaces,modernize-deprecated-headers,modernize-deprecated-ios-base-aliases,modernize-loop-convert,modernize-make-shared,modernize-make-unique,modernize-pass-by-value,modernize-raw-string-literal,modernize-redundant-void-arg,modernize-replace-auto-ptr,modernize-replace-disallow-copy-and-assign-macro,modernize-replace-random-shuffle,modernize-return-braced-init-list,modernize-shrink-to-fit,modernize-unary-static-assert,modernize-use-auto,modernize-use-bool-literals,modernize-use-emplace,modernize-use-equals-default,modernize-use-equals-delete,modernize-use-nodiscard,modernize-use-noexcept,modernize-use-nullptr,modernize-use-override,modernize-use-transparent-functors,modernize-use-uncaught-exceptions,mpi-buffer-deref,mpi-type-mismatch,openmp-use-default-none,performance-faster-string-find,performance-for-range-copy,performance-implicit-conversion-in-loop,performance-inefficient-algorithm,performance-inefficient-string-concatenation,performance-inefficient-vector-operation,performance-move-const-arg,performance-move-constructor-init,performance-no-automatic-move,performance-noexcept-move-constructor,performance-trivially-destructible,performance-type-promotion-in-math-fn,performance-unnecessary-copy-initialization,performance-unnecessary-value-param,portability-simd-intrinsics,readability-avoid-const-params-in-decls,readability-const-return-type,readability-container-size-empty,readability-convert-member-functions-to-static,readability-delete-null-pointer,readability-deleted-default,readability-inconsistent-declaration-parameter-name,readability-make-member-function-const,readability-misleading-indentation,readability-misplaced-array-index,readability-non-const-parameter,readability-redundant-control-flow,readability-redundant-declaration,readability-redundant-function-ptr-dereference,readability-redundant-smartptr-get,readability-redundant-string-cstr,readability-redundant-string-init,readability-simplify-subscript-expr,readability-static-accessed-through-instance,readability-static-definition-in-anonymous-namespace,readability-string-compare,readability-uniqueptr-delete-release,readability-use-anyofallof" />
<option name="clangTidyChecks" value="-*,cppcoreguidelines-interfaces-global-init,cppcoreguidelines-narrowing-conversions,cppcoreguidelines-pro-type-member-init,cppcoreguidelines-pro-type-static-cast-downcast,cppcoreguidelines-slicing,google-default-arguments,google-explicit-constructor,google-runtime-operator,hicpp-exception-baseclass,hicpp-multiway-paths-covered,mpi-buffer-deref,mpi-type-mismatch,openmp-use-default-none,performance-faster-string-find,performance-for-range-copy,performance-implicit-conversion-in-loop,performance-inefficient-algorithm,performance-inefficient-string-concatenation,performance-inefficient-vector-operation,performance-move-const-arg,performance-move-constructor-init,performance-no-automatic-move,performance-noexcept-move-constructor,performance-trivially-destructible,performance-type-promotion-in-math-fn,performance-unnecessary-copy-initialization,performance-unnecessary-value-param,readability-avoid-const-params-in-decls,readability-const-return-type,readability-container-size-empty,readability-convert-member-functions-to-static,readability-delete-null-pointer,readability-deleted-default,readability-inconsistent-declaration-parameter-name,readability-make-member-function-const,readability-misleading-indentation,readability-misplaced-array-index,readability-non-const-parameter,readability-redundant-control-flow,readability-redundant-declaration,readability-redundant-function-ptr-dereference,readability-redundant-smartptr-get,readability-redundant-string-cstr,readability-redundant-string-init,readability-simplify-subscript-expr,readability-static-accessed-through-instance,readability-static-definition-in-anonymous-namespace,readability-string-compare,readability-uniqueptr-delete-release,readability-use-anyofallof,cert-*,misc-*,readability-duplicate-include,-misc-non-private-member-variables-in-classes,-misc-no-recursion,bugprone-*,clang-analyzer-*,modernize-*,portability-*,-modernize-use-trailing-return-type,-bugprone-easily-swappable-parameters" />
</inspection_tool>
<inspection_tool class="Clazy" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="ConstantConditionsOC" enabled="false" level="WARNING" enabled_by_default="false" />
@ -13,6 +13,7 @@
<inspection_tool class="InfiniteRecursion" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="LocalValueEscapesScope" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="LoopDoesntUseConditionVariable" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="NullDereference" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="NullDereferences" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="UnreachableCallsOfFunction" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="UnreachableCode" enabled="false" level="WARNING" enabled_by_default="false" />

8
.idea/modules.xml generated
View File

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/nostalgia.iml" filepath="$PROJECT_DIR$/.idea/nostalgia.iml" />
</modules>
</component>
</project>

8
.idea/nostalgia.iml generated
View File

@ -1,2 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<module classpath="External" external.linked.project.id="nostalgia" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="CompDB" type="CPP_MODULE" version="4" />
<module version="4">
<component name="FacetManager">
<facet type="Python" name="Python facet">
<configuration sdkName="Python 3.8" />
</facet>
</component>
</module>

View File

@ -1,14 +1,14 @@
{
"init_functions": [
{
"bin_path": "/home/gary/projects/nostalgia/dist/linux-x86_64-debug/lib/ox/libOxTraceHook.so",
"bin_path": "dist/linux-x86_64-debug/lib/ox/libOxTraceHook.so",
"function": "oxTraceInitHook",
"ignore_frames": 3
}
],
"log_functions": [
{
"bin_path": "/home/gary/projects/nostalgia/dist/linux-x86_64-debug/lib/ox/libOxTraceHook.so",
"bin_path": "dist/linux-x86_64-debug/lib/ox/libOxTraceHook.so",
"function": "oxTraceHook",
"ignore_frames": 3
}

View File

@ -1,4 +1,4 @@
FROM fedora:34
FROM fedora:36
RUN dnf update -y
@ -12,25 +12,25 @@ RUN chmod +x /usr/local/bin/gosu
###############################################################################
# Install dev tools
RUN dnf install -y clang
RUN dnf install -y llvm
RUN dnf install -y libasan
RUN dnf install -y mingw64-gcc-c++
RUN dnf install -y cmake
RUN dnf install -y make
RUN dnf install -y git
RUN dnf install -y vim
RUN dnf install -y sudo
RUN dnf install -y fuse-devel
RUN dnf install -y findutils
RUN dnf install -y ninja-build
RUN dnf install -y libcxx-devel libcxxabi-devel
RUN dnf install -y unzip
RUN dnf install -y ccache
RUN dnf install -y pacman
RUN dnf install -y python3-pip
RUN dnf install -y libglvnd-devel
RUN dnf install -y gtk3-devel
RUN dnf install -y clang \
llvm \
libasan \
mingw64-gcc-c++ \
cmake \
make \
git \
vim \
sudo \
fuse-devel \
findutils \
ninja-build \
libcxx-devel libcxxabi-devel \
unzip \
ccache \
pacman \
python3-pip \
libglvnd-devel \
gtk3-devel
RUN pip install conan
###############################################################################

View File

@ -12,8 +12,7 @@ else
endif
.PHONY: pkg-gba
pkg-gba:
${ENV_RUN} ${CMAKE_BUILD} build install
pkg-gba: install
${ENV_RUN} ./scripts/pkg-gba sample_project
.PHONY: run

View File

@ -1,4 +1,4 @@
O1;net.drinkingtea.ox.DescriptorType;2;{
O1;net.drinkingtea.ox.TypeDescriptor;1;{
"length" : 4,
"primitiveType" : 1,
"typeName" : "B.int32"

View File

@ -1,4 +1,4 @@
O1;net.drinkingtea.ox.DescriptorType;2;{
O1;net.drinkingtea.ox.TypeDescriptor;1;{
"length" : 1,
"primitiveType" : 1,
"typeName" : "B.int8"

View File

@ -1,4 +1,4 @@
O1;net.drinkingtea.ox.DescriptorType;2;{
O1;net.drinkingtea.ox.TypeDescriptor;1;{
"primitiveType" : 4,
"typeName" : "B.string"
}

View File

@ -1,4 +1,4 @@
O1;net.drinkingtea.ox.DescriptorType;2;{
O1;net.drinkingtea.ox.TypeDescriptor;1;{
"length" : 2,
"typeName" : "B.uint16"
}

View File

@ -1,4 +1,4 @@
O1;net.drinkingtea.ox.DescriptorType;2;{
O1;net.drinkingtea.ox.TypeDescriptor;1;{
"length" : 8,
"typeName" : "B.uint64"
}

View File

@ -1,4 +1,4 @@
O1;net.drinkingtea.ox.DescriptorType;2;{
O1;net.drinkingtea.ox.TypeDescriptor;1;{
"length" : 1,
"typeName" : "B.uint8"
}

View File

@ -1,10 +1,16 @@
O1;net.drinkingtea.ox.DescriptorType;2;{
O1;net.drinkingtea.ox.TypeDescriptor;1;{
"fieldList" :
[
{
"fieldName" : "colors",
"subscriptLevels" : 1,
"typeName" : "B.uint16"
"subscriptStack" :
[
{
"subscriptType" : 4
}
],
"typeId" : "B.uint16;0"
}
],
"primitiveType" : 5,

View File

@ -1,27 +1,39 @@
O1;net.drinkingtea.ox.DescriptorType;2;{
O1;net.drinkingtea.ox.TypeDescriptor;1;{
"fieldList" :
[
{
"fieldName" : "name",
"typeName" : "B.string"
"typeId" : "net.drinkingtea.ox.BasicString<8>;1"
},
{
"fieldName" : "rows",
"typeName" : "B.int32"
"typeId" : "B.int32;0"
},
{
"fieldName" : "columns",
"typeName" : "B.int32"
"typeId" : "B.int32;0"
},
{
"fieldName" : "subsheets",
"subscriptLevels" : 1,
"typeName" : "net.drinkingtea.nostalgia.core.TileSheet.SubSheet"
"subscriptStack" :
[
{
"subscriptType" : 4
}
],
"typeId" : "net.drinkingtea.nostalgia.core.TileSheet.SubSheet;1"
},
{
"fieldName" : "pixels",
"subscriptLevels" : 1,
"typeName" : "B.uint8"
"subscriptStack" :
[
{
"subscriptType" : 4
}
],
"typeId" : "B.uint8;0"
}
],
"primitiveType" : 5,

View File

@ -1,17 +1,17 @@
O1;net.drinkingtea.ox.DescriptorType;2;{
O1;net.drinkingtea.ox.TypeDescriptor;1;{
"fieldList" :
[
{
"fieldName" : "bpp",
"typeName" : "B.int8"
"typeId" : "B.int8;0"
},
{
"fieldName" : "defaultPalette",
"typeName" : "net.drinkingtea.ox.FileAddress"
"typeId" : "net.drinkingtea.ox.FileAddress;1"
},
{
"fieldName" : "subsheet",
"typeName" : "net.drinkingtea.nostalgia.core.TileSheet.SubSheet"
"typeId" : "net.drinkingtea.nostalgia.core.TileSheet.SubSheet;1"
}
],
"primitiveType" : 5,

View File

@ -0,0 +1,9 @@
O1;net.drinkingtea.ox.TypeDescriptor;1;{
"primitiveType" : 4,
"typeName" : "net.drinkingtea.ox.BasicString",
"typeParams" :
[
"8"
],
"typeVersion" : 1
}

View File

@ -1,17 +1,17 @@
O1;net.drinkingtea.ox.DescriptorType;2;{
O1;net.drinkingtea.ox.TypeDescriptor;1;{
"fieldList" :
[
{
"fieldName" : "path",
"typeName" : "B.string"
"typeId" : "B.string"
},
{
"fieldName" : "constPath",
"typeName" : "B.string"
"typeId" : "B.string"
},
{
"fieldName" : "inode",
"typeName" : "B.uint64"
"typeId" : "B.uint64;0"
}
],
"primitiveType" : 6,

View File

@ -1,13 +1,13 @@
O1;net.drinkingtea.ox.DescriptorType;2;{
O1;net.drinkingtea.ox.TypeDescriptor;1;{
"fieldList" :
[
{
"fieldName" : "type",
"typeName" : "B.int8"
"typeId" : "B.int8;0"
},
{
"fieldName" : "data",
"typeName" : "net.drinkingtea.ox.FileAddress.Data"
"typeId" : "net.drinkingtea.ox.FileAddress.Data"
}
],
"primitiveType" : 5,

Binary file not shown.

Binary file not shown.

View File

@ -1,24 +1,16 @@
#! /usr/bin/env bash
set -e
set -u
OS=$(uname | tr [:upper:] [:lower:])
HOST_ENV=${OS}-$(uname -m)
BIN=./dist/${HOST_ENV}-$(cat .current_build)/bin/
PATH=$BIN:${DEVKITPRO}/tools/bin/:${DEVKITARM}/bin/:$PATH
NOSTALGIA_BIN=build/gba-*/src/nostalgia/player/nostalgia.bin
NOSTALGIA_MEDIA=nostalgia_media.oxfs
NOSTALGIA_BIN=build/$(hostname)/gba-*/src/nostalgia/player/nostalgia.bin
NOSTALGIA_PROJECT=$1
NOSTALGIA_GBA=nostalgia.gba
MEDIA_HEADER=media_header.txt
echo NOSTALGIA_MEDIA_HEADER_________ > $MEDIA_HEADER
nost-pack -src $NOSTALGIA_PROJECT -dst $NOSTALGIA_MEDIA
padbin 32 $NOSTALGIA_BIN
ls -lh $NOSTALGIA_BIN
cat $NOSTALGIA_BIN $MEDIA_HEADER $NOSTALGIA_MEDIA > $NOSTALGIA_GBA
rm -f $MEDIA_HEADER #$NOSTALGIA_MEDIA
cp $NOSTALGIA_BIN $NOSTALGIA_GBA
${BIN}/nost-pack -src $NOSTALGIA_PROJECT -rom-bin $NOSTALGIA_GBA
gbafix $NOSTALGIA_GBA

View File

@ -17,6 +17,7 @@ class AssetManager;
template<typename T>
class AssetRef;
#ifndef OX_BARE_METAL
template<typename T>
class AssetContainer {
@ -260,5 +261,36 @@ class AssetManager {
}
}
};
#else
template<typename T>
class AssetRef: public ox::SignalHandler {
private:
T &m_obj;
public:
explicit constexpr AssetRef(T &obj) noexcept: m_obj(obj) {
}
constexpr const T *get() const noexcept {
return &m_obj;
}
constexpr const T &operator*() const & noexcept {
return &m_obj;
}
constexpr const T &&operator*() const && noexcept {
return &m_obj;
}
constexpr const T *operator->() const noexcept {
return &m_obj;
}
explicit constexpr operator bool() const noexcept {
return m_obj;
}
};
#endif
}

View File

@ -91,6 +91,7 @@ class Context {
ox::UniquePtr<BaseClipboardObject> clipboard;
#else
bool running = true;
std::size_t preloadSectionOffset = 0;
#endif
protected:
#ifndef OX_BARE_METAL

View File

@ -37,13 +37,31 @@ static void initTimer() noexcept {
REG_IE = REG_IE | Int_timer0;
}
static ox::Result<std::size_t> findPreloadSection() noexcept {
// put the header in the wrong order to prevent mistaking this code for the
// media section
constexpr auto headerP2 = "D_HEADER________";
constexpr auto headerP1 = "NOSTALGIA_PRELOA";
constexpr auto headerP1Len = ox_strlen(headerP2);
constexpr auto headerP2Len = ox_strlen(headerP1);
constexpr auto headerLen = headerP1Len + headerP2Len;
for (auto current = MEM_ROM; current < reinterpret_cast<char*>(0x0a000000); current += headerLen) {
if (ox_memcmp(current, headerP1, headerP1Len) == 0 &&
ox_memcmp(current + headerP1Len, headerP2, headerP2Len) == 0) {
return reinterpret_cast<std::size_t>(current + headerLen);
}
}
return OxError(1);
}
ox::Result<ox::UniquePtr<Context>> init(ox::UniquePtr<ox::FileSystem> fs, const char *appName) noexcept {
auto ctx = ox::make_unique<Context>();
ctx->rom = std::move(fs);
ctx->appName = std::move(appName);
ctx->appName = appName;
oxReturnError(initGfx(ctx.get()));
initTimer();
initIrq();
oxReturnError(findPreloadSection().moveTo(&ctx->preloadSectionOffset));
return ctx;
}

View File

@ -213,7 +213,8 @@ ox::Error loadSpritePalette(Context *ctx, unsigned cbb, const ox::FileAddress &p
// Do NOT use Context in the GBA version of this function.
void puts(Context *ctx, int column, int row, const char *str) noexcept {
for (int i = 0; str[i]; i++) {
setTile(ctx, 0, column + i, row, static_cast<uint8_t>(charMap[static_cast<int>(str[i])]));
const auto c = charMap[static_cast<unsigned>(str[i])];
setTile(ctx, 0, column + i, row, static_cast<uint8_t>(c));
}
}

View File

@ -2,7 +2,8 @@
* Copyright 2016 - 2022 Gary Talent (gary@drinkingtea.net). All rights reserved.
*/
#include <ox/fs/fs.hpp>
#include <ox/mc/read.hpp>
#include <ox/preloader/preloader.hpp>
#include <ox/std/std.hpp>
#include "../media.hpp"
@ -14,11 +15,11 @@ namespace nostalgia::core {
ox::Result<char*> loadRom(const char*) noexcept {
// put the header in the wrong order to prevent mistaking this code for the
// media section
constexpr auto headerP2 = "_HEADER_________";
constexpr auto headerP1 = "NOSTALGIA_MEDIA";
constexpr auto headerP1Len = 15;
constexpr auto headerP2Len = 16;
constexpr auto headerLen = headerP1Len + headerP2Len + 1;
constexpr auto headerP2 = "HEADER__________";
constexpr auto headerP1 = "NOSTALGIA_MEDIA_";
constexpr auto headerP1Len = ox_strlen(headerP2);
constexpr auto headerP2Len = ox_strlen(headerP1);
constexpr auto headerLen = headerP1Len + headerP2Len;
for (auto current = MEM_ROM; current < reinterpret_cast<char*>(0x0a000000); current += headerLen) {
if (ox_memcmp(current, headerP1, headerP1Len) == 0 &&
ox_memcmp(current + headerP1Len, headerP2, headerP2Len) == 0) {
@ -31,4 +32,12 @@ ox::Result<char*> loadRom(const char*) noexcept {
void unloadRom(char*) noexcept {
}
ox::Result<std::size_t> getPreloadAddr(Context *ctx, const ox::FileAddress &file) noexcept {
oxRequire(stat, ctx->rom->stat(file));
oxRequire(buff, ctx->rom->directAccess(file));
PreloadPtr p;
oxReturnError(ox::readMC(buff, stat.size, &p));
return p.preloadAddr + ctx->preloadSectionOffset;
}
}

View File

@ -8,14 +8,28 @@
#include <ox/claw/claw.hpp>
#include <ox/fs/fs.hpp>
#include <ox/model/metadata.hpp>
#include "context.hpp"
#include "typeconv.hpp"
namespace nostalgia::core {
struct PreloadPtr {
static constexpr auto TypeName = "net.drinkingtea.ox.PreloadPtr";
static constexpr auto TypeVersion = 1;
uint32_t preloadAddr = 0;
};
oxModelBegin(PreloadPtr)
oxModelField(preloadAddr)
oxModelEnd()
ox::Result<std::size_t> getPreloadAddr(Context *ctx, const ox::FileAddress &file) noexcept;
template<typename T>
ox::Result<AssetRef<T>> readObj(Context *ctx, const ox::FileAddress &file, bool forceLoad = false) noexcept {
ox::Result<AssetRef<T>> readObj(Context *ctx, const ox::FileAddress &file,
[[maybe_unused]] bool forceLoad = false) noexcept {
#ifndef OX_BARE_METAL
constexpr auto readConvert = [](const ox::Buffer &buff) -> ox::Result<T> {
auto [obj, err] = ox::readClaw<T>(buff);
@ -43,12 +57,17 @@ ox::Result<AssetRef<T>> readObj(Context *ctx, const ox::FileAddress &file, bool
return std::move(cached);
}
#else
return OxError(1);
if constexpr(ox::preloadable<T>::value) {
return AssetRef<T>{*reinterpret_cast<T*>(getPreloadAddr(ctx, file))};
} else {
return OxError(1);
}
#endif
}
template<typename T>
ox::Error writeObj(Context *ctx, const ox::FileAddress &file, const T &obj, ox::ClawFormat fmt = ox::ClawFormat::Metal) noexcept {
ox::Error writeObj(Context *ctx, const ox::FileAddress &file, const T &obj,
ox::ClawFormat fmt = ox::ClawFormat::Metal) noexcept {
oxRequire(objBuff, ox::writeClaw(&obj, fmt));
return ctx->rom->write(file, objBuff.data(), objBuff.size());
}

View File

@ -6,13 +6,13 @@
namespace nostalgia::core {
ox::Result<ox::UniquePtr<ox::DescriptorType>> TypeStore::loadDescriptor(const ox::String &name, int version) noexcept {
ox::Result<ox::UniquePtr<ox::DescriptorType>> TypeStore::loadDescriptor(ox::CRStringView typeId) noexcept {
constexpr auto descPath = "/.nostalgia/type_descriptors";
auto path = ox::sfmt("{}/{};{}", descPath, name, version);
auto path = ox::sfmt("{}/{}", descPath, typeId);
oxRequire(buff, m_fs->read(path));
auto dt = ox::make_unique<ox::DescriptorType>();
oxReturnError(ox::readClaw<ox::DescriptorType>(buff, dt.get()));
return dt;
}
}
}

View File

@ -19,7 +19,7 @@ class TypeStore: public ox::TypeStore {
}
protected:
ox::Result<ox::UniquePtr<ox::DescriptorType>> loadDescriptor(const ox::String &name, int version) noexcept override;
ox::Result<ox::UniquePtr<ox::DescriptorType>> loadDescriptor(ox::CRStringView typeId) noexcept override;
};
}

View File

@ -32,4 +32,8 @@ void unloadRom(char *rom) noexcept {
ox::safeDelete(rom);
}
ox::Result<void*> findPreloadSection() noexcept {
return OxError(1, "findPreloadSection is unsupported on this platform");
}
}

View File

@ -45,6 +45,7 @@ ox::Error run(ox::UniquePtr<ox::FileSystem> fs) noexcept {
oxRequireM(ctx, core::init(std::move(fs)));
constexpr auto TileSheetAddr = "/TileSheets/Charset.ng";
constexpr auto PaletteAddr = "/Palettes/Charset.npal";
oxRequire(tsStat, ctx->rom->stat(PaletteAddr));
oxReturnError(core::loadSpriteTileSheet(ctx.get(), 0, TileSheetAddr, PaletteAddr));
oxReturnError(core::initConsole(ctx.get()));
core::puts(ctx.get(), 10, 9, "DOPENESS!!!");

View File

@ -4,6 +4,8 @@
#pragma once
#include <ox/fs/fs.hpp>
#include <ox/preloader/preloader.hpp>
#include <ox/std/error.hpp>
#include <ox/std/types.hpp>
#include <ox/std/vector.hpp>
@ -12,7 +14,6 @@ namespace nostalgia::scene {
struct TileDoc {
constexpr static auto Fields = 2;
constexpr static auto Preloadable = true;
constexpr static auto TypeName = "net.drinkingtea.nostalgia.scene.Tile";
constexpr static auto TypeVersion = 1;
@ -22,13 +23,10 @@ struct TileDoc {
};
template<typename T>
constexpr ox::Error model(T *io, TileDoc *obj) {
io->template setTypeInfo<TileDoc>();
oxReturnError(io->field("sheetIdx", &obj->sheetIdx));
oxReturnError(io->field("type", &obj->type));
return OxError(0);
}
oxModelBegin(TileDoc)
oxModelField(sheetIdx);
oxModelField(type);
oxModelEnd()
struct SceneDoc {
@ -36,30 +34,62 @@ struct SceneDoc {
using TileMapLayer = ox::Vector<TileMapRow>;
using TileMap = ox::Vector<TileMapLayer>;
constexpr static auto Fields = 1;
constexpr static auto Preloadable = true;
constexpr static auto TypeName = "net.drinkingtea.nostalgia.scene.Scene";
constexpr static auto TypeVersion = 1;
ox::FileAddress tilesheet;
ox::FileAddress palette;
TileMap tiles;
};
template<typename T>
constexpr ox::Error model(T *io, SceneDoc *obj) {
io->template setTypeInfo<SceneDoc>();
oxReturnError(io->field("tiles", &obj->tiles));
return OxError(0);
}
oxModelBegin(SceneDoc)
oxModelField(tilesheet)
oxModelField(palette)
oxModelField(tiles)
oxModelEnd()
struct SceneInstance {
uint16_t layers = 0;
uint16_t *columns = nullptr;
uint16_t *rows = nullptr;
uint16_t **tileMapIdx = nullptr;
uint8_t **tileType = nullptr;
struct Tile {
uint16_t &tileMapIdx;
uint8_t &tileType;
constexpr Tile(uint16_t &pTileMapIdx, uint8_t &pTileType) noexcept:
tileMapIdx(pTileMapIdx),
tileType(pTileType) {
}
};
struct Layer {
uint16_t &columns;
uint16_t &rows;
uint16_t *tileMapIdx;
uint8_t *tileType;
constexpr Layer(uint16_t &pColumns,
uint16_t &pRows,
uint16_t *pTileMapIdx,
uint8_t *pTileType) noexcept:
columns(pColumns),
rows(pRows),
tileMapIdx(pTileMapIdx),
tileType(pTileType) {
}
[[nodiscard]]
constexpr Tile tile(std::size_t i) const noexcept {
return {tileMapIdx[i], tileType[i]};
}
};
uint16_t layers = 0;
ox::Vector<uint16_t> columns;
ox::Vector<uint16_t> rows;
ox::Vector<ox::Vector<uint16_t>> tileMapIdx;
ox::Vector<ox::Vector<uint8_t>> tileType;
[[nodiscard]]
constexpr Layer layer(std::size_t i) noexcept {
return {columns[i], rows[i], tileMapIdx[i].data(), tileType[i].data()};
}
};
}

View File

@ -13,9 +13,9 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleVersion</key>
<string>1.2.8</string>
<string>0.0.0</string>
<key>LSMinimumSystemVersion</key>
<string>10.13.0</string>
<string>12.0.0</string>
<!-- HiDPI -->
<key>NSPrincipalClass</key>
@ -24,6 +24,6 @@
<string>True</string>
<key>NSHumanReadableCopyright</key>
<string>Copyright (c) 2016-2021 Gary Talent &lt;gary@drinkingtea.net&gt;</string>
<string>Copyright (c) 2016-2022 Gary Talent &lt;gary@drinkingtea.net&gt;</string>
</dict>
</plist>

View File

@ -57,7 +57,8 @@ class NOSTALGIASTUDIO_EXPORT Project {
/**
* Writes a MetalClaw object to the project at the given path.
*/
ox::Error writeObj(const ox::String &path, auto *obj, ox::ClawFormat fmt = ox::ClawFormat::Metal) noexcept;
template<typename T>
ox::Error writeObj(const ox::String &path, const T *obj, ox::ClawFormat fmt = ox::ClawFormat::Metal) noexcept;
template<typename T>
ox::Result<ox::UniquePtr<T>> loadObj(const ox::String &path) const noexcept;
@ -99,13 +100,16 @@ class NOSTALGIASTUDIO_EXPORT Project {
};
ox::Error Project::writeObj(const ox::String &path, auto *obj, ox::ClawFormat fmt) noexcept {
template<typename T>
ox::Error Project::writeObj(const ox::String &path, const T *obj, ox::ClawFormat fmt) noexcept {
// write MetalClaw
oxRequireM(buff, ox::writeClaw(obj, fmt));
// write to FS
oxReturnError(writeBuff(path, buff));
// write type descriptor
oxReturnError(ox::buildTypeDef(&m_typeStore, obj));
if (m_typeStore.get<T>().error) {
oxReturnError(ox::buildTypeDef(&m_typeStore, obj));
}
// write out type store
static constexpr auto descPath = "/.nostalgia/type_descriptors";
oxReturnError(mkdir(descPath));
@ -114,7 +118,7 @@ ox::Error Project::writeObj(const ox::String &path, auto *obj, ox::ClawFormat fm
// replace garbage last character with new line
typeOut.back().value = '\n';
// write to FS
const auto typePath = ox::sfmt("{}/{};{}", descPath, t->typeName, t->typeVersion);
const auto typePath = ox::sfmt("{}/{}", descPath, buildTypeId(*t));
oxReturnError(writeBuff(typePath, typeOut));
}
fileUpdated.emit(path);

View File

@ -110,7 +110,6 @@ void NewMenu::drawLastPageButtons(core::Context *ctx) noexcept {
void NewMenu::finish(core::Context *ctx) noexcept {
const auto err = m_types[static_cast<std::size_t>(m_selectedType)]->write(ctx, m_itemName.c_str());
if (err) {
oxDebugf("NewMenu::finish() error: {}", toStr(err));
oxLogError(err);
return;
}

View File

@ -33,6 +33,7 @@ StudioUI::StudioUI(core::Context *ctx) noexcept {
m_ctx = ctx;
m_projectExplorer = ox::make_unique<ProjectExplorer>(m_ctx);
m_projectExplorer->fileChosen.connect(this, &StudioUI::openFile);
ImGui::GetIO().IniFilename = nullptr;
loadModules();
// open project and files
const auto [config, err] = studio::readConfig<StudioConfig>(ctx);

View File

@ -7,43 +7,74 @@
#include <ox/clargs/clargs.hpp>
#include <ox/fs/fs.hpp>
#include <nostalgia/core/typestore.hpp>
#include "pack/pack.hpp"
static ox::Error writeFileBuff(const ox::String &path, const ox::Buffer &buff) noexcept {
using namespace nostalgia;
static ox::Error writeFileBuff(ox::CRString path, const ox::Buffer &buff) noexcept {
try {
std::ofstream f(path.c_str(), std::ios::binary);
f.write(buff.data(), static_cast<intptr_t>(buff.size()));
} catch (const std::fstream::failure&) {
return OxError(2, "failed to write file");
}
return OxError(0);
return {};
}
static ox::Result<ox::Buffer> readFileBuff(const char *path) noexcept {
std::ifstream file(path, std::ios::binary | std::ios::ate);
if (!file.good()) {
oxErrorf("Could not find OxFS file: {}", path);
return OxError(1, "Could not find OxFS file");
}
try {
const auto size = static_cast<std::size_t>(file.tellg());
ox::Buffer buff(size);
file.seekg(0, std::ios::beg);
file.read(buff.data(), static_cast<std::streamsize>(buff.size()));
return buff;
} catch (const std::ios_base::failure &e) {
oxErrorf("Could not read OxFS file: {}", e.what());
return OxError(2, "Could not read OxFS file");
}
}
static ox::Error run(const ox::ClArgs &args) noexcept {
ox::trace::init();
const auto argSrc = args.getString("src", "");
const auto argDst = args.getString("dst", "");
const auto argRomBin = args.getString("rom-bin", "");
if (argSrc == "") {
oxErr("\033[31;1;1merror:\033[0m must specify a source directory\n");
return OxError(1, "must specify a source directory");
}
if (argDst == "") {
oxErr("\033[31;1;1merror:\033[0m must specify a destination ROM file\n");
return OxError(1, "must specify a destination ROM file");
if (argRomBin == "") {
oxErr("\033[31;1;1merror:\033[0m must specify a path for preload file\n");
return OxError(1, "must specify a path for preload file");
}
ox::Buffer buff(32 * ox::units::MB);
oxReturnError(ox::FileSystem32::format(buff.data(), buff.size()));
ox::Buffer dstBuff(32 * ox::units::MB);
oxReturnError(ox::FileSystem32::format(dstBuff.data(), dstBuff.size()));
ox::PassThroughFS src(argSrc.c_str());
ox::FileSystem32 dst(ox::FileStore32(buff.data(), buff.size()));
oxReturnError(nostalgia::pack(&src, &dst));
ox::FileSystem32 dst(ox::FileStore32(dstBuff.data(), dstBuff.size()));
core::TypeStore ts(&src);
oxReturnError(pack(&ts, &src, &dst));
oxRequireM(pl, GbaPreloader::make());
oxReturnError(preload(&ts, &dst, pl.get()));
oxReturnError(dst.resize());
// resize buffer
oxRequire(dstSize, dst.size());
oxOutf("new size: {} bytes\n", dstSize);
buff.resize(dstSize);
dstBuff.resize(dstSize);
oxReturnError(writeFileBuff(argDst, buff));
return OxError(0);
oxRequireM(romBuff, readFileBuff(argRomBin.c_str()));
oxReturnError(appendBinary(&romBuff, &dstBuff, pl.get()));
oxOutf("new size: {} bytes\n", dstSize);
oxOutf("preload buff size: {} bytes\n", pl->buff().size());
oxOutf("ROM buff size: {} bytes\n", romBuff.size());
oxReturnError(writeFileBuff(argRomBin, romBuff));
return {};
}
int main(int argc, const char **args) {

View File

@ -7,6 +7,7 @@ add_library(
target_link_libraries(
NostalgiaPack PUBLIC
NostalgiaCore-Headless
OxPreloader
)
install(

View File

@ -4,11 +4,11 @@
#include <ox/claw/read.hpp>
#include <ox/fs/fs.hpp>
#include <ox/mc/write.hpp>
#include <ox/model/descwrite.hpp>
#include <ox/model/modelvalue.hpp>
#include <nostalgia/core/gfx.hpp>
#include <nostalgia/core/media.hpp>
#include <nostalgia/core/typeconv.hpp>
#include <nostalgia/core/typestore.hpp>
@ -16,6 +16,8 @@
namespace nostalgia {
using Preloader = ox::ModelHandlerInterface<GbaPreloader>;
static ox::Error pathToInode(ox::FileSystem *dest, ox::ModelObject *obj) noexcept {
auto &o = *obj;
auto type = static_cast<ox::FileAddressType>(o["type"].get<int8_t>());
@ -30,7 +32,7 @@ static ox::Error pathToInode(ox::FileSystem *dest, ox::ModelObject *obj) noexcep
break;
case ox::FileAddressType::Inode:
case ox::FileAddressType::None:
return OxError(0);
return {};
}
oxRequire(s, dest->stat(path.c_str()));
oxReturnError(o["type"].set(static_cast<int8_t>(ox::FileAddressType::Inode)));
@ -41,7 +43,6 @@ static ox::Error pathToInode(ox::FileSystem *dest, ox::ModelObject *obj) noexcep
* Convert path references in Claw data to inodes to save space
* @param buff buffer holding file
* @return error
* stub for now
*/
static ox::Error transformObj(ox::FileSystem *dest, ox::ModelObject *obj) noexcept {
for (auto &f : *obj) {
@ -56,10 +57,10 @@ static ox::Error transformObj(ox::FileSystem *dest, ox::ModelObject *obj) noexce
oxReturnError(transformObj(dest, &o));
}
}
return OxError(0);
return {};
}
static ox::Error doTransformations(core::TypeStore *ts, ox::FileSystem *dest, const ox::String &filePath) noexcept {
static ox::Error doTransformations(core::TypeStore *ts, ox::FileSystem *dest, ox::CRString filePath) noexcept {
if (filePath.endsWith(".ng") || filePath.endsWith(".npal")) {
// load file
oxRequire(s, dest->stat(filePath.c_str()));
@ -70,16 +71,16 @@ static ox::Error doTransformations(core::TypeStore *ts, ox::FileSystem *dest, co
oxRequireM(obj, ox::readClaw(ts, buff));
// do transformations
oxReturnError(transformObj(dest, &obj));
oxReturnError(ox::writeMC(&obj).moveTo(&buff));
oxReturnError(ox::writeClaw(&obj).moveTo(&buff));
// write file to dest
oxReturnError(dest->write(s.inode, buff.data(), buff.size()));
}
return OxError(0);
return {};
}
// claw file transformations are broken out because path to inode
// transformations need to be done after the copy to the new FS is complete
static ox::Error transformClaw(core::TypeStore *ts, ox::FileSystem *dest, const ox::String &path) noexcept {
static ox::Error transformClaw(core::TypeStore *ts, ox::FileSystem *dest, ox::CRString path) noexcept {
// copy
oxTracef("pack::transformClaw", "path: {}", path);
oxRequire(fileList, dest->ls(path));
@ -93,10 +94,10 @@ static ox::Error transformClaw(core::TypeStore *ts, ox::FileSystem *dest, const
oxReturnError(doTransformations(ts, dest, filePath));
}
}
return OxError(0);
return {};
}
static ox::Error verifyFile(ox::FileSystem *fs, const ox::String &path, const ox::Buffer &expected) noexcept {
static ox::Error verifyFile(ox::FileSystem *fs, ox::CRString path, const ox::Buffer &expected) noexcept {
ox::Buffer buff(expected.size());
oxReturnError(fs->read(path.c_str(), buff.data(), buff.size()));
return OxError(buff == expected ? 0 : 1);
@ -105,19 +106,19 @@ static ox::Error verifyFile(ox::FileSystem *fs, const ox::String &path, const ox
struct VerificationPair {
ox::String path;
ox::Buffer buff;
VerificationPair(const ox::String &pPath, ox::Buffer pBuff) noexcept:
path(pPath),
buff(std::move(pBuff)) {
VerificationPair(ox::String &&pPath, ox::Buffer &&pBuff) noexcept:
path(std::forward<ox::String>(pPath)),
buff(std::forward<ox::Buffer>(pBuff)) {
}
};
static ox::Error copy(ox::FileSystem *src, ox::FileSystem *dest, const ox::String &path) noexcept {
static ox::Error copy(ox::FileSystem *src, ox::FileSystem *dest, ox::CRString path) noexcept {
oxOutf("copying directory: {}\n", path);
ox::Vector<VerificationPair> verificationPairs;
// copy
oxRequire(fileList, src->ls(path));
for (const auto &name : fileList) {
const auto currentFile = path + name;
auto currentFile = ox::sfmt("{}{}", path, name);
if (currentFile == "/.nostalgia") {
continue;
}
@ -133,22 +134,84 @@ static ox::Error copy(ox::FileSystem *src, ox::FileSystem *dest, const ox::Strin
oxOutf("writing {}\n", currentFile);
oxReturnError(dest->write(currentFile.c_str(), buff.data(), buff.size()));
oxReturnError(verifyFile(dest, currentFile, buff));
verificationPairs.emplace_back(currentFile, std::move(buff));
verificationPairs.emplace_back(std::move(currentFile), std::move(buff));
}
}
// verify all at once in addition to right after the files are written
for (const auto &v : verificationPairs) {
oxReturnError(verifyFile(dest, v.path, v.buff));
}
return OxError(0);
return {};
}
ox::Error pack(ox::FileSystem *src, ox::FileSystem *dest) noexcept {
// transformations need to be done after the copy to the new FS is complete
static ox::Error preloadObj(core::TypeStore *ts, ox::FileSystem *romFs, Preloader *pl, ox::CRString path) noexcept {
// load file
oxRequireM(buff, romFs->read(path.c_str()));
oxRequireM(obj, ox::readClaw(ts, buff));
if (obj.type()->preloadable) {
// preload
oxReturnError(model(pl, &obj));
const core::PreloadPtr p{.preloadAddr = 0};
oxReturnError(ox::writeMC(&p).moveTo(&buff));
} else {
// strip the Claw header (it is not needed after preloading) and write back out to dest fs
oxReturnError(ox::writeMC(&obj).moveTo(&buff));
}
oxReturnError(romFs->write(path.c_str(), buff.data(), buff.size()));
return {};
}
// claw file transformations are broken out because path to inode
// transformations need to be done after the copy to the new FS is complete
static ox::Error preload(core::TypeStore *ts, ox::FileSystem *romFs, Preloader *pl, ox::CRString path) noexcept {
// copy
oxTracef("pack::preload", "path: {}", path);
oxRequire(fileList, romFs->ls(path));
for (const auto &name : fileList) {
const auto filePath = path + name;
oxRequire(stat, romFs->stat(filePath.c_str()));
if (stat.fileType == ox::FileType::Directory) {
const auto dir = path + name + '/';
oxReturnError(preload(ts, romFs, pl, dir));
} else {
oxReturnError(preloadObj(ts, romFs, pl, filePath));
}
}
return {};
}
static ox::Error padbin(ox::BufferWriter *w, unsigned factor) noexcept {
return w->write(nullptr, factor - w->data()->size() % factor);
}
ox::Error appendBinary(ox::Buffer *binBuff, ox::Buffer *fsBuff, GbaPreloader *pl) noexcept {
constexpr ox::StringView mediaHdr = "NOSTALGIA_MEDIA_HEADER__________";
constexpr ox::StringView preloadHdr = "NOSTALGIA_PRELOAD_HEADER________";
constexpr auto hdrSize = 32;
static_assert(mediaHdr.bytes() == hdrSize);
static_assert(preloadHdr.bytes() == hdrSize);
ox::BufferWriter w(binBuff);
oxReturnError(padbin(&w, hdrSize));
oxReturnError(w.write(mediaHdr.data(), mediaHdr.bytes()));
oxReturnError(w.write(fsBuff->data(), fsBuff->size()));
oxReturnError(padbin(&w, hdrSize));
oxReturnError(w.write(preloadHdr.data(), preloadHdr.bytes()));
const auto &plBuff = pl->buff();
oxReturnError(pl->offsetPtrs(binBuff->size()));
oxReturnError(w.write(plBuff.data(), plBuff.size()));
return {};
}
ox::Error pack(core::TypeStore *ts, ox::FileSystem *src, ox::FileSystem *dest) noexcept {
oxReturnError(copy(src, dest, "/"));
core::TypeStore ts(src);
oxReturnError(ox::buildTypeDef<core::CompactTileSheet>(&ts));
oxReturnError(transformClaw(&ts, dest, "/"));
return OxError(0);
oxReturnError(ox::buildTypeDef<core::CompactTileSheet>(ts));
oxReturnError(transformClaw(ts, dest, "/"));
return {};
}
ox::Error preload(core::TypeStore *ts, ox::FileSystem *src, GbaPreloader *pl) noexcept {
return preload(ts, src, pl->interface(), "/");
}
}

View File

@ -2,8 +2,20 @@
* Copyright 2016 - 2022 Gary Talent (gary@drinkingtea.net). All rights reserved.
*/
#include <ox/preloader/preloader.hpp>
namespace nostalgia {
typename ox::Error pack(class ox::FileSystem *src, class ox::FileSystem *dest) noexcept;
namespace core {
class TypeStore;
}
using GbaPreloader = ox::Preloader<ox::GbaPlatSpec>;
ox::Error appendBinary(ox::Buffer *binBuff, ox::Buffer *fsBuff, GbaPreloader *pl) noexcept;
auto pack(core::TypeStore *ts, ox::FileSystem *src, ox::FileSystem *dest) noexcept -> ox::Error;
auto preload(core::TypeStore *ts, ox::FileSystem *src, GbaPreloader *ph) noexcept -> ox::Error;
}