summaryrefslogtreecommitdiff
path: root/src/factories/bk64/DialogFactory.cpp
blob: cd359db893d080f33005162547dde49dcb2a5a2e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
#include "DialogFactory.h"

#include "BKDialogShared.h"
#include "BKEmitText.h"

#include "Companion.h"
#include "spdlog/spdlog.h"
#include "types/RawBuffer.h"
#include "utils/Decompressor.h"
#include "utils/TorchUtils.h"

#define DIALOG_HEADER_1 0x01
#define DIALOG_HEADER_2 0x03
#define DIALOG_HEADER_3 0x00
#define DIALOG_CMD_CLOSE 0x04
#define DIALOG_TERMINATOR_SIZE 3

namespace BK64 {

static void WriteLangBlock(LUS::BinaryWriter& writer, const std::vector<DialogString>& bottom,
                           const std::vector<DialogString>& top) {
    WriteDialogStrings(writer, bottom);
    WriteDialogStrings(writer, top);
}

static void EmitLangBlock(YAML::Emitter& out, const std::vector<DialogString>& bottom,
                          const std::vector<DialogString>& top) {
    out << YAML::Key << "Bottom";
    out << YAML::Value;
    EmitDialogStringSeq(out, bottom);
    out << YAML::Key << "Top";
    out << YAML::Value;
    EmitDialogStringSeq(out, top);
}

ExportResult DialogCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName,
                                        YAML::Node& node, std::string* replacement) {
    auto offset = GetSafeNode<uint32_t>(node, "offset");
    auto dialog = std::static_pointer_cast<DialogData>(raw);
    const auto symbol = GetSafeNode(node, "symbol", entryName);

    write << "u8 " << symbol << "[] = {\n";

    write << fourSpaceTab << "DIALOG_HEADER_1"
          << ", "
          << "DIALOG_HEADER_2"
          << ", "
          << "DIALOG_HEADER_3"
          << ",\n";
    write << fourSpaceTab << "/* Bottom Dialog */\n";
    WriteDialogStringArray(write, dialog->mBottom);
    write << fourSpaceTab << "/* Top Dialog */\n";
    WriteDialogStringArray(write, dialog->mTop);

    write << "};\n\n";

    return offset;
}

ExportResult BK64::DialogBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw,
                                                std::string& entryName, YAML::Node& node, std::string* replacement) {
    auto writer = LUS::BinaryWriter();
    const auto dialog = std::static_pointer_cast<DialogData>(raw);

    WriteHeader(writer, Torch::ResourceType::BKDialog, 0);

    // 1 for US/JP, 3 for PAL (EN + FR + DE)
    uint32_t langCount = 1 + static_cast<uint32_t>(dialog->mExtraLangs.size());
    writer.Write(langCount);

    // English always goes first
    WriteLangBlock(writer, dialog->mBottom, dialog->mTop);

    // PAL only: French then German
    for (const auto& lang : dialog->mExtraLangs) {
        WriteLangBlock(writer, lang.bottom, lang.top);
    }

    writer.Finish(write);
    return std::nullopt;
}

ExportResult BK64::DialogModdingExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw,
                                                 std::string& entryName, YAML::Node& node, std::string* replacement) {
    const auto dialog = std::static_pointer_cast<DialogData>(raw);
    const auto symbol = GetSafeNode(node, "symbol", entryName);

    *replacement += ".yaml";

    YAML::Emitter out;
    out << YAML::BeginMap;
    out << YAML::Key << symbol;
    out << YAML::Value;
    out.SetIndent(2);

    out << YAML::BeginMap;
    EmitLangBlock(out, dialog->mBottom, dialog->mTop);

    for (size_t i = 0; i < dialog->mExtraLangs.size() && i < std::size(kPalExtraLangs); i++) {
        out << YAML::Key << kPalExtraLangs[i];
        out << YAML::Value;
        out << YAML::BeginMap;
        EmitLangBlock(out, dialog->mExtraLangs[i].bottom, dialog->mExtraLangs[i].top);
        out << YAML::EndMap;
    }

    out << YAML::EndMap;
    out << YAML::EndMap;

    write.write(out.c_str(), out.size());

    return std::nullopt;
}

// Give empty dialogs the terminator the game expects
static void EnsureTerminator(std::vector<DialogString>& box) {
    if (box.empty()) {
        box.push_back({ DIALOG_CMD_CLOSE, std::string(1, '\0') });
    }
}

// Read one box's entries. A count byte the blob can't back would otherwise walk the reader off the
// end, and whatever memory follows gets baked into the o2r as dialog text. Returns false once the
// blob is exhausted so the caller stops rather than parsing the rest from nothing.
static bool ReadEntries(LUS::BinaryReader& reader, uint8_t count, std::vector<DialogString>& box,
                        const std::string& symbol, const char* boxName) {
    for (uint8_t i = 0; i < count; i++) {
        // cmd + length, then the string itself
        if (!HasBytes(reader, 2)) {
            SPDLOG_WARN("[BK64] Dialog {}: {} entry {} of {} runs past the end of the blob; dropping the rest.", symbol,
                        boxName, i + 1, count);
            return false;
        }

        DialogString dialogString;
        dialogString.cmd = reader.ReadUByte();
        auto strLen = reader.ReadUByte();

        if (!HasBytes(reader, strLen)) {
            SPDLOG_WARN("[BK64] Dialog {}: {} entry {} of {} claims {} bytes the blob doesn't hold; dropping the rest.",
                        symbol, boxName, i + 1, count, strLen);
            return false;
        }

        dialogString.str = reader.ReadString(strLen);
        box.push_back(dialogString);
    }
    return true;
}

// One language: bottom box strings, then top box strings.
static DialogLang ParseLangBlock(LUS::BinaryReader& reader, const std::string& symbol) {
    DialogLang lang;

    uint8_t bottomSize = 0;
    bool bottomComplete = false;

    if (HasBytes(reader, 1)) {
        bottomSize = reader.ReadUByte();
        bottomComplete = ReadEntries(reader, bottomSize, lang.bottom, symbol, "bottom");
    } else {
        SPDLOG_WARN("[BK64] Dialog {}: blob ends before the bottom box count.", symbol);
    }

    // Banjo's Backpack still writes the bottom box's terminator entry after a zero count. Consume
    // it or it gets read as topSize (0x04), inventing four junk top entries and running off the
    // blob; EnsureTerminator puts the entry back below. A real top box can't open with these bytes.
    if (bottomComplete && bottomSize == 0 && HasBytes(reader, DIALOG_TERMINATOR_SIZE)) {
        const uint32_t savedPos = reader.GetBaseAddress();
        const uint8_t b0 = reader.ReadUByte();
        const uint8_t b1 = reader.ReadUByte();
        const uint8_t b2 = reader.ReadUByte();
        if (b0 != DIALOG_CMD_CLOSE || b1 != 0x01 || b2 != 0x00) {
            reader.Seek(savedPos, LUS::SeekOffsetType::Start);
        }
    }

    // A truncated bottom means every offset past it is guesswork, so don't invent a top from it.
    if (bottomComplete && HasBytes(reader, 1)) {
        const uint8_t topSize = reader.ReadUByte();
        ReadEntries(reader, topSize, lang.top, symbol, "top");
    }

    EnsureTerminator(lang.bottom);
    EnsureTerminator(lang.top);

    return lang;
}

std::optional<std::shared_ptr<IParsedData>> DialogFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) {
    auto [_, segment] = Decompressor::AutoDecode(node, buffer);
    LUS::BinaryReader reader(segment.data, segment.size);
    reader.SetEndianness(Torch::Endianness::Big);
    const auto symbol = GetSafeNode<std::string>(node, "symbol");

    auto header1 = reader.ReadInt8();
    auto header2 = reader.ReadInt8();
    auto header3 = reader.ReadInt8();

    if (header1 == DIALOG_HEADER_1 && header2 == DIALOG_HEADER_2 && header3 == DIALOG_HEADER_3) {
        // US/JP: 01 03 00, dialog data follows immediately
        auto lang = ParseLangBlock(reader, symbol);
        return std::make_shared<DialogData>(std::move(lang.bottom), std::move(lang.top));
    }

    if (header1 == 0x03 && header2 == 0x07 && header3 == 0x00) {
        // PAL: 03 07 00, then two LE u16 offsets (French, German), then the
        // EN/FR/DE blocks.
        uint16_t frenchOffset = reader.ReadUByte() | (reader.ReadUByte() << 8);
        uint16_t germanOffset = reader.ReadUByte() | (reader.ReadUByte() << 8);

        // EN sits right here at byte 7; FR and DE we seek to.
        auto english = ParseLangBlock(reader, symbol);

        reader.Seek(frenchOffset, LUS::SeekOffsetType::Start);
        auto french = ParseLangBlock(reader, symbol);

        reader.Seek(germanOffset, LUS::SeekOffsetType::Start);
        auto german = ParseLangBlock(reader, symbol);

        std::vector<DialogLang> extraLangs;
        extraLangs.push_back(std::move(french));
        extraLangs.push_back(std::move(german));

        return std::make_shared<DialogData>(std::move(english.bottom), std::move(english.top), std::move(extraLangs));
    }

    SPDLOG_ERROR("Invalid Header For BK64 Dialog {}: {:02X} {:02X} {:02X}", symbol, header1, header2, header3);
    return std::nullopt;
}

std::optional<std::shared_ptr<IParsedData>> DialogFactory::parse_modding(std::vector<uint8_t>& buffer,
                                                                         YAML::Node& node) {
    const auto symbol = GetSafeNode<std::string>(node, "symbol");
    const YAML::Node info = YamlEntry(buffer, symbol);

    const auto readLang = [](const YAML::Node& lang) {
        DialogLang out{ ReadModdingDialogSeq(lang["Bottom"]), ReadModdingDialogSeq(lang["Top"]) };
        EnsureTerminator(out.bottom);
        EnsureTerminator(out.top);
        return out;
    };

    auto english = readLang(info);
    std::vector<DialogLang> extraLangs;
    for (const auto& lang : ReadPalExtraLangs(info, symbol, "Dialog")) {
        extraLangs.push_back(readLang(lang));
    }

    return std::make_shared<DialogData>(std::move(english.bottom), std::move(english.top), std::move(extraLangs));
}

} // namespace BK64