| 1 | // Aseprite Document Library |
| 2 | // Copyright (C) 2019-2020 Igara Studio S.A. |
| 3 | // |
| 4 | // This file is released under the terms of the MIT license. |
| 5 | // Read LICENSE.txt for more information. |
| 6 | |
| 7 | #ifdef HAVE_CONFIG_H |
| 8 | #include "config.h" |
| 9 | #endif |
| 10 | |
| 11 | #include "doc/tileset_io.h" |
| 12 | |
| 13 | #include "base/serialization.h" |
| 14 | #include "doc/cancel_io.h" |
| 15 | #include "doc/grid_io.h" |
| 16 | #include "doc/image_io.h" |
| 17 | #include "doc/subobjects_io.h" |
| 18 | #include "doc/tileset.h" |
| 19 | #include "doc/util.h" |
| 20 | |
| 21 | #include <iostream> |
| 22 | |
| 23 | // Extra BYTE with special flags to check the tileset version. This |
| 24 | // field didn't exist in Aseprite v1.3-alpha3 (so read8() fails = 0) |
| 25 | #define TILESET_VER1 1 |
| 26 | |
| 27 | namespace doc { |
| 28 | |
| 29 | using namespace base::serialization; |
| 30 | using namespace base::serialization::little_endian; |
| 31 | |
| 32 | bool write_tileset(std::ostream& os, |
| 33 | const Tileset* tileset, |
| 34 | CancelIO* cancel) |
| 35 | { |
| 36 | write32(os, tileset->id()); |
| 37 | write32(os, tileset->size()); |
| 38 | write_grid(os, tileset->grid()); |
| 39 | |
| 40 | for (tile_index ti=0; ti<tileset->size(); ++ti) { |
| 41 | if (cancel && cancel->isCanceled()) |
| 42 | return false; |
| 43 | |
| 44 | write_image(os, tileset->get(ti).get(), cancel); |
| 45 | } |
| 46 | |
| 47 | write8(os, TILESET_VER1); |
| 48 | return true; |
| 49 | } |
| 50 | |
| 51 | Tileset* read_tileset(std::istream& is, |
| 52 | Sprite* sprite, |
| 53 | bool setId, |
| 54 | bool* isOldVersion) |
| 55 | { |
| 56 | ObjectId id = read32(is); |
| 57 | tileset_index ntiles = read32(is); |
| 58 | Grid grid = read_grid(is, setId); |
| 59 | auto tileset = new Tileset(sprite, grid, ntiles); |
| 60 | if (setId) |
| 61 | tileset->setId(id); |
| 62 | |
| 63 | for (tileset_index ti=0; ti<ntiles; ++ti) { |
| 64 | ImageRef image(read_image(is, setId)); |
| 65 | tileset->set(ti, image); |
| 66 | } |
| 67 | |
| 68 | // Read extra version byte after tiles |
| 69 | uint32_t ver = read8(is); |
| 70 | if (ver == TILESET_VER1) { |
| 71 | if (isOldVersion) |
| 72 | *isOldVersion = false; |
| 73 | |
| 74 | tileset->setBaseIndex(1); |
| 75 | } |
| 76 | // Old tileset used in internal versions (this was added to recover |
| 77 | // old files, maybe in a future we could remove this code) |
| 78 | else { |
| 79 | if (isOldVersion) |
| 80 | *isOldVersion = true; |
| 81 | |
| 82 | fix_old_tileset(tileset); |
| 83 | } |
| 84 | |
| 85 | return tileset; |
| 86 | } |
| 87 | |
| 88 | } |
| 89 | |