载入中...
搜索中...
未找到
TileConfig.cpp
浏览该文件的文档.
1#include "map/TileConfig.h"
3
4#include "common/Json.h"
5#include "common/Module.h"
6#include "common/Xml.h"
7#include "data/DataModule.h"
11#include "graphics/Graphics.h"
12
13#include <algorithm>
14#include <array>
15#include <cmath>
16#include <cstdint>
17#include <filesystem>
18#include <fstream>
19#include <memory>
20#include <optional>
21#include <sstream>
22#include <stdexcept>
23
24namespace eve::map {
25namespace {
26
27using Json = eve::json::Value;
28
29uint32_t asUInt32(const Json &v, uint32_t fallback) {
30 if (!v) return fallback;
31 if (v.isInt64()) return uint32_t(uint64_t(v.asInt64(0)) & 0xffffffffu);
32 const double d = v.asDouble(static_cast<double>(fallback));
33 if (!std::isfinite(d) || d < 0.0 || d > 4294967295.0) return fallback;
34 return uint32_t(d);
35}
36
37bool readVec2(const Json &o, const char *key, float &a, float &b) {
38 if (!o || !o.has(key)) return false;
39 const Json arr = o.get(key);
40 if (!arr.isArray() || arr.size() < 2) return false;
41 a = arr.at(0).asFloat(a);
42 b = arr.at(1).asFloat(b);
43 return true;
44}
45
46bool readVec4(const Json &o, const char *key, float &a, float &b, float &c, float &d) {
47 if (!o || !o.has(key)) return false;
48 const Json arr = o.get(key);
49 if (!arr.isArray() || arr.size() < 4) return false;
50 a = arr.at(0).asFloat(a);
51 b = arr.at(1).asFloat(b);
52 c = arr.at(2).asFloat(c);
53 d = arr.at(3).asFloat(d);
54 return true;
55}
56
57int64_t fileModtime(const std::string &path) {
58 auto *fs = eve::ModuleManager::getInstance<eve::filesystem::Filesystem>("Filesystem");
59 if (!fs) fs = eve::filesystem::Filesystem::create();
61 if (!fs->getInfo(path, info)) return -1;
62 return info.modtime;
63}
64
65graphics::Texture *tryLoadTexture(const std::string &path) {
66 if (path.empty()) return nullptr;
67 auto *gfx = eve::ModuleManager::getInstance<eve::graphics::Graphics>("Graphics");
68 if (!gfx) return nullptr;
69 try {
70 graphics::Texture *tex = gfx->newTextureFromFile(path);
71 if (auto *hot = eve::ModuleManager::getInstance<eve::filesystem::HotReload>("HotReload"))
72 hot->bind(path, "texture");
73 return tex;
74 } catch (...) {
75 return nullptr;
76 }
77}
78
79struct TilesetInfo {
80 std::string image;
81 std::string sourcePath;
82 int firstGid = 1;
83 int columns = 1;
84 int tileW = 32;
85 int tileH = 32;
86 int margin = 0;
87 int spacing = 0;
88 std::vector<TileLayer::Tileset::Visual> visuals;
89 std::vector<TileLayer::Tileset::Animation> animations;
90 std::vector<TileLayer::Tileset::TerrainRule> terrainRules;
91 std::vector<TileLayer::Tileset::CustomData> customData;
92};
93
94TileLayer::Tileset::Visual readTileVisual(const Json &o, int fallbackGid) {
95 TileLayer::Tileset::Visual visual;
96 if (!o || !o.isObject()) return visual;
97 visual.gid = o.has("gid") ? o.getInt("gid", fallbackGid) : fallbackGid;
98 float x = 0.f, y = 0.f, w = 0.f, h = 0.f;
99 if (readVec4(o, "region", x, y, w, h)) {
100 visual.x = int(x);
101 visual.y = int(y);
102 visual.width = int(w);
103 visual.height = int(h);
104 }
105 readVec2(o, "pivot", visual.pivotX, visual.pivotY);
106 visual.sortBias = o.has("sortBias") ? o.getFloat("sortBias", 0.f) : 0.f;
107 float fw = 1.f, fh = 1.f;
108 if (readVec2(o, "footprint", fw, fh)) {
109 visual.footprintW = std::max(1, int(fw));
110 visual.footprintH = std::max(1, int(fh));
111 }
112 visual.walkable = o.has("walkable") ? o.getBool("walkable", true) : true;
113 visual.cost = o.has("cost") ? std::max(0.001f, o.getFloat("cost", 1.f)) : 1.f;
114 if (o.has("properties")) {
115 const Json properties = o.get("properties");
116 for (size_t index = 0; properties.isArray() && index < properties.size(); ++index) {
117 const Json property = properties.at(index);
118 if (!property.isObject() || !property.has("name") || !property.has("value")) continue;
119 const std::string name = property.getString("name");
120 if (name == "walkable")
121 visual.walkable = property.get("value").asBool(true);
122 else if (name == "cost")
123 visual.cost = std::max(0.001f, property.get("value").asFloat(1.f));
124 else if (name == "enterMask")
125 visual.enterMask = uint8_t(property.get("value").asInt(0xff) & 0xff);
126 else if (name == "exitMask")
127 visual.exitMask = uint8_t(property.get("value").asInt(0xff) & 0xff);
128 else if (name == "opaque")
129 visual.opaque = property.get("value").asBool(false);
130 else if (name == "semanticFlags")
131 visual.semanticFlags = uint32_t(property.get("value").asInt(0));
132 }
133 }
134 if (o.has("objectgroup")) {
135 const Json group = o.get("objectgroup");
136 const Json objects = group.isObject() ? group.get("objects") : Json{};
137 for (size_t index = 0; objects.isArray() && index < objects.size(); ++index) {
138 const Json object = objects.at(index);
139 if (!object.isObject()) continue;
140 float ox = object.has("x") ? object.getFloat("x", 0.f) : 0.f;
141 float oy = object.has("y") ? object.getFloat("y", 0.f) : 0.f;
142 float width = object.has("width") ? object.getFloat("width", 0.f) : 0.f;
143 float height = object.has("height") ? object.getFloat("height", 0.f) : 0.f;
144 if (object.has("polygon")) {
145 const Json polygon = object.get("polygon");
146 float minX = 0.f, minY = 0.f, maxX = 0.f, maxY = 0.f;
147 for (size_t pointIndex = 0; polygon.isArray() && pointIndex < polygon.size(); ++pointIndex) {
148 const Json point = polygon.at(pointIndex);
149 if (!point.isObject()) continue;
150 const float px = point.getFloat("x", 0.f);
151 const float py = point.getFloat("y", 0.f);
152 minX = std::min(minX, px);
153 minY = std::min(minY, py);
154 maxX = std::max(maxX, px);
155 maxY = std::max(maxY, py);
156 }
157 ox += minX;
158 oy += minY;
159 width = maxX - minX;
160 height = maxY - minY;
161 }
162 if (width > 0.f && height > 0.f) visual.collisionShapes.push_back({ox, oy, width, height});
163 }
164 if (!visual.collisionShapes.empty()) visual.walkable = false;
165 }
166 return visual;
167}
168
169TilesetInfo readTilesetObject(const Json &o, std::optional<int> firstGid = std::nullopt) {
170 TilesetInfo info;
171 if (!o || !o.isObject()) return info;
172 if (o.has("image"))
173 info.image = o.getString("image");
174 else if (o.has("texture"))
175 info.image = o.getString("texture");
176 if (o.has("firstgid"))
177 info.firstGid = o.getInt("firstgid", 1);
178 else if (o.has("firstGid"))
179 info.firstGid = o.getInt("firstGid", 1);
180 if (firstGid) info.firstGid = *firstGid;
181 if (o.has("columns")) info.columns = o.getInt("columns", 1);
182 if (o.has("tilewidth"))
183 info.tileW = o.getInt("tilewidth", 32);
184 else if (o.has("tileWidth"))
185 info.tileW = o.getInt("tileWidth", 32);
186 if (o.has("tileheight"))
187 info.tileH = o.getInt("tileheight", 32);
188 else if (o.has("tileHeight"))
189 info.tileH = o.getInt("tileHeight", 32);
190 if (o.has("margin")) info.margin = o.getInt("margin", 0);
191 if (o.has("spacing")) info.spacing = o.getInt("spacing", 0);
192 if (info.columns <= 0 && o.has("imagewidth") && info.tileW > 0) {
193 const int iw = o.getInt("imagewidth", 0);
194 if (iw > 0) info.columns = std::max(1, (iw - info.margin) / (info.tileW + info.spacing));
195 }
196 if (o.has("tiles")) {
197 const Json arr = o.get("tiles");
198 for (size_t i = 0; arr.isArray() && i < arr.size(); ++i) {
199 const Json tile = arr.at(i);
200 const int localId = tile.isObject() && tile.has("id") ? tile.getInt("id", int(i)) : int(i);
201 const int gid = tile.isObject() && tile.has("gid") ? tile.getInt("gid", info.firstGid + localId)
202 : info.firstGid + localId;
203 auto visual = readTileVisual(tile, gid);
204 if (visual.gid > 0) info.visuals.push_back(visual);
205 if (!tile.isObject()) continue;
206 if (tile.has("animation")) {
207 const Json frames = tile.get("animation");
208 TileLayer::Tileset::Animation animation;
209 animation.gid = gid;
210 for (size_t frameIndex = 0; frames.isArray() && frameIndex < frames.size(); ++frameIndex) {
211 const Json frame = frames.at(frameIndex);
212 if (!frame.isObject()) continue;
213 const int frameLocal = frame.getInt("tileid", localId);
214 const int duration = frame.has("duration") ? frame.getInt("duration", 100) : 100;
215 animation.frames.push_back({info.firstGid + frameLocal, std::max(1, duration)});
216 }
217 if (!animation.frames.empty()) info.animations.push_back(std::move(animation));
218 }
219 if (tile.has("terrain") && tile.has("neighborMask")) {
220 info.terrainRules.push_back(
221 {gid, tile.getInt("terrain", 0), tile.getInt("neighborMask", 0) & 0xff});
222 }
223 if (tile.has("properties")) {
224 const Json properties = tile.get("properties");
225 for (size_t propertyIndex = 0; properties.isArray() && propertyIndex < properties.size();
226 ++propertyIndex) {
227 const Json property = properties.at(propertyIndex);
228 if (!property.isObject() || !property.has("name") || !property.has("value")) continue;
229 const std::string type = property.has("type") ? property.getString("type") : "string";
230 info.customData.push_back(
231 {gid, property.getString("name"), type, property.get("value").asString()});
232 }
233 }
234 }
235 }
236 if (o.has("wangsets")) {
237 const Json sets = o.get("wangsets");
238 for (size_t setIndex = 0; sets.isArray() && setIndex < sets.size(); ++setIndex) {
239 const Json set = sets.at(setIndex);
240 if (!set.isObject() || !set.has("wangtiles")) continue;
241 const Json wangTiles = set.get("wangtiles");
242 for (size_t tileIndex = 0; wangTiles.isArray() && tileIndex < wangTiles.size(); ++tileIndex) {
243 const Json wangTile = wangTiles.at(tileIndex);
244 if (!wangTile.isObject() || !wangTile.has("tileid") || !wangTile.has("wangid")) continue;
245 const Json wangId = wangTile.get("wangid");
246 if (!wangId.isArray() || wangId.size() != 8) continue;
247 const int gid = info.firstGid + wangTile.getInt("tileid", 0);
248 // Tiled orders Wang positions N, NE, E, SE, S, SW, W, NW.
249 // EVEngine terrain masks order NW, N, NE, E, SE, S, SW, W.
250 constexpr int tiledToTerrainBit[8] = {1, 2, 3, 4, 5, 6, 7, 0};
251 for (int color = 1; color <= 255; ++color) {
252 int mask = 0;
253 bool present = false;
254 for (int position = 0; position < 8; ++position) {
255 if (wangId.at(size_t(position)).asInt(0) != color) continue;
256 present = true;
257 mask |= 1 << tiledToTerrainBit[position];
258 }
259 if (present) info.terrainRules.push_back({gid, int(setIndex) * 256 + color, mask});
260 }
261 }
262 }
263 }
264 return info;
265}
266
267std::string resolveAssetPath(const std::string &ownerPath, const std::string &referencedPath) {
268 if (ownerPath.empty() || referencedPath.empty()) return referencedPath;
269 const std::filesystem::path reference(referencedPath);
270 if (reference.is_absolute()) return reference.lexically_normal().generic_string();
271 return (std::filesystem::path(ownerPath).parent_path() / reference).lexically_normal().generic_string();
272}
273
274bool readImportText(eve::filesystem::Filesystem *fs, const std::string &path, std::string &text) {
275 if (fs) {
276 try {
277 std::unique_ptr<eve::filesystem::FileData> bytes(fs->read(path));
278 if (bytes && bytes->getSize() > 0) {
279 text.assign(static_cast<const char *>(bytes->getData()), bytes->getSize());
280 return true;
281 }
282 } catch (...) {
283 }
284 }
285 std::ifstream input(std::filesystem::path(path), std::ios::binary);
286 if (!input) return false;
287 std::ostringstream stream;
288 stream << input.rdbuf();
289 text = stream.str();
290 return !text.empty();
291}
292
293eve::json::Document readJsonDocument(eve::filesystem::Filesystem *fs, const std::string &path, std::string *error) {
294 if (!fs) {
295 if (error) *error = "map.import.filesystem-unavailable: " + path;
296 return {};
297 }
298 std::string text;
299 if (!readImportText(fs, path, text)) {
300 if (error) *error = "map.import.external-tileset-empty: " + path;
301 return {};
302 }
303 std::string decodeError;
304 auto document = eve::json::Document::parse(text, &decodeError);
305 if (!document.valid() || !document.root().isObject()) {
306 if (error)
307 *error = "map.import.external-tileset-invalid-json: " + path +
308 (decodeError.empty() ? std::string{} : " (" + decodeError + ")");
309 return {};
310 }
311 return document;
312}
313
314TilesetInfo readTsxTileset(eve::filesystem::Filesystem *fs, const std::string &path, int firstGid,
315 std::string *error) {
316 TilesetInfo info;
317 info.firstGid = firstGid;
318 std::string text;
319 if (!readImportText(fs, path, text)) {
320 if (error) *error = "map.import.external-tileset-empty: " + path;
321 return info;
322 }
323 std::string parseError;
324 auto document = eve::xml::Document::parse(text, &parseError);
325 auto root = document.root();
326 if (!document.valid() || !root || root.tagName() != "tileset") {
327 if (error)
328 *error = "map.import.external-tsx-invalid: " + path +
329 (parseError.empty() ? " (root is not tileset)" : " (" + parseError + ")");
330 return {};
331 }
332 info.columns = root.getIntAttribute("columns", 1);
333 info.tileW = root.getIntAttribute("tilewidth", 32);
334 info.tileH = root.getIntAttribute("tileheight", 32);
335 info.margin = root.getIntAttribute("margin", 0);
336 info.spacing = root.getIntAttribute("spacing", 0);
337 const auto images = root.elementsByTag("image");
338 if (!images.empty()) info.image = resolveAssetPath(path, images.front().getAttribute("source"));
339 const auto tiles = root.children("tile");
340 for (size_t index = 0; index < tiles.size(); ++index) {
341 const auto &tile = tiles[index];
342 TileLayer::Tileset::Visual visual;
343 const int localId = tile.getIntAttribute("id", int(index));
344 visual.gid = firstGid + localId;
345 for (const auto &property : tile.elementsByTag("property")) {
346 const std::string name = property.getAttribute("name");
347 const std::string type = property.getAttribute("type");
348 const std::string value = property.getAttribute("value");
349 info.customData.push_back({visual.gid, name, type.empty() ? "string" : type, value});
350 if (name == "walkable")
351 visual.walkable = value != "false" && value != "0";
352 else if (name == "cost") {
353 try {
354 visual.cost = std::max(0.001f, std::stof(value));
355 } catch (...) {
356 }
357 } else if (name == "enterMask") {
358 visual.enterMask = uint8_t(property.getIntAttribute("value", 0xff));
359 } else if (name == "exitMask") {
360 visual.exitMask = uint8_t(property.getIntAttribute("value", 0xff));
361 } else if (name == "opaque") {
362 visual.opaque = value != "false" && value != "0";
363 } else if (name == "semanticFlags") {
364 visual.semanticFlags = uint32_t(property.getIntAttribute("value", 0));
365 }
366 }
367 for (const auto &object : tile.elementsByTag("object")) {
368 const float x = float(object.getIntAttribute("x", 0));
369 const float y = float(object.getIntAttribute("y", 0));
370 const float width = float(object.getIntAttribute("width", 0));
371 const float height = float(object.getIntAttribute("height", 0));
372 if (width > 0.f && height > 0.f) visual.collisionShapes.push_back({x, y, width, height});
373 }
374 if (!visual.collisionShapes.empty()) visual.walkable = false;
375 info.visuals.push_back(visual);
376 TileLayer::Tileset::Animation animation;
377 animation.gid = visual.gid;
378 for (const auto &frame : tile.elementsByTag("frame")) {
379 animation.frames.push_back({firstGid + frame.getIntAttribute("tileid", localId),
380 std::max(1, frame.getIntAttribute("duration", 100))});
381 }
382 if (!animation.frames.empty()) info.animations.push_back(std::move(animation));
383 }
384 const auto wangSets = root.elementsByTag("wangset");
385 for (size_t setIndex = 0; setIndex < wangSets.size(); ++setIndex) {
386 const auto &set = wangSets[setIndex];
387 for (const auto &wangTile : set.elementsByTag("wangtile")) {
388 std::array<int, 8> values{};
389 std::stringstream stream(wangTile.getAttribute("wangid"));
390 std::string token;
391 int count = 0;
392 while (count < 8 && std::getline(stream, token, ',')) {
393 try {
394 values[size_t(count)] = std::stoi(token);
395 } catch (...) {
396 values[size_t(count)] = 0;
397 }
398 ++count;
399 }
400 if (count != 8) continue;
401 constexpr int tiledToTerrainBit[8] = {1, 2, 3, 4, 5, 6, 7, 0};
402 for (int color = 1; color <= 255; ++color) {
403 int mask = 0;
404 for (int position = 0; position < 8; ++position)
405 if (values[size_t(position)] == color) mask |= 1 << tiledToTerrainBit[position];
406 if (mask != 0)
407 info.terrainRules.push_back(
408 {firstGid + wangTile.getIntAttribute("tileid", 0), int(setIndex) * 256 + color, mask});
409 }
410 }
411 }
412 return info;
413}
414
415void applyTileset(TileLayer *layer, const TilesetInfo &info) {
416 if (!layer) return;
417 layer->setTilesetTileSize(info.tileW, info.tileH);
418 graphics::Texture *tex = tryLoadTexture(info.image);
419 layer->resource()->texturePath = info.image;
420 layer->setTileset(tex, info.firstGid, info.columns, info.margin, info.spacing);
421 layer->tileset()->visuals = info.visuals;
422 layer->tileset()->animations = info.animations;
423 layer->tileset()->terrainRules = info.terrainRules;
424 layer->tileset()->customData = info.customData;
425}
426
427void appendTileset(TileLayer *layer, const TilesetInfo &info) {
428 if (!layer) return;
429 auto tileset = layer->tileset();
430 graphics::Texture *texture = tryLoadTexture(info.image);
431 tileset->atlases.push_back({texture, info.firstGid, std::max(1, info.columns), std::max(1, info.tileW),
432 std::max(1, info.tileH), std::max(0, info.margin), std::max(0, info.spacing),
433 info.image});
434 tileset->visuals.insert(tileset->visuals.end(), info.visuals.begin(), info.visuals.end());
435 tileset->animations.insert(tileset->animations.end(), info.animations.begin(), info.animations.end());
436 tileset->terrainRules.insert(tileset->terrainRules.end(), info.terrainRules.begin(), info.terrainRules.end());
437 tileset->customData.insert(tileset->customData.end(), info.customData.begin(), info.customData.end());
438}
439
440void applyTilesets(TileLayer *layer, const std::vector<TilesetInfo> &infos) {
441 if (!layer || infos.empty()) return;
442 applyTileset(layer, infos.front());
443 for (size_t index = 1; index < infos.size(); ++index) appendTileset(layer, infos[index]);
444}
445
446bool decodeLayerData(const Json &layerObj, size_t expectedCount, std::vector<uint32_t> &out, std::string *error) {
447 if (!layerObj || !layerObj.has("data")) {
448 if (error) *error = "missing data";
449 return false;
450 }
451
452 const Json data = layerObj.get("data");
453 if (data.isArray()) {
454 out.resize(data.size());
455 for (size_t i = 0; i < data.size(); ++i) out[i] = asUInt32(data.at(i), 0);
456 if (expectedCount > 0 && out.size() != expectedCount) {
457 if (error) *error = "gid count mismatch";
458 return false;
459 }
460 return true;
461 }
462
463 const std::string encoding = layerObj.has("encoding") ? layerObj.getString("encoding") : "";
464 const std::string compression = layerObj.has("compression") ? layerObj.getString("compression") : "";
465 if (encoding != "base64") {
466 if (error) *error = "unsupported encoding";
467 return false;
468 }
469 if (compression == "zstd") {
470 if (error) *error = "zstd not supported; export as zlib";
471 return false;
472 }
473
474 const std::string b64 = data.asString();
475 size_t decodedLen = 0;
476 std::unique_ptr<char[]> decoded(eve::data::decode("base64", b64.data(), b64.size(), decodedLen));
477 if (!decoded) {
478 if (error) *error = "base64 decode failed";
479 return false;
480 }
481
482 const char *bytes = decoded.get();
483 size_t nbytes = decodedLen;
484 std::unique_ptr<char[]> inflated;
485 if (!compression.empty()) {
486 if (compression != "zlib" && compression != "gzip") {
487 if (error) *error = "unsupported compression";
488 return false;
489 }
490 size_t rawsize = expectedCount * 4;
491 try {
492 inflated.reset(eve::data::decompress(compression, bytes, nbytes, rawsize));
493 } catch (...) {
494 if (error) *error = "decompress failed";
495 return false;
496 }
497 if (!inflated) {
498 if (error) *error = "decompress failed";
499 return false;
500 }
501 bytes = inflated.get();
502 nbytes = rawsize;
503 }
504
505 if (expectedCount > 0 && nbytes != expectedCount * 4) {
506 if (error) *error = "gid byte length mismatch";
507 return false;
508 }
509 const size_t count = nbytes / 4;
510 out.resize(count);
511 for (size_t i = 0; i < count; ++i) {
512 const unsigned char *p = reinterpret_cast<const unsigned char *>(bytes) + i * 4;
513 out[i] = uint32_t(p[0]) | (uint32_t(p[1]) << 8) | (uint32_t(p[2]) << 16) | (uint32_t(p[3]) << 24);
514 }
515 return true;
516}
517
518void applyLayerDraw(TileLayer *layer, const Json &layerObj) {
519 if (!layer || !layerObj) return;
520 if (layerObj.has("visible")) layer->setVisible(layerObj.getBool("visible", true));
521 if (layerObj.has("layer"))
522 layer->setLayer(layerObj.getInt("layer", layer->getLayer()));
523 else if (layerObj.has("id"))
524 layer->setLayer(layerObj.getInt("id", layer->getLayer()));
525 float r = 1, g = 1, b = 1, a = 1;
526 if (readVec4(layerObj, "tint", r, g, b, a))
527 layer->setTint(r, g, b, a);
528 else if (layerObj.has("opacity")) {
529 a = layerObj.getFloat("opacity", 1.f);
530 layer->setTint(1.f, 1.f, 1.f, a);
531 }
532 float ox = layer->getX(), oy = layer->getY();
533 if (layerObj.has("x")) ox = layerObj.getFloat("x", ox);
534 if (layerObj.has("offsetx")) ox += layerObj.getFloat("offsetx", 0.f);
535 if (layerObj.has("y")) oy = layerObj.getFloat("y", oy);
536 if (layerObj.has("offsety")) oy += layerObj.getFloat("offsety", 0.f);
537 if (layerObj.has("x") || layerObj.has("y") || layerObj.has("offsetx") || layerObj.has("offsety"))
538 layer->setOrigin(ox, oy);
539}
540
541bool isTileLayerObject(const Json &o) {
542 if (!o || !o.isObject()) return false;
543 if (o.has("type")) {
544 const std::string t = o.getString("type");
545 if (!t.empty() && t != "tilelayer") return false;
546 }
547 return o.has("data") || o.has("chunks");
548}
549
550bool isObjectGroup(const Json &o) {
551 if (!o || !o.isObject() || !o.has("type")) return false;
552 return o.getString("type") == "objectgroup";
553}
554
555bool parseOrientation(const Json &root, TileLayer::Config *cfg, std::string *error) {
556 if (!root || !cfg) return false;
557 if (!root.has("orientation")) return true;
558 const std::string o = root.getString("orientation");
559 if (o.empty() || o == "orthogonal")
560 cfg->orientation = MapOrientation::Orthogonal;
561 else if (o == "isometric")
562 cfg->orientation = MapOrientation::Isometric;
563 else if (o == "staggered")
564 cfg->orientation = MapOrientation::Staggered;
565 else if (o == "hexagonal")
566 cfg->orientation = MapOrientation::Hexagonal;
567 else {
568 if (error) *error = "unknown orientation: " + o;
569 return false;
570 }
571 if (root.has("staggeraxis")) {
572 const std::string a = root.getString("staggeraxis");
573 cfg->staggerAxis = (a == "x") ? StaggerAxis::X : StaggerAxis::Y;
574 }
575 if (root.has("staggerindex")) {
576 const std::string i = root.getString("staggerindex");
577 cfg->staggerIndex = (i == "even") ? StaggerIndex::Even : StaggerIndex::Odd;
578 }
579 if (root.has("hexsidelength")) cfg->hexSideLength = root.getFloat("hexsidelength", 0.f);
580 return true;
581}
582
583bool applyMapGlobals(TileLayer *layer, const Json &root, std::string *error) {
584 if (!layer || !root) return false;
585
586 int mapW = layer->getMapWidth();
587 int mapH = layer->getMapHeight();
588 float tileW = layer->getTileWidth();
589 float tileH = layer->getTileHeight();
590
591 if (root.has("width")) mapW = root.getInt("width", mapW);
592 if (root.has("height")) mapH = root.getInt("height", mapH);
593 if (root.has("tilewidth"))
594 tileW = root.getFloat("tilewidth", tileW);
595 else if (root.has("tileWidth"))
596 tileW = root.getFloat("tileWidth", tileW);
597 if (root.has("tileheight"))
598 tileH = root.getFloat("tileheight", tileH);
599 else if (root.has("tileHeight"))
600 tileH = root.getFloat("tileHeight", tileH);
601
602 if (mapW != layer->getMapWidth() || mapH != layer->getMapHeight()) layer->resize(mapW, mapH);
604
605 float gapX = layer->getCellGapX();
606 float gapY = layer->getCellGapY();
607 if (readVec2(root, "cellGap", gapX, gapY)) {
608 layer->setCellGap(gapX, gapY);
609 } else {
611 float spacingY = layer->getRenderSpacingY();
612 if (readVec2(root, "renderSpacing", spacingX, spacingY)) {
613 layer->setRenderSpacing(spacingX, spacingY);
614 } else {
615 if (root.has("cellGapX")) gapX = root.getFloat("cellGapX", gapX);
616 if (root.has("cellGapY")) gapY = root.getFloat("cellGapY", gapY);
617 if (root.has("cellGapX") || root.has("cellGapY")) layer->setCellGap(gapX, gapY);
618 }
619 }
620
621 if (!parseOrientation(root, &(*layer->config()), error)) return false;
622
623 float ox = layer->getX(), oy = layer->getY();
624 if (readVec2(root, "origin", ox, oy))
625 layer->setOrigin(ox, oy);
626 else {
627 if (root.has("x")) ox = root.getFloat("x", ox);
628 if (root.has("y")) oy = root.getFloat("y", oy);
629 if (root.has("x") || root.has("y")) layer->setOrigin(ox, oy);
630 }
631
632 if (root.has("layer")) layer->setLayer(root.getInt("layer", layer->getLayer()));
633 if (root.has("visible")) layer->setVisible(root.getBool("visible", layer->isVisible()));
634 if (root.has("autoReload")) layer->resource()->autoReload = root.getBool("autoReload", true);
635
636 float r = 1, g = 1, b = 1, a = 1;
637 if (readVec4(root, "tint", r, g, b, a)) layer->setTint(r, g, b, a);
638
639 if (root.has("tileset") && !root.get("tileset").isArray()) {
640 const Json tileset = root.get("tileset");
641 if (tileset.isObject() && !tileset.has("source")) applyTileset(layer, readTilesetObject(tileset));
642 } else if (root.has("tilesets")) {
643 const Json arr = root.get("tilesets");
644 for (size_t i = 0; arr.isArray() && i < arr.size(); ++i) {
645 const Json o = arr.at(i);
646 if (!o.isObject() || o.has("source")) continue;
647 applyTileset(layer, readTilesetObject(o));
648 break;
649 }
650 } else if (root.has("image") || root.has("texture")) {
651 applyTileset(layer, readTilesetObject(root));
652 }
653 return true;
654}
655
656bool applyFlatLayerData(TileLayer *layer, const Json &root, std::string *error) {
657 const int mapW = layer->getMapWidth();
658 const int mapH = layer->getMapHeight();
659 const size_t need = size_t(std::max(0, mapW) * std::max(0, mapH));
660 if (need == 0) {
661 if (error) *error = "empty map size";
662 return false;
663 }
664 std::vector<uint32_t> data;
665 if (!decodeLayerData(root, need, data, error)) return false;
666 auto &gids = layer->tiles()->gids;
667 gids.assign(need, 0u);
668 const size_t n = std::min(need, data.size());
669 for (size_t i = 0; i < n; ++i) gids[i] = data[i];
671 return true;
672}
673
674bool applyOneLayerObject(TileLayer *layer, const Json &layerObj, int mapW, int mapH, std::string *error) {
675 if (!layer || !layerObj) return false;
676 if (layerObj.has("chunks")) {
677 const Json chunks = layerObj.get("chunks");
678 if (!chunks.isArray() || chunks.size() == 0) return false;
679 int minX = 0, minY = 0, maxX = 0, maxY = 0;
680 bool first = true;
681 for (size_t i = 0; i < chunks.size(); ++i) {
682 const Json chunk = chunks.at(i);
683 if (!chunk.isObject()) continue;
684 const int x = chunk.getInt("x", 0), y = chunk.getInt("y", 0);
685 const int w = chunk.getInt("width", 0), h = chunk.getInt("height", 0);
686 if (w <= 0 || h <= 0) continue;
687 if (first) {
688 minX = x;
689 minY = y;
690 maxX = x + w;
691 maxY = y + h;
692 first = false;
693 } else {
694 minX = std::min(minX, x);
695 minY = std::min(minY, y);
696 maxX = std::max(maxX, x + w);
697 maxY = std::max(maxY, y + h);
698 }
699 }
700 if (first) return false;
701 float shiftX = 0.f, shiftY = 0.f;
702 layer->tileToWorld(minX, minY, shiftX, shiftY);
703 layer->resize(maxX - minX, maxY - minY);
704 layer->setOrigin(shiftX, shiftY);
705 auto &gids = layer->tiles()->gids;
706 for (size_t i = 0; i < chunks.size(); ++i) {
707 const Json chunk = chunks.at(i);
708 if (!chunk.isObject()) continue;
709 const int x = chunk.getInt("x", 0), y = chunk.getInt("y", 0);
710 const int w = chunk.getInt("width", 0), h = chunk.getInt("height", 0);
711 if (w <= 0 || h <= 0) continue;
712 std::vector<uint32_t> data;
713 if (!decodeLayerData(chunk, size_t(w * h), data, error)) return false;
714 for (int cy = 0; cy < h; ++cy)
715 for (int cx = 0; cx < w; ++cx)
716 gids[size_t((y - minY + cy) * layer->getMapWidth() + x - minX + cx)] =
717 data[size_t(cy * w + cx)];
718 }
720 applyLayerDraw(layer, layerObj);
721 return true;
722 }
723 int w = mapW, h = mapH;
724 if (layerObj.has("width")) w = layerObj.getInt("width", w);
725 if (layerObj.has("height")) h = layerObj.getInt("height", h);
726 if (w != layer->getMapWidth() || h != layer->getMapHeight()) layer->resize(w, h);
727
728 const size_t need =
729 size_t(std::max(0, layer->getMapWidth()) * std::max(0, layer->getMapHeight()));
730 std::vector<uint32_t> data;
731 if (!decodeLayerData(layerObj, need, data, error)) return false;
732 auto &gids = layer->tiles()->gids;
733 gids.assign(need, 0u);
734 const size_t n = std::min(need, data.size());
735 for (size_t i = 0; i < n; ++i) gids[i] = data[i];
737
738 applyLayerDraw(layer, layerObj);
739 return true;
740}
741
742void parseObjectGroup(const Json &group, std::vector<MapObject> &out) {
743 if (!group || !group.has("objects")) return;
744 const Json arr = group.get("objects");
745 if (!arr.isArray()) return;
746 for (size_t i = 0; i < arr.size(); ++i) {
747 const Json o = arr.at(i);
748 if (!o.isObject()) continue;
749 MapObject mo;
750 if (o.has("name")) mo.name = o.getString("name");
751 if (o.has("type"))
752 mo.type = o.getString("type");
753 else if (o.has("class"))
754 mo.type = o.getString("class");
755 mo.x = o.has("x") ? o.getFloat("x", 0.f) : 0.f;
756 mo.y = o.has("y") ? o.getFloat("y", 0.f) : 0.f;
757 mo.width = o.has("width") ? o.getFloat("width", 0.f) : 0.f;
758 mo.height = o.has("height") ? o.getFloat("height", 0.f) : 0.f;
759 if (o.has("gid")) mo.gid = uint32_t(o.getInt("gid", 0));
760 if (o.has("properties")) {
761 const Json properties = o.get("properties");
762 for (size_t propertyIndex = 0; properties.isArray() && propertyIndex < properties.size();
763 ++propertyIndex) {
764 const Json property = properties.at(propertyIndex);
765 if (!property.isObject() || !property.has("name") || !property.has("value")) continue;
766 const std::string name = property.getString("name");
767 if (!name.empty()) mo.properties.emplace(name, property.get("value").asString());
768 }
769 }
770 out.push_back(std::move(mo));
771 }
772}
773
774void abandonLayers(std::vector<TileLayer *> &layers) {
775 for (TileLayer *layer : layers) {
776 if (!layer) continue;
777 layer->clear();
778 layer->setVisible(false);
779 }
780 layers.clear();
781}
782
783struct LayerEntry {
784 Json object;
785 float offsetX = 0.f;
786 float offsetY = 0.f;
787 float opacity = 1.f;
788 bool visible = true;
789};
790
791void flattenLayers(const Json &source, std::vector<LayerEntry> &out, float parentX = 0.f, float parentY = 0.f,
792 float parentOpacity = 1.f, bool parentVisible = true) {
793 for (size_t index = 0; source.isArray() && index < source.size(); ++index) {
794 const Json object = source.at(index);
795 if (!object.isObject()) continue;
796 const float offsetX =
797 parentX + (object.has("offsetx") ? object.getFloat("offsetx", 0.f) : 0.f);
798 const float offsetY =
799 parentY + (object.has("offsety") ? object.getFloat("offsety", 0.f) : 0.f);
800 const float opacity =
801 parentOpacity * (object.has("opacity") ? object.getFloat("opacity", 1.f) : 1.f);
802 const bool visible =
803 parentVisible && (!object.has("visible") || object.getBool("visible", true));
804 if (object.has("type") && object.getString("type") == "group" && object.has("layers")) {
805 flattenLayers(object.get("layers"), out, offsetX, offsetY, opacity, visible);
806 continue;
807 }
808 out.push_back({object, offsetX, offsetY, opacity, visible});
809 }
810}
811
812std::vector<TilesetInfo> readTilesets(const Json &root, const std::string &mapPath,
813 eve::filesystem::Filesystem *fs, std::string *error) {
814 std::vector<TilesetInfo> result;
815 // Keep external JSON documents alive: TilesetInfo reads image paths as
816 // strings (copied), but we still need the Document while reading fields.
817 std::vector<eve::json::Document> ownedDocs;
818 if (root.has("tilesets")) {
819 const Json arr = root.get("tilesets");
820 if (!arr.isArray()) {
821 if (error) *error = "map.import.tilesets-invalid";
822 return {};
823 }
824 for (size_t i = 0; i < arr.size(); ++i) {
825 const Json o = arr.at(i);
826 if (!o.isObject()) {
827 if (error) *error = "map.import.tileset-entry-invalid: index=" + std::to_string(i);
828 return {};
829 }
830 const int firstGid = o.has("firstgid") ? o.getInt("firstgid", 1) : 1;
831 if (o.has("source")) {
832 const std::string source = resolveAssetPath(mapPath, o.getString("source"));
833 if (std::filesystem::path(source).extension() == ".tsx") {
834 TilesetInfo info = readTsxTileset(fs, source, firstGid, error);
835 if (error && !error->empty()) return {};
836 info.sourcePath = source;
837 result.push_back(std::move(info));
838 continue;
839 }
840 ownedDocs.push_back(readJsonDocument(fs, source, error));
841 if (!ownedDocs.back().valid()) return {};
842 TilesetInfo info = readTilesetObject(ownedDocs.back().root(), firstGid);
843 info.sourcePath = source;
844 info.image = resolveAssetPath(source, info.image);
845 result.push_back(std::move(info));
846 continue;
847 }
848 TilesetInfo info = readTilesetObject(o);
849 info.image = resolveAssetPath(mapPath, info.image);
850 result.push_back(std::move(info));
851 }
852 } else if (root.has("tileset") && !root.get("tileset").isArray()) {
853 const Json o = root.get("tileset");
854 if (o.isObject() && !o.has("source")) {
855 TilesetInfo info = readTilesetObject(o);
856 info.image = resolveAssetPath(mapPath, info.image);
857 result.push_back(std::move(info));
858 }
859 } else if (root.has("image") || root.has("texture")) {
860 TilesetInfo info = readTilesetObject(root);
861 info.image = resolveAssetPath(mapPath, info.image);
862 result.push_back(std::move(info));
863 }
864 std::sort(result.begin(), result.end(),
865 [](const TilesetInfo &left, const TilesetInfo &right) { return left.firstGid < right.firstGid; });
866 return result;
867}
868
869std::vector<TileLayer *> loadMapObject(const Json &root, const std::string &path, eve::filesystem::Filesystem *fs,
870 std::vector<MapObject> *objects, std::string *error) {
871 std::vector<TileLayer *> out;
872 if (!root || !root.isObject()) {
873 if (error) *error = "config root must be object";
874 return out;
875 }
876
877 int mapW = 10, mapH = 10;
878 float tileW = 32.f, tileH = 32.f;
879 if (root.has("width")) mapW = root.getInt("width", mapW);
880 if (root.has("height")) mapH = root.getInt("height", mapH);
881 if (root.has("tilewidth"))
882 tileW = root.getFloat("tilewidth", tileW);
883 else if (root.has("tileWidth"))
884 tileW = root.getFloat("tileWidth", tileW);
885 if (root.has("tileheight"))
886 tileH = root.getFloat("tileheight", tileH);
887 else if (root.has("tileHeight"))
888 tileH = root.getFloat("tileHeight", tileH);
889
890 TileLayer::Config orientCheck;
891 if (!parseOrientation(root, &orientCheck, error)) return out;
892
893 std::vector<TilesetInfo> tilesets = readTilesets(root, path, fs, error);
894 if (root.has("tilesets") && tilesets.empty() && error && !error->empty()) return out;
895 if (objects) objects->clear();
896
897 auto bindResource = [&](TileLayer *layer) {
898 auto res = layer->resource();
899 res->path = path;
900 res->dependencyPaths.clear();
901 res->dependencyModtimes.clear();
902 if (!path.empty()) {
903 res->modtime = fileModtime(path);
904 if (fs) {
905 fs->watch(path);
906 if (auto *hot =
907 eve::ModuleManager::getInstance<eve::filesystem::HotReload>("HotReload"))
908 hot->bind(path, "tilemap");
909 }
910 }
911 for (const TilesetInfo &tileset : tilesets) {
912 if (tileset.sourcePath.empty()) continue;
913 res->dependencyPaths.push_back(tileset.sourcePath);
914 res->dependencyModtimes.push_back(fileModtime(tileset.sourcePath));
915 if (fs) fs->watch(tileset.sourcePath);
916 if (auto *hot = eve::ModuleManager::getInstance<eve::filesystem::HotReload>("HotReload"))
917 hot->bind(tileset.sourcePath, "tilemap");
918 }
919 if (root.has("autoReload")) res->autoReload = root.getBool("autoReload", true);
920 };
921
922 if (root.has("layers")) {
923 const Json arr = root.get("layers");
924 if (arr.isArray()) {
925 std::vector<LayerEntry> entries;
926 flattenLayers(arr, entries);
927 int sort = 0;
928 for (const LayerEntry &entry : entries) {
929 const Json &lo = entry.object;
930 if (objects && isObjectGroup(lo)) {
931 parseObjectGroup(lo, *objects);
932 continue;
933 }
934 if (!isTileLayerObject(lo)) continue;
935 TileLayer *layer = TileLayer::createLayer(mapW, mapH, tileW, tileH);
936 if (!applyMapGlobals(layer, root, error)) {
937 abandonLayers(out);
938 layer->clear();
939 layer->setVisible(false);
940 return {};
941 }
942 applyTilesets(layer, tilesets);
943 if (!applyOneLayerObject(layer, lo, mapW, mapH, error)) {
944 abandonLayers(out);
945 layer->clear();
946 layer->setVisible(false);
947 return {};
948 }
949 if (!lo.has("layer") && !lo.has("id")) layer->setLayer(sort);
950 layer->setOrigin(layer->getX() + entry.offsetX, layer->getY() + entry.offsetY);
951 layer->draw()->visible = layer->draw()->visible && entry.visible;
952 layer->draw()->tint.a *= entry.opacity;
953 ++sort;
954 bindResource(layer);
955 out.push_back(layer);
956 }
957 }
958 if (!out.empty()) return out;
959 }
960
961 TileLayer *layer = TileLayer::createLayer(mapW, mapH, tileW, tileH);
962 if (!applyMapGlobals(layer, root, error)) {
963 layer->clear();
964 layer->setVisible(false);
965 return {};
966 }
967 applyTilesets(layer, tilesets);
968 if (root.has("data")) {
969 if (!applyFlatLayerData(layer, root, error)) {
970 layer->clear();
971 layer->setVisible(false);
972 return {};
973 }
974 }
975 bindResource(layer);
976 out.push_back(layer);
977 return out;
978}
979
980} // namespace
981
983 auto fail = [](eve::DiagnosticCode code, const std::string& message) {
985 };
986 if (!layer || !root || !root.isObject())
987 return fail(eve::DiagnosticCode::InvalidArgument, "config root must be an object");
988
989 std::string err;
990 if (!applyMapGlobals(layer, root, &err))
991 return fail(eve::DiagnosticCode::Failed, err.empty() ? "map globals rejected" : err);
992
993 if (root.has("layers")) {
994 const Json arr = root.get("layers");
995 for (size_t i = 0; arr.isArray() && i < arr.size(); ++i) {
996 const Json lo = arr.at(i);
997 if (!isTileLayerObject(lo)) continue;
998 if (!applyOneLayerObject(layer, lo, layer->getMapWidth(), layer->getMapHeight(), &err))
999 return fail(eve::DiagnosticCode::Failed, err.empty() ? "tile layer apply failed" : err);
1001 }
1002 }
1003
1004 if (root.has("data")) {
1005 if (!applyFlatLayerData(layer, root, &err))
1006 return fail(eve::DiagnosticCode::Failed, err.empty() ? "layer data apply failed" : err);
1008 }
1010}
1011
1012bool applyConfigText(TileLayer *layer, const std::string &json, std::string *error) {
1013 std::string err;
1014 auto doc = eve::json::Document::parse(json, &err);
1015 if (!doc.valid()) {
1016 if (error) *error = err.empty() ? "invalid json" : err;
1017 return false;
1018 }
1019 const Json root = doc.root();
1020 if (!root.isObject()) {
1021 if (error) *error = "config root must be object";
1022 return false;
1023 }
1024 const TileLayer::Config oldConfig = *layer->config();
1025 const TileLayer::Tiles oldTiles = *layer->tiles();
1026 const TileLayer::Tileset oldTileset = *layer->tileset();
1027 const TileLayer::Draw oldDraw = *layer->draw();
1028 const TileLayer::Resource oldResource = *layer->resource();
1029 auto rollback = [&]() {
1030 *layer->config() = oldConfig;
1031 *layer->tiles() = oldTiles;
1032 *layer->tileset() = oldTileset;
1033 *layer->draw() = oldDraw;
1034 *layer->resource() = oldResource;
1035 };
1036 if (!applyMapGlobals(layer, root, error)) {
1037 rollback();
1038 return false;
1039 }
1040 if (root.has("layers")) {
1041 const Json arr = root.get("layers");
1042 for (size_t i = 0; arr.isArray() && i < arr.size(); ++i) {
1043 const Json lo = arr.at(i);
1044 if (!isTileLayerObject(lo)) continue;
1045 if (applyOneLayerObject(layer, lo, layer->getMapWidth(), layer->getMapHeight(), error)) return true;
1046 rollback();
1047 return false;
1048 }
1049 }
1050 if (root.has("data")) {
1051 if (applyFlatLayerData(layer, root, error)) return true;
1052 rollback();
1053 return false;
1054 }
1055 return true;
1056}
1057
1058bool loadConfigFile(TileLayer *layer, const std::string &path, std::string *error) {
1059 if (error) error->clear();
1060 if (!layer || path.empty()) {
1061 if (error) *error = "empty path";
1062 return false;
1063 }
1064 auto *fs = eve::ModuleManager::getInstance<eve::filesystem::Filesystem>("Filesystem");
1065 if (!fs) fs = eve::filesystem::Filesystem::create();
1066
1067 std::string text;
1068 if (!readImportText(fs, path, text)) {
1069 if (error) *error = "empty file: " + path;
1070 return false;
1071 }
1072
1073 std::string decodeError;
1074 auto document = eve::json::Document::parse(text, &decodeError);
1075 if (!document.valid() || !document.root().isObject()) {
1076 if (error) *error = decodeError.empty() ? "map.import.invalid-json" : decodeError;
1077 return false;
1078 }
1079 const Json root = document.root();
1080 std::vector<TilesetInfo> tilesets = readTilesets(root, path, fs, error);
1081 if (root.has("tilesets") && tilesets.empty() && error && !error->empty()) return false;
1082
1083 const TileLayer::Config oldConfig = *layer->config();
1084 const TileLayer::Tiles oldTiles = *layer->tiles();
1085 const TileLayer::Tileset oldTileset = *layer->tileset();
1086 const TileLayer::Draw oldDraw = *layer->draw();
1087 const TileLayer::Resource oldResource = *layer->resource();
1088 if (!applyConfigText(layer, text, error)) {
1089 *layer->config() = oldConfig;
1090 *layer->tiles() = oldTiles;
1091 *layer->tileset() = oldTileset;
1092 *layer->draw() = oldDraw;
1093 *layer->resource() = oldResource;
1094 return false;
1095 }
1096 if (!tilesets.empty()) applyTilesets(layer, tilesets);
1097
1098 auto res = layer->resource();
1099 res->path = path;
1100 res->modtime = fileModtime(path);
1101 res->dependencyPaths.clear();
1102 res->dependencyModtimes.clear();
1103 for (const auto &tileset : tilesets) {
1104 if (tileset.sourcePath.empty()) continue;
1105 res->dependencyPaths.push_back(tileset.sourcePath);
1106 res->dependencyModtimes.push_back(fileModtime(tileset.sourcePath));
1107 fs->watch(tileset.sourcePath);
1108 if (auto *hot = eve::ModuleManager::getInstance<eve::filesystem::HotReload>("HotReload"))
1109 hot->bind(tileset.sourcePath, "tilemap");
1110 }
1111 fs->watch(path);
1112 if (auto *hot = eve::ModuleManager::getInstance<eve::filesystem::HotReload>("HotReload"))
1113 hot->bind(path, "tilemap");
1114 return true;
1115}
1116
1118 if (!layer) return false;
1119 const std::string &path = layer->resource()->path;
1120 if (path.empty()) {
1121 if (error) *error = "no config path";
1122 return false;
1123 }
1124 return loadConfigFile(layer, path, error);
1125}
1126
1127bool loadTilesetManifestFile(TileLayer *layer, const std::string &path, std::string *error) {
1128 if (!layer || path.empty()) {
1129 if (error) *error = "empty path";
1130 return false;
1131 }
1132 auto *fs = eve::ModuleManager::getInstance<eve::filesystem::Filesystem>("Filesystem");
1133 if (!fs) fs = eve::filesystem::Filesystem::create();
1134 std::unique_ptr<eve::filesystem::FileData> data;
1135 try {
1136 data.reset(fs->read(path));
1137 } catch (...) {
1138 if (error) *error = "read failed: " + path;
1139 return false;
1140 }
1141 if (!data || data->getSize() == 0) {
1142 if (error) *error = "empty file: " + path;
1143 return false;
1144 }
1145 const std::string text(static_cast<const char *>(data->getData()), data->getSize());
1146 std::string decodeError;
1147 auto doc = eve::json::Document::parse(text, &decodeError);
1148 if (!doc.valid() || !doc.root().isObject()) {
1149 if (error) *error = decodeError.empty() ? "invalid tileset manifest" : decodeError;
1150 return false;
1151 }
1152 Json root = doc.root();
1153 if (root.has("tileset")) {
1154 root = root.get("tileset");
1155 if (!root.isObject()) {
1156 if (error) *error = "tileset must be an object";
1157 return false;
1158 }
1159 }
1160 const TilesetInfo info = readTilesetObject(root);
1161 if (info.image.empty()) {
1162 if (error) *error = "tileset manifest has no image";
1163 return false;
1164 }
1165 applyTileset(layer, info);
1166 fs->watch(path);
1167 if (auto *hot = eve::ModuleManager::getInstance<eve::filesystem::HotReload>("HotReload"))
1168 hot->bind(path, "tilemap");
1169 return true;
1170}
1171
1172std::vector<TileLayer *> loadMapText(const std::string &json, std::vector<MapObject> *objects,
1173 std::string *error) {
1174 std::string err;
1175 auto doc = eve::json::Document::parse(json, &err);
1176 if (!doc.valid() || !doc.root().isObject()) {
1177 if (error) *error = err.empty() ? "invalid json" : err;
1178 return {};
1179 }
1180 return loadMapObject(doc.root(), {}, nullptr, objects, error);
1181}
1182
1183std::vector<TileLayer *> loadMapFile(const std::string &path, std::vector<MapObject> *objects,
1184 std::string *error) {
1185 if (error) error->clear();
1186 if (path.empty()) {
1187 if (error) *error = "empty path";
1188 return {};
1189 }
1190
1191 auto *fs = eve::ModuleManager::getInstance<eve::filesystem::Filesystem>("Filesystem");
1192 if (!fs) fs = eve::filesystem::Filesystem::create();
1193
1194 std::string text;
1195 if (!readImportText(fs, path, text)) {
1196 if (error) *error = "empty file: " + path;
1197 return {};
1198 }
1199 std::string err;
1200 auto doc = eve::json::Document::parse(text, &err);
1201 if (!doc.valid() || !doc.root().isObject()) {
1202 if (error) *error = err.empty() ? "invalid json" : err;
1203 return {};
1204 }
1205 return loadMapObject(doc.root(), path, fs, objects, error);
1206}
1207
1208std::vector<TileLayer *> loadMapFile(const std::string &path, std::string *error) {
1209 return loadMapFile(path, nullptr, error);
1210}
1211
1213
1214} // namespace eve::map
double y
double x
float w
Definition AnimClip.cpp:738
float duration
int root
Definition AnimSmr.cpp:119
AuthorityStoreHandleRef reference
Definition Authority.cpp:24
std::unordered_map< std::string, QuestRuntime > entries
int mask
float cx
Definition CardTypes.cpp:36
float cy
Definition CardTypes.cpp:37
glm::vec4 p[6]
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
EvpackChunkInput input
Definition Evpack.cpp:170
std::string message
DiagnosticCode code
tensor::Graph g
Definition GpuGraph.cpp:7
vk::UniqueImage image
float u
Definition Grass.cpp:233
glm::vec3 n
Definition Grass.cpp:63
double r
float v
HexVec3 left
HexVec3 right
std::int32_t c
std::int32_t first
int h
std::vector< Colorf > px
std::string encoding
std::uint32_t height
std::uint32_t width
std::array< float, 3 > position
std::map< std::string, PropertyRule > properties
bool present
Poco::JSON::Object::Ptr result
std::uint64_t bytes
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
OceanGpuFrameToken token
ssq::Object frame
std::string error
Definition Package.cpp:174
Texture * texture
TileLayer * layer
std::string path
Definition PlayHost.cpp:111
std::set< std::string > values
Object::Ptr value
float d
float t
std::vector< WfcTile > tiles
std::string text
ScriptStructure out
std::string_view source
int count
AbilityActivationGroup group
double spacingX
int spacing
int firstGid
std::vector< TileLayer::Tileset::TerrainRule > terrainRules
int columns
std::vector< TileLayer::Tileset::CustomData > customData
float offsetX
std::vector< TileLayer::Tileset::Visual > visuals
float offsetY
int tileW
float opacity
int margin
int tileH
std::string sourcePath
bool visible
Json object
std::vector< TileLayer::Tileset::Animation > animations
uint32_t index
double oy
double ox
double compression
glm::vec3 point
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
EVENGINE_API_FOUNDATION public API.
Definition Filesystem.h:43
virtual FileData * read(std::string filename, int64_t size=File::ALL) const =0
Reads data from a file.
virtual bool watch(std::string path)=0
Watch a virtual or absolute OS path (file or directory). File watches monitor the parent directory an...
EVENGINE_API_FOUNDATION public API.
Definition Json.h:137
static Document parse(const std::string &text, std::string *error=nullptr)
Parse.
Definition Json.cpp:623
EVENGINE_API_FOUNDATION public API.
Definition Json.h:39
ECS tile layer entity. Script mutates tile GIDs / tileset / draw; TileRenderSystem batch-draws atlas ...
Definition TileLayer.h:33
void clear()
Clears the layer to empty.
float getTileWidth()
Tile size in pixels.
Definition TileLayer.cpp:37
void setCellGap(float gapX, float gapY)
Sets extra world-space distance between projected cells.
void rebuildSpatialIndex()
Rebuild chunk occupancy after bulk loader writes directly to gids.
void setOrigin(float x, float y)
World origin of the layer (pixels).
Definition TileLayer.cpp:27
void setTileset(graphics::Texture *texture, int firstGid, int columns, int margin=0, int spacing=0)
Binds the atlas texture and tile table.
void resize(int mapW, int mapH)
Resizes the tile grid (existing GIDs preserved where possible).
Definition TileLayer.cpp:46
void setRenderSpacing(float spacingX, float spacingY)
Sets projected cell pitch as a multiple of the logical tile size.
void setTilesetTileSize(int tileW, int tileH)
Tile size in pixels of the bound tileset.
void setLayer(int layer)
Draw order layer / visibility / tint.
static TileLayer * createLayer(int mapW, int mapH, float tileW=32.f, float tileH=32.f)
Definition TileLayer.cpp:14
float getCellGapX()
Horizontal and vertical world-space gaps between projected cells.
void setTileSize(float tileW, float tileH)
Definition TileLayer.cpp:40
void tileToWorld(int tx, int ty, float &wx, float &wy)
Tile-index ↔ world-pixel conversions (per layer orientation).
float getRenderSpacingX()
Horizontal and vertical projected pitch multipliers.
void setVisible(bool visible)
int getMapWidth()
Map dimensions in tiles.
Definition TileLayer.cpp:35
void setTint(float r, float g, float b, float a=1.f)
static Document parse(const std::string &text, std::string *error=nullptr)
Definition Xml.cpp:305
StateValue objects
Definition Snapshot.cpp:110
std::string extension(std::string_view name)
Extension.
char * decompress(CompressedData *data, size_t &decompressedsize)
Decompresses existing compressed data into raw bytes.
char * decode(std::string format, const char *src, size_t srclen, size_t &dstlen)
Decodes a text buffer (hex / base64) back into raw bytes.
bool has(const std::vector< std::reference_wrapper< const HouseComponent > > &values)
放置世界:格子占用(多通道)+ 地形语义 + 已放置建筑实例。 行为由 PlacementSystem 提供;本类暴露便于脚本绑定的薄封装方法。 坐标换算统一走 eve::grid(支持 rectang...
eve::Result< void > applyConfigDocument(TileLayer *layer, eve::json::Value root)
Apply map/layer JSON onto an existing TileLayer (Config + Tiles + Tileset + Draw)....
std::vector< TileLayer * > loadMapText(const std::string &json, std::vector< MapObject > *objects, std::string *error)
Parse map JSON text (no filesystem). Same semantics as loadMapFile.
bool loadTilesetManifestFile(TileLayer *layer, const std::string &path, std::string *error)
Load a composable TileSet manifest onto an existing layer.
bool reloadConfigFile(TileLayer *layer, std::string *error)
Reloads config file.
bool applyConfigText(TileLayer *layer, const std::string &json, std::string *error)
Parse JSON text and apply onto one layer.
StaggerIndex
Which rows/columns are offset by half a tile.
std::vector< TileLayer * > loadMapFile(const std::string &path, std::vector< MapObject > *objects, std::string *error)
Loads map file.
StaggerAxis
Stagger axis for staggered/hex maps (shift every other row/column).
bool loadConfigFile(TileLayer *layer, const std::string &path, std::string *error)
Read path via Filesystem, apply onto layer, bind Resource.path + modtime for hot reload....
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
Config public API.
Definition TileLayer.h:50
glm::uvec4 info
glm::vec4 color