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;
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);
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);
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;
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;
70 graphics::Texture *tex = gfx->newTextureFromFile(
path);
71 if (
auto *hot = eve::ModuleManager::getInstance<eve::filesystem::HotReload>(
"HotReload"))
72 hot->bind(
path,
"texture");
88 std::vector<TileLayer::Tileset::Visual>
visuals;
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)) {
102 visual.width = int(
w);
103 visual.height = int(
h);
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));
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")) {
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));
134 if (o.has(
"objectgroup")) {
135 const Json
group = o.get(
"objectgroup");
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);
164 if (!visual.collisionShapes.empty()) visual.walkable =
false;
169TilesetInfo readTilesetObject(
const Json &o, std::optional<int>
firstGid = std::nullopt) {
171 if (!o || !o.isObject())
return info;
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);
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));
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;
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);
215 animation.frames.push_back({
info.firstGid + frameLocal, std::max(1,
duration)});
217 if (!animation.frames.empty())
info.animations.push_back(std::move(animation));
219 if (tile.has(
"terrain") && tile.has(
"neighborMask")) {
220 info.terrainRules.push_back(
221 {gid, tile.getInt(
"terrain", 0), tile.getInt(
"neighborMask", 0) & 0xff});
223 if (tile.has(
"properties")) {
224 const Json
properties = tile.get(
"properties");
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()});
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);
250 constexpr int tiledToTerrainBit[8] = {1, 2, 3, 4, 5, 6, 7, 0};
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);
271 return (std::filesystem::path(ownerPath).parent_path() /
reference).lexically_normal().generic_string();
277 std::unique_ptr<eve::filesystem::FileData>
bytes(fs->
read(
path));
279 text.assign(
static_cast<const char *
>(
bytes->getData()),
bytes->getSize());
285 std::ifstream
input(std::filesystem::path(
path), std::ios::binary);
286 if (!
input)
return false;
287 std::ostringstream stream;
288 stream <<
input.rdbuf();
290 return !
text.empty();
299 if (!readImportText(fs,
path,
text)) {
303 std::string decodeError;
305 if (!document.valid() || !document.root().isObject()) {
307 *
error =
"map.import.external-tileset-invalid-json: " +
path +
308 (decodeError.empty() ? std::string{} :
" (" + decodeError +
")");
315 std::string *
error) {
319 if (!readImportText(fs,
path,
text)) {
323 std::string parseError;
325 auto root = document.root();
326 if (!document.valid() || !
root ||
root.tagName() !=
"tileset") {
328 *
error =
"map.import.external-tsx-invalid: " +
path +
329 (parseError.empty() ?
" (root is not tileset)" :
" (" + parseError +
")");
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");
342 TileLayer::Tileset::Visual visual;
343 const int localId = tile.getIntAttribute(
"id",
int(
index));
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");
350 if (
name ==
"walkable")
351 visual.walkable =
value !=
"false" &&
value !=
"0";
352 else if (
name ==
"cost") {
354 visual.cost = std::max(0.001f, std::stof(
value));
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));
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));
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))});
382 if (!animation.frames.empty())
info.animations.push_back(std::move(animation));
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"));
392 while (
count < 8 && std::getline(stream,
token,
',')) {
400 if (
count != 8)
continue;
401 constexpr int tiledToTerrainBit[8] = {1, 2, 3, 4, 5, 6, 7, 0};
407 info.terrainRules.push_back(
408 {
firstGid + wangTile.getIntAttribute(
"tileid", 0),
int(setIndex) * 256 +
color,
mask});
415void applyTileset(TileLayer *
layer,
const TilesetInfo &
info) {
418 graphics::Texture *tex = tryLoadTexture(
info.image);
419 layer->resource()->texturePath =
info.image;
421 layer->tileset()->visuals =
info.visuals;
422 layer->tileset()->animations =
info.animations;
423 layer->tileset()->terrainRules =
info.terrainRules;
424 layer->tileset()->customData =
info.customData;
427void appendTileset(TileLayer *
layer,
const TilesetInfo &
info) {
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),
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());
440void applyTilesets(TileLayer *
layer,
const std::vector<TilesetInfo> &infos) {
441 if (!
layer || infos.empty())
return;
442 applyTileset(
layer, infos.front());
446bool decodeLayerData(
const Json &layerObj,
size_t expectedCount, std::vector<uint32_t> &
out, std::string *
error) {
447 if (!layerObj || !layerObj.has(
"data")) {
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) {
463 const std::string
encoding = layerObj.has(
"encoding") ? layerObj.getString(
"encoding") :
"";
464 const std::string
compression = layerObj.has(
"compression") ? layerObj.getString(
"compression") :
"";
470 if (
error) *
error =
"zstd not supported; export as zlib";
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));
482 const char *
bytes = decoded.get();
483 size_t nbytes = decodedLen;
484 std::unique_ptr<char[]> inflated;
487 if (
error) *
error =
"unsupported compression";
490 size_t rawsize = expectedCount * 4;
501 bytes = inflated.get();
505 if (expectedCount > 0 && nbytes != expectedCount * 4) {
506 if (
error) *
error =
"gid byte length mismatch";
509 const size_t count = nbytes / 4;
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);
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"))
523 else if (layerObj.has(
"id"))
525 float r = 1,
g = 1,
b = 1,
a = 1;
526 if (readVec4(layerObj,
"tint",
r,
g,
b,
a))
528 else if (layerObj.has(
"opacity")) {
529 a = layerObj.getFloat(
"opacity", 1.f);
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"))
541bool isTileLayerObject(
const Json &o) {
542 if (!o || !o.isObject())
return false;
544 const std::string
t = o.getString(
"type");
545 if (!
t.empty() &&
t !=
"tilelayer")
return false;
547 return o.has(
"data") || o.has(
"chunks");
550bool isObjectGroup(
const Json &o) {
551 if (!o || !o.isObject() || !o.has(
"type"))
return false;
552 return o.getString(
"type") ==
"objectgroup";
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")
561 else if (o ==
"isometric")
563 else if (o ==
"staggered")
565 else if (o ==
"hexagonal")
568 if (
error) *
error =
"unknown orientation: " + o;
571 if (
root.has(
"staggeraxis")) {
572 const std::string
a =
root.getString(
"staggeraxis");
575 if (
root.has(
"staggerindex")) {
576 const std::string i =
root.getString(
"staggerindex");
579 if (
root.has(
"hexsidelength")) cfg->hexSideLength =
root.getFloat(
"hexsidelength", 0.f);
583bool applyMapGlobals(TileLayer *
layer,
const Json &
root, std::string *
error) {
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"))
595 else if (
root.has(
"tileWidth"))
597 if (
root.has(
"tileheight"))
599 else if (
root.has(
"tileHeight"))
607 if (readVec2(
root,
"cellGap", gapX, gapY)) {
612 if (readVec2(
root,
"renderSpacing",
spacingX, spacingY)) {
615 if (
root.has(
"cellGapX")) gapX =
root.getFloat(
"cellGapX", gapX);
616 if (
root.has(
"cellGapY")) gapY =
root.getFloat(
"cellGapY", gapY);
621 if (!parseOrientation(
root, &(*
layer->config()),
error))
return false;
624 if (readVec2(
root,
"origin",
ox,
oy))
634 if (
root.has(
"autoReload"))
layer->resource()->autoReload =
root.getBool(
"autoReload",
true);
636 float r = 1,
g = 1,
b = 1,
a = 1;
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));
650 }
else if (
root.has(
"image") ||
root.has(
"texture")) {
651 applyTileset(
layer, readTilesetObject(
root));
656bool applyFlatLayerData(TileLayer *
layer,
const Json &
root, std::string *
error) {
659 const size_t need = size_t(std::max(0, mapW) * std::max(0, mapH));
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, 0
u);
668 const size_t n = std::min(need, data.size());
669 for (
size_t i = 0; i <
n; ++i) gids[i] = data[i];
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;
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;
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);
700 if (
first)
return false;
701 float shiftX = 0.f, shiftY = 0.f;
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;
717 data[size_t(
cy *
w +
cx)];
720 applyLayerDraw(
layer, layerObj);
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);
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, 0
u);
734 const size_t n = std::min(need, data.size());
735 for (
size_t i = 0; i <
n; ++i) gids[i] = data[i];
738 applyLayerDraw(
layer, layerObj);
742void parseObjectGroup(
const Json &
group, std::vector<MapObject> &
out) {
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;
750 if (o.has(
"name")) mo.name = o.getString(
"name");
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")) {
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());
770 out.push_back(std::move(mo));
774void abandonLayers(std::vector<TileLayer *> &layers) {
775 for (TileLayer *
layer : layers) {
776 if (!
layer)
continue;
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) {
795 if (!
object.isObject())
continue;
797 parentX + (
object.has(
"offsetx") ?
object.getFloat(
"offsetx", 0.f) : 0.f);
799 parentY + (
object.has(
"offsety") ?
object.getFloat(
"offsety", 0.f) : 0.f);
801 parentOpacity * (
object.has(
"opacity") ?
object.getFloat(
"opacity", 1.f) : 1.f);
803 parentVisible && (!
object.has(
"visible") ||
object.getBool(
"visible",
true));
804 if (
object.
has(
"type") &&
object.getString(
"type") ==
"group" &&
object.has(
"layers")) {
812std::vector<TilesetInfo> readTilesets(
const Json &
root,
const std::string &mapPath,
814 std::vector<TilesetInfo>
result;
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";
824 for (
size_t i = 0; i < arr.size(); ++i) {
825 const Json o = arr.at(i);
827 if (
error) *
error =
"map.import.tileset-entry-invalid: index=" + std::to_string(i);
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"));
840 ownedDocs.push_back(readJsonDocument(fs,
source,
error));
841 if (!ownedDocs.back().valid())
return {};
842 TilesetInfo
info = readTilesetObject(ownedDocs.back().root(),
firstGid);
848 TilesetInfo
info = readTilesetObject(o);
849 info.image = resolveAssetPath(mapPath,
info.image);
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);
859 }
else if (
root.has(
"image") ||
root.has(
"texture")) {
860 TilesetInfo
info = readTilesetObject(
root);
861 info.image = resolveAssetPath(mapPath,
info.image);
865 [](
const TilesetInfo &
left,
const TilesetInfo &
right) { return left.firstGid < right.firstGid; });
871 std::vector<TileLayer *>
out;
873 if (
error) *
error =
"config root must be object";
877 int mapW = 10, mapH = 10;
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"))
883 else if (
root.has(
"tileWidth"))
885 if (
root.has(
"tileheight"))
887 else if (
root.has(
"tileHeight"))
890 TileLayer::Config orientCheck;
891 if (!parseOrientation(
root, &orientCheck,
error))
return out;
893 std::vector<TilesetInfo> tilesets = readTilesets(
root,
path, fs,
error);
894 if (
root.has(
"tilesets") && tilesets.empty() &&
error && !
error->empty())
return out;
897 auto bindResource = [&](TileLayer *
layer) {
898 auto res =
layer->resource();
900 res->dependencyPaths.
clear();
901 res->dependencyModtimes.clear();
903 res->modtime = fileModtime(
path);
907 eve::ModuleManager::getInstance<eve::filesystem::HotReload>(
"HotReload"))
908 hot->bind(
path,
"tilemap");
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");
919 if (
root.has(
"autoReload")) res->autoReload =
root.getBool(
"autoReload",
true);
922 if (
root.has(
"layers")) {
923 const Json arr =
root.get(
"layers");
925 std::vector<LayerEntry>
entries;
928 for (
const LayerEntry &entry :
entries) {
929 const Json &lo = entry.object;
930 if (
objects && isObjectGroup(lo)) {
931 parseObjectGroup(lo, *
objects);
934 if (!isTileLayerObject(lo))
continue;
942 applyTilesets(
layer, tilesets);
943 if (!applyOneLayerObject(
layer, lo, mapW, mapH,
error)) {
949 if (!lo.has(
"layer") && !lo.has(
"id"))
layer->
setLayer(sort);
951 layer->draw()->visible =
layer->draw()->visible && entry.visible;
952 layer->draw()->tint.a *= entry.opacity;
958 if (!
out.empty())
return out;
967 applyTilesets(
layer, tilesets);
968 if (
root.has(
"data")) {
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;
1004 if (
root.has(
"data")) {
1005 if (!applyFlatLayerData(
layer,
root, &err))
1016 if (
error) *
error = err.empty() ?
"invalid json" : err;
1019 const Json
root = doc.root();
1020 if (!
root.isObject()) {
1021 if (
error) *
error =
"config root must be object";
1029 auto rollback = [&]() {
1030 *
layer->config() = oldConfig;
1031 *
layer->tiles() = oldTiles;
1032 *
layer->tileset() = oldTileset;
1033 *
layer->draw() = oldDraw;
1034 *
layer->resource() = oldResource;
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;
1050 if (
root.has(
"data")) {
1064 auto *fs = eve::ModuleManager::getInstance<eve::filesystem::Filesystem>(
"Filesystem");
1065 if (!fs) fs = eve::filesystem::Filesystem::create();
1068 if (!readImportText(fs,
path,
text)) {
1073 std::string decodeError;
1075 if (!document.valid() || !document.root().isObject()) {
1076 if (
error) *
error = decodeError.empty() ?
"map.import.invalid-json" : decodeError;
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;
1089 *
layer->config() = oldConfig;
1090 *
layer->tiles() = oldTiles;
1091 *
layer->tileset() = oldTileset;
1092 *
layer->draw() = oldDraw;
1093 *
layer->resource() = oldResource;
1096 if (!tilesets.empty()) applyTilesets(
layer, tilesets);
1098 auto res =
layer->resource();
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");
1112 if (
auto *hot = eve::ModuleManager::getInstance<eve::filesystem::HotReload>(
"HotReload"))
1113 hot->bind(
path,
"tilemap");
1118 if (!
layer)
return false;
1119 const std::string &
path =
layer->resource()->path;
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;
1141 if (!data || data->getSize() == 0) {
1145 const std::string
text(
static_cast<const char *
>(data->getData()), data->getSize());
1146 std::string decodeError;
1148 if (!doc.valid() || !doc.root().isObject()) {
1149 if (
error) *
error = decodeError.empty() ?
"invalid tileset manifest" : decodeError;
1152 Json
root = doc.root();
1153 if (
root.has(
"tileset")) {
1155 if (!
root.isObject()) {
1156 if (
error) *
error =
"tileset must be an object";
1160 const TilesetInfo
info = readTilesetObject(
root);
1161 if (
info.image.empty()) {
1162 if (
error) *
error =
"tileset manifest has no image";
1167 if (
auto *hot = eve::ModuleManager::getInstance<eve::filesystem::HotReload>(
"HotReload"))
1168 hot->bind(
path,
"tilemap");
1173 std::string *
error) {
1176 if (!doc.valid() || !doc.root().isObject()) {
1177 if (
error) *
error = err.empty() ?
"invalid json" : err;
1180 return loadMapObject(doc.root(), {},
nullptr,
objects,
error);
1184 std::string *
error) {
1191 auto *fs = eve::ModuleManager::getInstance<eve::filesystem::Filesystem>(
"Filesystem");
1192 if (!fs) fs = eve::filesystem::Filesystem::create();
1195 if (!readImportText(fs,
path,
text)) {
1201 if (!doc.valid() || !doc.root().isObject()) {
1202 if (
error) *
error = err.empty() ?
"invalid json" : err;
AuthorityStoreHandleRef reference
std::unordered_map< std::string, QuestRuntime > entries
std::array< float, 3 > position
std::map< std::string, PropertyRule > properties
std::set< std::string > values
std::vector< WfcTile > tiles
AbilityActivationGroup group
std::vector< TileLayer::Tileset::TerrainRule > terrainRules
std::vector< TileLayer::Tileset::CustomData > customData
std::vector< TileLayer::Tileset::Visual > visuals
std::vector< TileLayer::Tileset::Animation > animations
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.
static Result success(T value)
Construct a successful result owning value.
static Result failure(Status status)
Construct a failed result from a structured status.
EVENGINE_API_FOUNDATION public API.
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.
static Document parse(const std::string &text, std::string *error=nullptr)
Parse.
EVENGINE_API_FOUNDATION public API.
ECS tile layer entity. Script mutates tile GIDs / tileset / draw; TileRenderSystem batch-draws atlas ...
void clear()
Clears the layer to empty.
float getTileWidth()
Tile size in pixels.
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).
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).
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)
float getCellGapX()
Horizontal and vertical world-space gaps between projected cells.
float getRenderSpacingY()
void setTileSize(float tileW, float tileH)
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.
void setTint(float r, float g, float b, float a=1.f)
static Document parse(const std::string &text, std::string *error=nullptr)
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.