summaryrefslogtreecommitdiffstats
path: root/src/BlockTypePalette.cpp
blob: 7759505cfadb8ad3cf6ecaf51c270ea73165c103 (plain) (blame)
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
#include "Globals.h"
#include "BlockTypePalette.h"
#include "json/value.h"
#include "JsonUtils.h"





/** Returns the index into aString >= aStartIdx at which the next separator occurs.
Separator is one of \t, \n or \r.
Returns AString::npos if no such separator. */
static size_t findNextSeparator(const AString & aString, size_t aStartIdx = 0)
{
	for (size_t i = aStartIdx, len = aString.length(); i < len; ++i)
	{
		switch (aString[i])
		{
			case '\t':
			case '\n':
			case '\r':
			{
				return i;
			}
		}
	}
	return AString::npos;
}





BlockTypePalette::BlockTypePalette():
	mMaxIndex(0)
{
}





UInt32 BlockTypePalette::index(const AString & aBlockTypeName, const BlockState & aBlockState)
{
	auto idx = maybeIndex(aBlockTypeName, aBlockState);
	if (idx.second)
	{
		return idx.first;
	}

	// Not found, append:
	auto index = mMaxIndex++;
	mBlockToNumber[aBlockTypeName][aBlockState] = index;
	mNumberToBlock[index] = {aBlockTypeName, aBlockState};
	return index;
}





std::pair<UInt32, bool> BlockTypePalette::maybeIndex(const AString & aBlockTypeName, const BlockState & aBlockState) const
{
	auto itr1 = mBlockToNumber.find(aBlockTypeName);
	if (itr1 == mBlockToNumber.end())
	{
		return {0, false};
	}
	auto itr2 = itr1->second.find(aBlockState);
	if (itr2 == itr1->second.end())
	{
		return {0, false};
	}
	return {itr2->second, true};
}





UInt32 BlockTypePalette::count() const
{
	return static_cast<UInt32>(mNumberToBlock.size());
}





const std::pair<AString, BlockState> & BlockTypePalette::entry(UInt32 aIndex) const
{
	auto itr = mNumberToBlock.find(aIndex);
	if (itr == mNumberToBlock.end())
	{
		throw NoSuchIndexException(aIndex);
	}
	return itr->second;
}





std::map<UInt32, UInt32> BlockTypePalette::createTransformMapAddMissing(const BlockTypePalette & aFrom)
{
	std::map<UInt32, UInt32> res;
	for (const auto & fromEntry: aFrom.mNumberToBlock)
	{
		auto fromIndex = fromEntry.first;
		const auto & blockTypeName = fromEntry.second.first;
		const auto & blockState = fromEntry.second.second;
		res[fromIndex] = index(blockTypeName, blockState);
	}
	return res;
}





std::map<UInt32, UInt32> BlockTypePalette::createTransformMapWithFallback(const BlockTypePalette & aFrom, UInt32 aFallbackIndex) const
{
	std::map<UInt32, UInt32> res;
	for (const auto & fromEntry: aFrom.mNumberToBlock)
	{
		auto fromIndex = fromEntry.first;
		const auto & blockTypeName = fromEntry.second.first;
		const auto & blockState = fromEntry.second.second;
		auto thisIndex = maybeIndex(blockTypeName, blockState);
		if (thisIndex.second)
		{
			// The entry was found in this
			res[fromIndex] = thisIndex.first;
		}
		else
		{
			// The entry was NOT found in this, replace with fallback:
			res[fromIndex] = aFallbackIndex;
		}
	}
	return res;
}





void BlockTypePalette::loadFromString(const AString & aString)
{
	static const AString hdrTsvRegular = "BlockTypePalette";
	static const AString hdrTsvUpgrade = "UpgradeBlockTypePalette";

	// Detect format by checking the header line (none -> JSON):
	if (aString.substr(0, hdrTsvRegular.length()) == hdrTsvRegular)
	{
		return loadFromTsv(aString, false);
	}
	else if (aString.substr(0, hdrTsvUpgrade.length()) == hdrTsvUpgrade)
	{
		return loadFromTsv(aString, true);
	}
	return loadFromJsonString(aString);
}





void BlockTypePalette::loadFromJsonString(const AString & aJsonPalette)
{
	// Parse the string into JSON object:
	Json::Value root;
	std::string errs;
	if (!JsonUtils::ParseString(aJsonPalette, root, &errs))
	{
		throw LoadFailedException(errs);
	}

	// Sanity-check the JSON's structure:
	if (!root.isObject())
	{
		throw LoadFailedException("Incorrect palette format, expected an object at root.");
	}

	// Load the palette:
	for (auto itr = root.begin(), end = root.end(); itr != end; ++itr)
	{
		const auto & blockTypeName = itr.name();
		const auto & states = (*itr)["states"];
		if (states == Json::Value())
		{
			throw LoadFailedException(Printf("Missing \"states\" for block type \"%s\"", blockTypeName));
		}
		for (const auto & state: states)
		{
			auto id = static_cast<UInt32>(std::stoul(state["id"].asString()));
			std::map<AString, AString> props;
			if (state.isMember("properties"))
			{
				const auto & properties = state["properties"];
				if (!properties.isObject())
				{
					throw LoadFailedException(Printf("Member \"properties\" is not a JSON object (block type \"%s\", id %u).", blockTypeName, id));
				}
				for (const auto & key: properties.getMemberNames())
				{
					props[key] = properties[key].asString();
				}
			}
			addMapping(id, blockTypeName, props);
		}
	}
}





void BlockTypePalette::loadFromTsv(const AString & aTsvPalette, bool aIsUpgrade)
{
	static const AString hdrTsvRegular = "BlockTypePalette";
	static const AString hdrTsvUpgrade = "UpgradeBlockTypePalette";

	// Check the file signature:
	auto idx = findNextSeparator(aTsvPalette);
	if ((idx == AString::npos) || (aTsvPalette[idx] == '\t'))
	{
		throw LoadFailedException("Invalid signature");
	}
	auto signature = aTsvPalette.substr(0, idx);
	bool isUpgrade = (signature == hdrTsvUpgrade);
	if (!isUpgrade && (signature != hdrTsvRegular))
	{
		throw LoadFailedException("Unknown signature");
	}
	if (aTsvPalette[idx] == '\r')   // CR of the CRLF pair, skip the LF:
	{
		idx += 1;
	}

	// Parse the header:
	bool hasHadVersion = false;
	AString commonPrefix;
	int line = 2;
	auto len = aTsvPalette.length();
	while (true)
	{
		auto keyStart = idx + 1;
		auto keyEnd = findNextSeparator(aTsvPalette, idx + 1);
		if (keyEnd == AString::npos)
		{
			throw LoadFailedException(Printf("Invalid header key format on line %u", line));
		}
		if (keyEnd == idx + 1)  // Empty line, end of headers
		{
			if (aTsvPalette[keyEnd] == '\r')  // CR of the CRLF pair, skip the LF:
			{
				++keyEnd;
			}
			idx = keyEnd;
			++line;
			break;
		}
		auto valueEnd = findNextSeparator(aTsvPalette, keyEnd + 1);
		if ((valueEnd == AString::npos) || (aTsvPalette[valueEnd] == '\t'))
		{
			throw LoadFailedException(Printf("Invalid header value format on line %u", line));
		}
		auto key = aTsvPalette.substr(keyStart, keyEnd - keyStart);
		if (key == "FileVersion")
		{
			unsigned version = 0;
			auto value = aTsvPalette.substr(keyEnd + 1, valueEnd - keyEnd - 1);
			if (!StringToInteger(value, version))
			{
				throw LoadFailedException("Invalid FileVersion value");
			}
			else if (version != 1)
			{
				throw LoadFailedException(Printf("Unknown FileVersion: %u. Only version 1 is supported.", version));
			}
			hasHadVersion = true;
		}
		else if (key == "CommonPrefix")
		{
			commonPrefix = aTsvPalette.substr(keyEnd + 1, valueEnd - keyEnd - 1);
		}
		idx = valueEnd;
		if (aTsvPalette[idx] == '\r')  // CR of the CRLF pair, skip the LF:
		{
			++idx;
		}
		++line;
	}
	if (!hasHadVersion)
	{
		throw LoadFailedException("No FileVersion value");
	}

	// Parse the data:
	while (idx + 1 < len)
	{
		auto lineStart = idx + 1;
		auto idEnd = findNextSeparator(aTsvPalette, lineStart);
		if ((idEnd == AString::npos) || (aTsvPalette[idEnd] != '\t'))
		{
			throw LoadFailedException(Printf("Incomplete data on line %u (id)", line));
		}
		UInt32 id;
		if (!StringToInteger(aTsvPalette.substr(lineStart, idEnd - lineStart), id))
		{
			throw LoadFailedException(Printf("Failed to parse id on line %u", line));
		}
		size_t metaEnd = idEnd;
		if (isUpgrade)
		{
			metaEnd = findNextSeparator(aTsvPalette, idEnd + 1);
			if ((metaEnd == AString::npos) || (aTsvPalette[metaEnd] != '\t'))
			{
				throw LoadFailedException(Printf("Incomplete data on line %u (meta)", line));
			}
			UInt32 meta = 0;
			if (!StringToInteger(aTsvPalette.substr(idEnd + 1, metaEnd - idEnd - 1), meta))
			{
				throw LoadFailedException(Printf("Failed to parse meta on line %u", line));
			}
			if (meta > 15)
			{
				throw LoadFailedException(Printf("Invalid meta value on line %u: %u", line, meta));
			}
			id = (id * 16) | meta;
		}
		auto blockTypeEnd = findNextSeparator(aTsvPalette, metaEnd + 1);
		if (blockTypeEnd == AString::npos)
		{
			throw LoadFailedException(Printf("Incomplete data on line %u (blockTypeName)", line));
		}
		auto blockTypeName = aTsvPalette.substr(metaEnd + 1, blockTypeEnd - metaEnd - 1);
		auto blockStateEnd = blockTypeEnd;
		AStringMap blockState;
		while (aTsvPalette[blockStateEnd] == '\t')
		{
			auto keyEnd = findNextSeparator(aTsvPalette, blockStateEnd + 1);
			if ((keyEnd == AString::npos) || (aTsvPalette[keyEnd] != '\t'))
			{
				throw LoadFailedException(Printf("Incomplete data on line %u (blockState key)", line));
			}
			auto valueEnd = findNextSeparator(aTsvPalette, keyEnd + 1);
			if (valueEnd == AString::npos)
			{
				throw LoadFailedException(Printf("Incomplete data on line %u (blockState value)", line));
			}
			auto key = aTsvPalette.substr(blockStateEnd + 1, keyEnd - blockStateEnd - 1);
			auto value = aTsvPalette.substr(keyEnd + 1, valueEnd - keyEnd - 1);
			blockState[key] = value;
			blockStateEnd = valueEnd;
		}
		addMapping(id, commonPrefix + blockTypeName, std::move(blockState));
		++line;
		if (aTsvPalette[blockStateEnd] == '\r')  // CR of the CRLF pair, skip the LF:
		{
			++blockStateEnd;
		}
		idx = blockStateEnd;
	}
}





void BlockTypePalette::addMapping(UInt32 aID, const AString & aBlockTypeName, const BlockState & aBlockState)
{
	mNumberToBlock[aID] = {aBlockTypeName, aBlockState};
	mBlockToNumber[aBlockTypeName][aBlockState] = aID;
	if (aID > mMaxIndex)
	{
		mMaxIndex = aID;
	}
}