summaryrefslogtreecommitdiff
path: root/src/factories/bk64/QuizQuestionFactory.cpp
blob: 0020e6b340c2eba83326564815169b5464800f99 (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
#include "QuizQuestionFactory.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 QUIZ_QUESTION_HEADER_1 0x01
#define QUIZ_QUESTION_HEADER_2 0x01
#define QUIZ_QUESTION_HEADER_3 0x02
#define QUIZ_QUESTION_HEADER_4 0x05
#define QUIZ_QUESTION_HEADER_5 0x00

namespace BK64 {

namespace {

constexpr int8_t kUsHeader[3] = { QUIZ_QUESTION_HEADER_1, QUIZ_QUESTION_HEADER_2, QUIZ_QUESTION_HEADER_3 };
constexpr int8_t kPalHeader[3] = { 0x03, 0x01, 0x02 };

// One language's quiz data. Same layout for every language. The last three entries are
// the answer options; their first two bytes are a fixed control pair the game expects,
// so they stay part of the string.
QuizQuestionLang ParseQuizBlock(LUS::BinaryReader& reader, const std::string& symbol) {
    const int textSize = reader.ReadUByte();
    auto text = ReadDialogStrings(reader, textSize - kQuestionOptionCount, symbol, "QuizQuestion");
    auto options = ReadDialogStrings(reader, textSize >= kQuestionOptionCount ? kQuestionOptionCount : 0, symbol,
                                     "QuizQuestion option");
    return { std::move(text), std::move(options) };
}

void WriteQuizLangBlock(LUS::BinaryWriter& writer, const std::vector<DialogString>& text,
                        const std::vector<DialogString>& options) {
    WriteDialogStrings(writer, text);
    WriteDialogStrings(writer, options);
}

void EmitQuizLang(YAML::Emitter& out, const std::vector<DialogString>& text, const std::vector<DialogString>& options) {
    out << YAML::Key << "Text";
    out << YAML::Value;
    EmitDialogStringSeq(out, text);

    out << YAML::Key << "Options";
    out << YAML::Value;

    // Options expose their leading control pair as separate fields so a pack can
    // edit the text without touching them. PAL's options have no pair.
    out << YAML::BeginSeq;
    for (const auto& [cmd, str] : options) {
        out << YAML::Flow;
        out << YAML::BeginSeq;
        out << YAML_HEX((uint32_t)cmd);
        if (str.size() >= 2 && static_cast<uint8_t>(str[0]) == 0xFD) {
            out << YAML_HEX((uint32_t)static_cast<uint8_t>(str[0]));
            out << YAML_HEX((uint32_t)static_cast<uint8_t>(str[1]));
            EmitText(out, str.substr(2));
        } else {
            EmitText(out, str);
        }
        out << YAML::EndSeq;
    }
    out << YAML::EndSeq;
}

QuizQuestionLang ReadQuizLang(const YAML::Node& lang) {
    auto text = ReadModdingDialogSeq(lang["Text"]);

    std::vector<DialogString> options;
    auto optionsNode = lang["Options"];
    for (YAML::iterator it = optionsNode.begin(); it != optionsNode.end(); ++it) {
        if (options.size() >= 3) {
            SPDLOG_WARN("BK64 QuizQuestion: Only 3 Options Allowed; extra options ignored");
            break;
        }
        if ((*it).size() != 4 && (*it).size() != 2) {
            throw std::runtime_error(
                "BK64 QuizQuestion: option must be [cmd, 0xfd, 0x6c, \"text\"] or [cmd, \"text\"]");
        }
        DialogString optionString;
        optionString.cmd = (*it)[0].as<uint32_t>();
        if ((*it).size() == 4) {
            optionString.str.push_back(static_cast<char>((*it)[1].as<uint32_t>()));
            optionString.str.push_back(static_cast<char>((*it)[2].as<uint32_t>()));
        }
        optionString.str += DecodeText((*it)[(*it).size() - 1].as<std::string>());
        optionString.str += '\0';
        options.push_back(optionString);
    }

    if (options.size() != 3) {
        throw std::runtime_error("BK64 QuizQuestion: Requires Exactly 3 Options");
    }

    return { std::move(text), std::move(options) };
}

} // namespace

ExportResult QuizQuestionCodeExporter::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 quizQuestion = std::static_pointer_cast<QuizQuestionData>(raw);
    const auto symbol = GetSafeNode(node, "symbol", entryName);

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

    write << fourSpaceTab << "QUIZ_QUESTION_HEADER_1"
          << ", "
          << "QUIZ_QUESTION_HEADER_2"
          << ", "
          << "QUIZ_QUESTION_HEADER_3"
          << ", "
          << "QUIZ_QUESTION_HEADER_4"
          << ", "
          << "QUIZ_QUESTION_HEADER_5"
          << ",\n";
    write << fourSpaceTab << "/* QuizQuestion */\n";
    WriteDialogStringArray(write, quizQuestion->mText);
    write << fourSpaceTab << "/* Options */\n";
    WriteDialogStringArray(write, quizQuestion->mOptions);

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

    return offset;
}

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

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

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

    // English always goes first
    WriteQuizLangBlock(writer, quizQuestion->mText, quizQuestion->mOptions);

    // PAL only: French then German
    for (const auto& lang : quizQuestion->mExtraLangs) {
        WriteQuizLangBlock(writer, lang.text, lang.options);
    }

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

ExportResult BK64::QuizQuestionModdingExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw,
                                                       std::string& entryName, YAML::Node& node,
                                                       std::string* replacement) {
    const auto quizQuestion = std::static_pointer_cast<QuizQuestionData>(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;
    EmitQuizLang(out, quizQuestion->mText, quizQuestion->mOptions);

    for (size_t i = 0; i < quizQuestion->mExtraLangs.size() && i < std::size(kPalExtraLangs); i++) {
        out << YAML::Key << kPalExtraLangs[i];
        out << YAML::Value;
        out << YAML::BeginMap;
        EmitQuizLang(out, quizQuestion->mExtraLangs[i].text, quizQuestion->mExtraLangs[i].options);
        out << YAML::EndMap;
    }

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

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

    return std::nullopt;
}

std::optional<std::shared_ptr<IParsedData>> QuizQuestionFactory::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");

    const auto extraOffsets = SeekQuestionBlock(reader, symbol, "QuizQuestion", kUsHeader, kPalHeader);
    if (!extraOffsets.has_value()) {
        return std::nullopt;
    }

    auto english = ParseQuizBlock(reader, symbol);

    std::vector<QuizQuestionLang> extraLangs;
    for (const uint16_t offset : *extraOffsets) {
        reader.Seek(offset, LUS::SeekOffsetType::Start);
        extraLangs.push_back(ParseQuizBlock(reader, symbol));
    }

    return std::make_shared<QuizQuestionData>(std::move(english.text), std::move(english.options),
                                              std::move(extraLangs));
}

std::optional<std::shared_ptr<IParsedData>> QuizQuestionFactory::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);

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

    return std::make_shared<QuizQuestionData>(std::move(english.text), std::move(english.options),
                                              std::move(extraLangs));
}

} // namespace BK64