17#include "absl/status/status.h"
18#include "absl/status/statusor.h"
19#include "absl/strings/str_cat.h"
20#include "absl/strings/str_format.h"
21#include "absl/strings/string_view.h"
43 rom_data.erase(rom_data.begin(), rom_data.begin() +
kHeaderSize);
74 uint32_t ptr2, uint32_t ptr3) {
80 std::vector<uint8_t> sheet;
81 const uint8_t sheets[] = {0x71, 0x72, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE};
82 for (
const auto &sheet_id : sheets) {
90 for (
const auto &each_pixel : converted_sheet) {
91 sheet.push_back(each_pixel);
99 const uint32_t kLinkGfxOffset = 0x80000;
100 const uint16_t kLinkGfxLength = 0x800;
101 std::array<gfx::Bitmap, kNumLinkSheets> link_graphics;
104 auto link_sheet_data,
114 return link_graphics;
118 std::vector<uint8_t> data(0x2000);
119 for (
int i = 0; i < 0x2000; i++) {
120 data[i] = rom.
data()[0x70000 + i];
123 std::vector<uint8_t> new_data(0x4000);
124 std::vector<uint8_t> mask = {0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01};
125 int sheet_position = 0;
128 for (
int s = 0; s < 4; s++) {
129 for (
int j = 0; j < 4; j++) {
130 for (
int i = 0; i < 16; i++) {
131 for (
int y = 0; y < 8; y++) {
133 data[(y * 2) + (i * 16) + (j * 256) + sheet_position];
135 data[(y * 2) + (i * 16) + (j * 256) + 1 + sheet_position];
137 for (
int x = 0; x < 4; x++) {
139 uint8_t pixdata2 = 0;
141 if ((line_bits0 & mask[(x * 2)]) == mask[(x * 2)]) {
144 if ((line_bits1 & mask[(x * 2)]) == mask[(x * 2)]) {
148 if ((line_bits0 & mask[(x * 2) + 1]) == mask[(x * 2) + 1]) {
151 if ((line_bits1 & mask[(x * 2) + 1]) == mask[(x * 2) + 1]) {
155 new_data[(y * 64) + (x) + (i * 4) + (j * 512) + (s * 2048)] =
156 (uint8_t)((pixdata << 4) | pixdata2);
162 sheet_position += 0x400;
165 std::vector<uint8_t> fontgfx16_data(0x4000);
166 for (
int i = 0; i < 0x4000; i++) {
167 fontgfx16_data[i] = new_data[i];
171 font_gfx.
Create(128, 128, 64, fontgfx16_data);
176 Rom &rom,
bool defer_render) {
177 std::array<gfx::Bitmap, kNumGfxSheets> graphics_sheets;
178 std::vector<uint8_t> sheet;
186 if (i >= 115 && i <= 126) {
195 }
else if (i == 113 || i == 114 || i >= 218) {
220 if (palette_group.size() > 0) {
221 default_palette = palette_group[0];
223 }
else if (i < 128) {
226 if (palette_group.size() > 0) {
227 default_palette = palette_group[0];
232 if (palette_group.size() > 0) {
233 default_palette = palette_group.palette(0);
238 if (!default_palette.
empty()) {
239 graphics_sheets[i].SetPalette(default_palette);
243 for (
int j = 0; j < graphics_sheets[i].size(); ++j) {
248 for (
int j = 0; j < graphics_sheets[0].size(); ++j) {
253 return graphics_sheets;
257 Rom &rom, std::array<gfx::Bitmap, kNumGfxSheets> &gfx_sheets) {
259 if (gfx_sheets[i].is_active()) {
261 std::vector<uint8_t> final_data;
262 bool compressed =
true;
263 if (i >= 115 && i <= 126) {
265 }
else if (i == 113 || i == 114 || i >= 218) {
270 std::cout <<
"Sheet ID " << i <<
" BPP: " << to_bpp << std::endl;
271 auto sheet_data = gfx_sheets[i].vector();
272 std::cout <<
"Sheet data size: " << sheet_data.size() << std::endl;
277 final_data.data(), final_data.size(), &size, 1);
278 for (
int j = 0; j < size; j++) {
279 sheet_data[j] = compressed_data[j];
286 std::copy(final_data.begin(), final_data.end(), rom.
begin() + offset);
289 return absl::OkStatus();
301 return absl::InvalidArgumentError(
302 "Could not load ROM: parameter `filename` is empty.");
306 if (!std::filesystem::exists(
filename)) {
307 return absl::NotFoundError(
308 absl::StrCat(
"ROM file does not exist: ",
filename));
314 std::ifstream file(
filename_, std::ios::binary);
315 if (!file.is_open()) {
316 return absl::NotFoundError(
317 absl::StrCat(
"Could not open ROM file: ",
filename_));
326 return absl::InvalidArgumentError(
327 absl::StrFormat(
"ROM file too small (%zu bytes), minimum is 32KB",
size_));
329 if (
size_ > 8 * 1024 * 1024) {
330 return absl::InvalidArgumentError(
331 absl::StrFormat(
"ROM file too large (%zu bytes), maximum is 8MB",
size_));
333 }
catch (
const std::filesystem::filesystem_error &
e) {
335 file.seekg(0, std::ios::end);
337 return absl::InternalError(absl::StrCat(
338 "Could not get file size: ",
filename_,
" - ",
e.what()));
340 size_ = file.tellg();
344 return absl::InvalidArgumentError(
345 absl::StrFormat(
"Invalid ROM size: %zu bytes",
size_));
352 file.seekg(0, std::ios::beg);
356 return absl::InternalError(
357 absl::StrFormat(
"Failed to read ROM data, read %zu of %zu bytes",
358 file.gcount(),
size_));
360 }
catch (
const std::bad_alloc&
e) {
361 return absl::ResourceExhaustedError(
362 absl::StrFormat(
"Failed to allocate memory for ROM (%zu bytes)",
size_));
378 absl::StrFormat(
"%s.labels",
filename));
381 return absl::OkStatus();
393 return absl::InvalidArgumentError(
394 "Could not load ROM: parameter `data` is empty.");
408 return absl::OkStatus();
417 return absl::FailedPreconditionError(
"ROM data is empty");
434 return absl::OutOfRangeError(
435 "ROM image is too small to contain title metadata.");
463 if (
rom_data_.size() < kBaseRomSize * 2) {
470 return absl::OkStatus();
478 for (
int j = 0;
j < 8;
j++) {
484 for (
int j = 0;
j < 4;
j++) {
490 for (
int j = 0;
j < 4;
j++) {
497 for (
int j = 0;
j < 4;
j++) {
503 return absl::OkStatus();
511 for (
int j = 0;
j < 8;
j++) {
517 for (
int j = 0;
j < 4;
j++) {
523 for (
int j = 0;
j < 4;
j++) {
530 for (
int j = 0;
j < 4;
j++) {
536 return absl::OkStatus();
542 return absl::InternalError(
"ROM data is empty.");
557 auto now = std::chrono::system_clock::now();
558 auto now_c = std::chrono::system_clock::to_time_t(
now);
573 std::filesystem::copy_options::overwrite_existing);
574 }
catch (
const std::filesystem::filesystem_error &
e) {
591 auto now = std::chrono::system_clock::now();
592 auto now_c = std::chrono::system_clock::to_time_t(
now);
608 std::ofstream file(
filename.data(), std::ios::binary | std::ios::trunc);
610 return absl::InternalError(
611 absl::StrCat(
"Could not open ROM file for writing: ",
filename));
617 static_cast<const char *
>(
static_cast<const void *
>(
rom_data_.data())),
619 }
catch (
const std::ofstream::failure &
e) {
620 return absl::InternalError(absl::StrCat(
621 "Error while writing to ROM file: ",
filename,
" - ",
e.what()));
626 return absl::InternalError(
627 absl::StrCat(
"Error while writing to ROM file: ",
filename));
636 for (
size_t j = 0;
j < palette.
size(); ++
j) {
645 return absl::OkStatus();
651 for (size_t i = 0; i < group.size(); ++i) {
653 SavePalette(i, group.name(), *group.mutable_palette(i)));
655 return absl::OkStatus();
658 return absl::OkStatus();
661absl::StatusOr<uint8_t> Rom::ReadByte(
int offset) {
662 if (offset >=
static_cast<int>(rom_data_.size())) {
663 return absl::FailedPreconditionError(
"Offset out of range");
665 return rom_data_[offset];
668absl::StatusOr<uint16_t> Rom::ReadWord(
int offset) {
669 if (offset + 1 >=
static_cast<int>(rom_data_.size())) {
670 return absl::FailedPreconditionError(
"Offset out of range");
672 auto result = (uint16_t)(rom_data_[offset] | (rom_data_[offset + 1] << 8));
676absl::StatusOr<uint32_t> Rom::ReadLong(
int offset) {
677 if (offset + 2 >=
static_cast<int>(rom_data_.size())) {
678 return absl::OutOfRangeError(
"Offset out of range");
680 auto result = (uint32_t)(rom_data_[offset] | (rom_data_[offset + 1] << 8) |
681 (rom_data_[offset + 2] << 16));
685absl::StatusOr<std::vector<uint8_t>> Rom::ReadByteVector(
686 uint32_t offset, uint32_t length)
const {
687 if (offset + length >
static_cast<uint32_t
>(rom_data_.size())) {
688 return absl::OutOfRangeError(
"Offset and length out of range");
690 std::vector<uint8_t> result;
691 for (uint32_t i = offset; i < offset + length; i++) {
692 result.push_back(rom_data_[i]);
697absl::StatusOr<gfx::Tile16> Rom::ReadTile16(uint32_t tile16_id) {
702 tile16.tile0_ = gfx::WordToTileInfo(new_tile0);
705 tile16.tile1_ = gfx::WordToTileInfo(new_tile1);
708 tile16.tile2_ = gfx::WordToTileInfo(new_tile2);
711 tile16.tile3_ = gfx::WordToTileInfo(new_tile3);
715absl::Status Rom::WriteTile16(
int tile16_id,
const gfx::Tile16 &tile) {
725 return absl::OkStatus();
728absl::Status Rom::WriteByte(
int addr, uint8_t value) {
729 if (addr >=
static_cast<int>(rom_data_.size())) {
730 return absl::OutOfRangeError(absl::StrFormat(
731 "Attempt to write byte %#02x value failed, address %d out of range",
734 rom_data_[addr] = value;
735 LOG_DEBUG(
"Rom",
"WriteByte: %#06X: %s", addr, util::HexByte(value).data());
737 return absl::OkStatus();
740absl::Status Rom::WriteWord(
int addr, uint16_t value) {
741 if (addr + 1 >=
static_cast<int>(rom_data_.size())) {
742 return absl::OutOfRangeError(absl::StrFormat(
743 "Attempt to write word %#04x value failed, address %d out of range",
746 rom_data_[addr] = (uint8_t)(value & 0xFF);
747 rom_data_[addr + 1] = (uint8_t)((value >> 8) & 0xFF);
748 LOG_DEBUG(
"Rom",
"WriteWord: %#06X: %s", addr, util::HexWord(value).data());
750 return absl::OkStatus();
753absl::Status Rom::WriteShort(
int addr, uint16_t value) {
754 if (addr + 1 >=
static_cast<int>(rom_data_.size())) {
755 return absl::OutOfRangeError(absl::StrFormat(
756 "Attempt to write short %#04x value failed, address %d out of range",
759 rom_data_[addr] = (uint8_t)(value & 0xFF);
760 rom_data_[addr + 1] = (uint8_t)((value >> 8) & 0xFF);
761 LOG_DEBUG(
"Rom",
"WriteShort: %#06X: %s", addr, util::HexWord(value).data());
763 return absl::OkStatus();
766absl::Status Rom::WriteLong(uint32_t addr, uint32_t value) {
767 if (addr + 2 >=
static_cast<uint32_t
>(rom_data_.size())) {
768 return absl::OutOfRangeError(absl::StrFormat(
769 "Attempt to write long %#06x value failed, address %d out of range",
772 rom_data_[addr] = (uint8_t)(value & 0xFF);
773 rom_data_[addr + 1] = (uint8_t)((value >> 8) & 0xFF);
774 rom_data_[addr + 2] = (uint8_t)((value >> 16) & 0xFF);
775 LOG_DEBUG(
"Rom",
"WriteLong: %#06X: %s", addr, util::HexLong(value).data());
777 return absl::OkStatus();
780absl::Status Rom::WriteVector(
int addr, std::vector<uint8_t> data) {
781 if (addr +
static_cast<int>(data.size()) >
782 static_cast<int>(rom_data_.size())) {
783 return absl::InvalidArgumentError(absl::StrFormat(
784 "Attempt to write vector value failed, address %d out of range", addr));
786 for (
int i = 0; i < static_cast<int>(data.size()); i++) {
787 rom_data_[addr + i] = data[i];
789 LOG_DEBUG(
"Rom",
"WriteVector: %#06X: %s", addr,
790 util::HexByte(data[0]).data());
792 return absl::OkStatus();
796 uint16_t bgr = ((color.
snes() >> 10) & 0x1F) | ((color.
snes() & 0x1F) << 10) |
797 (color.
snes() & 0x7C00);
800 LOG_DEBUG(
"Rom",
"WriteColor: %#06X: %s", address, util::HexWord(bgr).data());
801 auto st = WriteShort(address, bgr);
The Rom class is used to load, save, and modify Rom data.
absl::StatusOr< std::vector< uint8_t > > ReadByteVector(uint32_t offset, uint32_t length) const
absl::Status LoadFromFile(const std::string &filename, bool z3_load=true)
auto mutable_graphics_buffer()
std::vector< uint8_t > rom_data_
gfx::PaletteGroupMap palette_groups_
auto palette_group() const
absl::Status WriteColor(uint32_t address, const gfx::SnesColor &color)
absl::Status LoadFromData(const std::vector< uint8_t > &data, bool z3_load=true)
absl::Status LoadZelda3()
std::array< std::array< uint8_t, 4 >, kNumSpritesets > spriteset_ids
std::array< std::array< uint8_t, 4 >, kNumPalettesets > paletteset_ids
absl::StatusOr< uint16_t > ReadWord(int offset)
absl::Status SaveToFile(const SaveSettings &settings)
std::array< std::array< uint8_t, 4 >, kNumRoomBlocksets > room_blockset_ids
zelda3_version_pointers version_constants() const
absl::Status SaveGfxGroups()
absl::Status LoadGfxGroups()
absl::Status SavePalette(int index, const std::string &group_name, gfx::SnesPalette &palette)
project::ResourceLabelManager resource_label_manager_
std::array< std::array< uint8_t, 8 >, kNumMainBlocksets > main_blockset_ids
absl::Status SaveAllPalettes()
Represents a bitmap image optimized for SNES ROM hacking.
void Create(int width, int height, int depth, std::span< uint8_t > data)
Create a bitmap with the given dimensions and data.
constexpr void set_modified(bool m)
constexpr bool is_modified() const
constexpr uint16_t snes() const
Get SNES 15-bit color.
Represents a palette of colors for the Super Nintendo Entertainment System (SNES).
Tile composition of four 8x8 tiles.
#define LOG_DEBUG(category, format,...)
#define RETURN_IF_ERROR(expression)
#define ASSIGN_OR_RETURN(type_variable_name, expression)
void MaybeStripSmcHeader(std::vector< uint8_t > &rom_data, unsigned long &size)
constexpr size_t kHeaderSize
constexpr size_t kBaseRomSize
absl::StatusOr< std::vector< uint8_t > > DecompressV2(const uint8_t *data, int offset, int size, int mode)
Decompresses a buffer of data using the LC_LZ2 algorithm.
constexpr int kTilesheetHeight
constexpr int kTilesheetWidth
constexpr int kTilesheetDepth
std::vector< uint8_t > Bpp8SnesToIndexed(std::vector< uint8_t > data, uint64_t bpp)
std::vector< uint8_t > SnesTo8bppSheet(std::span< uint8_t > sheet, int bpp, int num_sheets)
uint32_t GetPaletteAddress(const std::string &group_name, size_t palette_index, size_t color_index)
std::vector< uint8_t > HyruleMagicCompress(uint8_t const *const src, int const oldsize, int *const size, int const flag)
absl::Status LoadAllPalettes(const std::vector< uint8_t > &rom_data, PaletteGroupMap &groups)
Loads all the palettes for the game.
Main namespace for the application.
constexpr uint32_t kGfxGroupsPointer
absl::StatusOr< std::vector< uint8_t > > Load2BppGraphics(const Rom &rom)
Loads 2bpp graphics from Rom data.
absl::StatusOr< std::array< gfx::Bitmap, kNumLinkSheets > > LoadLinkGraphics(const Rom &rom)
Loads the players 4bpp graphics sheet from Rom data.
constexpr int Uncompressed3BPPSize
constexpr uint32_t kNumLinkSheets
constexpr uint32_t kEntranceGfxGroup
constexpr uint32_t kNumSpritesets
int AddressFromBytes(uint8_t bank, uint8_t high, uint8_t low) noexcept
constexpr uint32_t kTile16Ptr
constexpr uint32_t kNumMainBlocksets
constexpr uint32_t kNumRoomBlocksets
absl::StatusOr< gfx::Bitmap > LoadFontGraphics(const Rom &rom)
constexpr uint32_t kNumGfxSheets
absl::StatusOr< std::array< gfx::Bitmap, kNumGfxSheets > > LoadAllGraphicsData(Rom &rom, bool defer_render)
This function iterates over all graphics sheets in the Rom and loads them into memory....
uint32_t GetGraphicsAddress(const uint8_t *data, uint8_t addr, uint32_t ptr1, uint32_t ptr2, uint32_t ptr3)
constexpr uint32_t kNumPalettesets
absl::Status SaveAllGraphicsData(Rom &rom, std::array< gfx::Bitmap, kNumGfxSheets > &gfx_sheets)
uint32_t SnesToPc(uint32_t addr) noexcept
static RomLoadOptions AppDefaults()
bool expand_to_full_image
static RomLoadOptions CliDefaults()
static RomLoadOptions RawDataOnly()
bool load_resource_labels
absl::Status for_each(Func &&func)
Represents a group of palettes.
bool LoadLabels(const std::string &filename)
uint32_t kOverworldGfxPtr1
uint32_t kOverworldGfxPtr2
uint32_t kSpriteBlocksetPointer
uint32_t kOverworldGfxPtr3
uint32_t kDungeonPalettesGroups
The Legend of Zelda: A Link to the Past - Data Structures and Constants.