-
Notifications
You must be signed in to change notification settings - Fork 1
/
vera_tilemap.cpp
107 lines (85 loc) · 2.56 KB
/
vera_tilemap.cpp
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
#include "vera_tilemap.h"
#include <iostream>
#include <fstream>
#include <cstdint>
#include "tilemap.h"
using namespace std;
void VeraTilemap::writeFile(const std::string &filename, const std::string &layername, const int &disable_paloffset, const int &use_header) const
{
Layer *layer = tilemap->Layers()[std::string(layername)];
if(!layer)
{
throw VeraTilemapFileException("Could not find layer");
}
ofstream file;
file.open(filename, ios::out | ios::binary);
uint32_t width = layer->Width();
uint32_t height = layer->Height();
if(width != 32 && width != 64 && width != 64 && width != 128 && width != 256)
{
throw VeraTilemapFileException( "Vera maps must be 32/64/128/256 tiles wide");
}
if(height != 32 && height != 64 && height != 64 && height != 128 && height != 256) {
throw VeraTilemapFileException( "Vera maps must be 32/64/128/256 tiles high");
}
if(use_header) {
// write out 2 byte header
file << (uint8_t)0 << (uint8_t)0;
}
for (uint32_t y = 0; y < height; ++y) {
for (uint32_t x = 0; x < width; ++x) {
const int index = (y * width) + x;
const uint32_t rawTile = layer->Data()[index];
uint32_t firstgid = 1;
uint32_t prev_firstgid = 1;
uint8_t paloffset = 0;
// determine firstgid
for(auto tileset : tilemap->Tilesets())
{
// mask off the upper byte which contains flags like hflip and vflip
if((rawTile & 0x00FFFFFF) >= tileset->FirstGid() &&
tileset->FirstGid() > firstgid)
{
// capture just the lower 24 bits to exclude flags
prev_firstgid = firstgid;
firstgid = (tileset->FirstGid()) & 0x00FFFFFF;
}
}
if(!disable_paloffset && firstgid - prev_firstgid > 0)
{
paloffset = (rawTile & 0x00FFFFFF) / (firstgid - prev_firstgid);
// account for the last tile in the row, which will get bumped
// to the next palette
if((rawTile & 0x00FFFFFF) % (firstgid - prev_firstgid) == 0)
{
paloffset--;
}
}
// make 0 based
uint16_t tileId = rawTile - firstgid;
// no tile
if(rawTile == 0)
{
file << (uint8_t)0;
file << (uint8_t)0;
continue;
}
// first byte: tile index (0:7)
file << (uint8_t) tileId;
// start off by putting bits 9:8 of the index in the lower two bits
uint8_t secondByte = tileId >> 8 | paloffset << 4;
// OR a 1 into bit 2 if flipped horizontally
if((rawTile & HFLIP_FLAG) == HFLIP_FLAG)
{
secondByte |= 0b00000100;
}
// OR a 1 into bit 3 if flipped vertically
if((rawTile & VFLIP_FLAG) == VFLIP_FLAG)
{
secondByte |= 0b00001000;
}
file << secondByte;
}
}
file.close();
}