@codexo/exojs-ldtk 0.19.1 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +5 -5
  2. package/dist/esm/LdtkData.d.ts +32 -2
  3. package/dist/esm/LdtkData.d.ts.map +1 -1
  4. package/dist/esm/LdtkData.js +1 -2
  5. package/dist/esm/LdtkData.js.map +1 -1
  6. package/dist/esm/LdtkMap.d.ts +4 -3
  7. package/dist/esm/LdtkMap.d.ts.map +1 -1
  8. package/dist/esm/LdtkMap.js +5 -5
  9. package/dist/esm/LdtkMap.js.map +1 -1
  10. package/dist/esm/LdtkProject.d.ts +12 -4
  11. package/dist/esm/LdtkProject.d.ts.map +1 -1
  12. package/dist/esm/LdtkProject.js +17 -8
  13. package/dist/esm/LdtkProject.js.map +1 -1
  14. package/dist/esm/index.d.ts.map +1 -1
  15. package/dist/esm/ldtkExtension.d.ts +2 -2
  16. package/dist/esm/ldtkExtension.d.ts.map +1 -1
  17. package/dist/esm/ldtkExtension.js +4 -5
  18. package/dist/esm/ldtkExtension.js.map +1 -1
  19. package/dist/esm/ldtkLevelEntries.d.ts.map +1 -1
  20. package/dist/esm/ldtkLevelEntries.js +1 -2
  21. package/dist/esm/ldtkLevelEntries.js.map +1 -1
  22. package/dist/esm/ldtkParallax.d.ts.map +1 -1
  23. package/dist/esm/ldtkParallax.js +1 -2
  24. package/dist/esm/ldtkToMapWorld.d.ts +1 -1
  25. package/dist/esm/ldtkToMapWorld.d.ts.map +1 -1
  26. package/dist/esm/ldtkToMapWorld.js +2 -3
  27. package/dist/esm/ldtkToMapWorld.js.map +1 -1
  28. package/dist/esm/ldtkToTileMap.d.ts +9 -4
  29. package/dist/esm/ldtkToTileMap.d.ts.map +1 -1
  30. package/dist/esm/ldtkToTileMap.js +34 -14
  31. package/dist/esm/ldtkToTileMap.js.map +1 -1
  32. package/dist/esm/ldtkTypes.d.ts.map +1 -1
  33. package/dist/esm/ldtkTypes.js +1 -2
  34. package/dist/esm/loadLdtkMap.d.ts.map +1 -1
  35. package/dist/esm/loadLdtkMap.js +50 -9
  36. package/dist/esm/loadLdtkMap.js.map +1 -1
  37. package/dist/esm/loadLdtkProject.d.ts.map +1 -1
  38. package/dist/esm/loadLdtkProject.js +6 -5
  39. package/dist/esm/loadLdtkProject.js.map +1 -1
  40. package/dist/esm/public.d.ts +4 -4
  41. package/dist/esm/public.d.ts.map +1 -1
  42. package/dist/esm/public.js +1 -1
  43. package/dist/esm/url.d.ts.map +1 -1
  44. package/dist/esm/url.js +1 -2
  45. package/dist/esm/validate.d.ts.map +1 -1
  46. package/dist/esm/validate.js +18 -4
  47. package/dist/esm/validate.js.map +1 -1
  48. package/package.json +5 -7
@@ -1 +1 @@
1
- {"version":3,"file":"ldtkToMapWorld.d.ts","sourceRoot":"","sources":["../../src/ldtkToMapWorld.ts"],"names":[],"mappings":"AACA,OAAO,EAAgB,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAE/D,OAAO,KAAK,EAAE,QAAQ,EAAa,MAAM,YAAY,CAAC;AAyCtD;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,cAAc,SAAU,QAAQ,KAAG,SAAS,QAAQ,EAgBhE,CAAC"}
1
+ {"version":3,"file":"ldtkToMapWorld.d.ts","sources":["../../src/ldtkToMapWorld.ts"],"names":[],"mappings":"AACA,OAAO,EAAgB,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAE/D,OAAO,KAAK,EAAE,QAAQ,EAAa,MAAM,YAAY,CAAC;AA4CtD;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,cAAc,SAAU,QAAQ,KAAG,SAAS,QAAQ,EAgBhE,CAAC"}
@@ -1,8 +1,8 @@
1
1
  import { getLdtkLevelEntries } from "./ldtkLevelEntries.js";
2
2
  import { buildLdtkLevelProperties } from "./ldtkToTileMap.js";
3
- import { MapLevelSide, MapWorld } from "@codexo/exojs-tilemap";
3
+ import { MapLevelSide, MapWorld } from "@codexo/exojs/tilemap";
4
4
 
5
- //#region src/ldtkToMapWorld.ts
5
+ // src/ldtkToMapWorld.ts
6
6
  /**
7
7
  * LDtk direction codes, as emitted in `__neighbours[].dir`. The cardinal four
8
8
  * have always existed; the depth relations arrived with LDtk 1.x.
@@ -71,6 +71,5 @@ const ldtkToMapWorld = (data) => {
71
71
  return Object.freeze([new MapWorld({ levels: entries.map((entry, index) => convertLevel(entry.level, entry.worldIid, index)) })]);
72
72
  };
73
73
 
74
- //#endregion
75
74
  export { ldtkToMapWorld };
76
75
  //# sourceMappingURL=ldtkToMapWorld.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ldtkToMapWorld.js","names":[],"sources":["../../src/ldtkToMapWorld.ts"],"sourcesContent":["import type { MapLevel, MapLevelNeighbour } from '@codexo/exojs-tilemap';\nimport { MapLevelSide, MapWorld } from '@codexo/exojs-tilemap';\n\nimport type { LdtkData, LdtkLevel } from './LdtkData';\nimport { getLdtkLevelEntries } from './ldtkLevelEntries';\nimport { buildLdtkLevelProperties } from './ldtkToTileMap';\n\n/**\n * LDtk direction codes, as emitted in `__neighbours[].dir`. The cardinal four\n * have always existed; the depth relations arrived with LDtk 1.x.\n */\nconst SIDE_BY_DIR: Readonly<Record<string, MapLevelSide>> = Object.freeze({\n n: MapLevelSide.North,\n s: MapLevelSide.South,\n e: MapLevelSide.East,\n w: MapLevelSide.West,\n o: MapLevelSide.Overlap,\n '<': MapLevelSide.Below,\n '>': MapLevelSide.Above,\n});\n\nconst convertNeighbours = (level: LdtkLevel): readonly MapLevelNeighbour[] => {\n const raw = level.__neighbours;\n if (raw === undefined || raw === null || raw.length === 0) return [];\n\n return raw.map(neighbour => ({\n id: neighbour.levelIid,\n // An unrecognised code still means the levels are adjacent, so the edge is\n // kept and only its side degrades - dropping it would lose real data if a\n // future LDtk adds a direction.\n side: SIDE_BY_DIR[neighbour.dir] ?? MapLevelSide.Unknown,\n }));\n};\n\nconst convertLevel = (level: LdtkLevel, worldIid: string | undefined, index: number): MapLevel => ({\n id: level.iid,\n name: level.identifier,\n index,\n bounds: { x: level.worldX, y: level.worldY, width: level.pxWid, height: level.pxHei },\n external: Boolean(level.externalRelPath),\n neighbours: convertNeighbours(level),\n properties: buildLdtkLevelProperties(level, worldIid),\n});\n\n/**\n * Build the format-neutral world model for an LDtk document: one\n * {@link MapWorld} per LDtk world, in document order.\n *\n * A single-world project - the overwhelmingly common shape - yields exactly one\n * unnamed world. A multi-world project yields one per entry of `worlds[]`, each\n * named by its identifier, and they stay separate on purpose: LDtk worlds have independent coordinate spaces, so merging them\n * would make {@link MapWorld.bounds} and {@link MapWorld.getLevelsInBounds}\n * report overlaps that do not exist.\n *\n * {@link MapLevel.index} counts across the whole document, matching the\n * flattened order {@link import('./LdtkMap').LdtkMap.levels} uses.\n *\n * Level metadata only: no layer payload is read, so this is safe to call on a\n * document whose external levels have not been fetched.\n */\nexport const ldtkToMapWorld = (data: LdtkData): readonly MapWorld[] => {\n const entries = getLdtkLevelEntries(data);\n\n if (data.worlds && data.worlds.length > 0) {\n const worlds: MapWorld[] = [];\n let index = 0;\n\n for (const world of data.worlds) {\n const levels = world.levels.map(level => convertLevel(level, world.iid, index++));\n worlds.push(new MapWorld({ name: world.identifier, levels }));\n }\n\n return Object.freeze(worlds);\n }\n\n return Object.freeze([new MapWorld({ levels: entries.map((entry, index) => convertLevel(entry.level, entry.worldIid, index)) })]);\n};\n"],"mappings":";;;;;;;;;AAWA,MAAM,cAAsD,OAAO,OAAO;CACxE,GAAG,aAAa;CAChB,GAAG,aAAa;CAChB,GAAG,aAAa;CAChB,GAAG,aAAa;CAChB,GAAG,aAAa;CAChB,KAAK,aAAa;CAClB,KAAK,aAAa;AACpB,CAAC;AAED,MAAM,qBAAqB,UAAmD;CAC5E,MAAM,MAAM,MAAM;CAClB,IAAI,QAAQ,UAAa,QAAQ,QAAQ,IAAI,WAAW,GAAG,OAAO,CAAC;CAEnE,OAAO,IAAI,KAAI,eAAc;EAC3B,IAAI,UAAU;EAId,MAAM,YAAY,UAAU,QAAQ,aAAa;CACnD,EAAE;AACJ;AAEA,MAAM,gBAAgB,OAAkB,UAA8B,WAA6B;CACjG,IAAI,MAAM;CACV,MAAM,MAAM;CACZ;CACA,QAAQ;EAAE,GAAG,MAAM;EAAQ,GAAG,MAAM;EAAQ,OAAO,MAAM;EAAO,QAAQ,MAAM;CAAM;CACpF,UAAU,QAAQ,MAAM,eAAe;CACvC,YAAY,kBAAkB,KAAK;CACnC,YAAY,yBAAyB,OAAO,QAAQ;AACtD;;;;;;;;;;;;;;;;;AAkBA,MAAa,kBAAkB,SAAwC;CACrE,MAAM,UAAU,oBAAoB,IAAI;CAExC,IAAI,KAAK,UAAU,KAAK,OAAO,SAAS,GAAG;EACzC,MAAM,SAAqB,CAAC;EAC5B,IAAI,QAAQ;EAEZ,KAAK,MAAM,SAAS,KAAK,QAAQ;GAC/B,MAAM,SAAS,MAAM,OAAO,KAAI,UAAS,aAAa,OAAO,MAAM,KAAK,OAAO,CAAC;GAChF,OAAO,KAAK,IAAI,SAAS;IAAE,MAAM,MAAM;IAAY;GAAO,CAAC,CAAC;EAC9D;EAEA,OAAO,OAAO,OAAO,MAAM;CAC7B;CAEA,OAAO,OAAO,OAAO,CAAC,IAAI,SAAS,EAAE,QAAQ,QAAQ,KAAK,OAAO,UAAU,aAAa,MAAM,OAAO,MAAM,UAAU,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC;AAClI"}
1
+ {"version":3,"file":"ldtkToMapWorld.js","names":[],"sources":["../../src/ldtkToMapWorld.ts"],"sourcesContent":["import type { MapLevel, MapLevelNeighbour } from '@codexo/exojs/tilemap';\nimport { MapLevelSide, MapWorld } from '@codexo/exojs/tilemap';\n\nimport type { LdtkData, LdtkLevel } from './LdtkData';\nimport { getLdtkLevelEntries } from './ldtkLevelEntries';\nimport { buildLdtkLevelProperties } from './ldtkToTileMap';\n\n/**\n * LDtk direction codes, as emitted in `__neighbours[].dir`. The cardinal four\n * have always existed; the depth relations arrived with LDtk 1.x.\n */\nconst SIDE_BY_DIR: Readonly<Record<string, MapLevelSide>> = Object.freeze({\n n: MapLevelSide.North,\n s: MapLevelSide.South,\n e: MapLevelSide.East,\n w: MapLevelSide.West,\n o: MapLevelSide.Overlap,\n '<': MapLevelSide.Below,\n '>': MapLevelSide.Above,\n});\n\nconst convertNeighbours = (level: LdtkLevel): readonly MapLevelNeighbour[] => {\n const raw = level.__neighbours;\n\n if (raw === undefined || raw === null || raw.length === 0) {\n return [];\n }\n\n return raw.map(neighbour => ({\n id: neighbour.levelIid,\n // An unrecognised code still means the levels are adjacent, so the edge is\n // kept and only its side degrades - dropping it would lose real data if a\n // future LDtk adds a direction.\n side: SIDE_BY_DIR[neighbour.dir] ?? MapLevelSide.Unknown,\n }));\n};\n\nconst convertLevel = (level: LdtkLevel, worldIid: string | undefined, index: number): MapLevel => ({\n id: level.iid,\n name: level.identifier,\n index,\n bounds: { x: level.worldX, y: level.worldY, width: level.pxWid, height: level.pxHei },\n external: Boolean(level.externalRelPath),\n neighbours: convertNeighbours(level),\n properties: buildLdtkLevelProperties(level, worldIid),\n});\n\n/**\n * Build the format-neutral world model for an LDtk document: one\n * {@link MapWorld} per LDtk world, in document order.\n *\n * A single-world project - the overwhelmingly common shape - yields exactly one\n * unnamed world. A multi-world project yields one per entry of `worlds[]`, each\n * named by its identifier, and they stay separate on purpose: LDtk worlds have independent coordinate spaces, so merging them\n * would make {@link MapWorld.bounds} and {@link MapWorld.getLevelsInBounds}\n * report overlaps that do not exist.\n *\n * {@link MapLevel.index} counts across the whole document, matching the\n * flattened order {@link import('./LdtkMap').LdtkMap.levels} uses.\n *\n * Level metadata only: no layer payload is read, so this is safe to call on a\n * document whose external levels have not been fetched.\n */\nexport const ldtkToMapWorld = (data: LdtkData): readonly MapWorld[] => {\n const entries = getLdtkLevelEntries(data);\n\n if (data.worlds && data.worlds.length > 0) {\n const worlds: MapWorld[] = [];\n let index = 0;\n\n for (const world of data.worlds) {\n const levels = world.levels.map(level => convertLevel(level, world.iid, index++));\n worlds.push(new MapWorld({ name: world.identifier, levels }));\n }\n\n return Object.freeze(worlds);\n }\n\n return Object.freeze([new MapWorld({ levels: entries.map((entry, index) => convertLevel(entry.level, entry.worldIid, index)) })]);\n};\n"],"mappings":";;;;;;;;;AAWA,MAAM,cAAsD,OAAO,OAAO;CACxE,GAAG,aAAa;CAChB,GAAG,aAAa;CAChB,GAAG,aAAa;CAChB,GAAG,aAAa;CAChB,GAAG,aAAa;CAChB,KAAK,aAAa;CAClB,KAAK,aAAa;AACpB,CAAC;AAED,MAAM,qBAAqB,UAAmD;CAC5E,MAAM,MAAM,MAAM;CAElB,IAAI,QAAQ,UAAa,QAAQ,QAAQ,IAAI,WAAW,GACtD,OAAO,CAAC;CAGV,OAAO,IAAI,KAAI,eAAc;EAC3B,IAAI,UAAU;EAId,MAAM,YAAY,UAAU,QAAQ,aAAa;CACnD,EAAE;AACJ;AAEA,MAAM,gBAAgB,OAAkB,UAA8B,WAA6B;CACjG,IAAI,MAAM;CACV,MAAM,MAAM;CACZ;CACA,QAAQ;EAAE,GAAG,MAAM;EAAQ,GAAG,MAAM;EAAQ,OAAO,MAAM;EAAO,QAAQ,MAAM;CAAM;CACpF,UAAU,QAAQ,MAAM,eAAe;CACvC,YAAY,kBAAkB,KAAK;CACnC,YAAY,yBAAyB,OAAO,QAAQ;AACtD;;;;;;;;;;;;;;;;;AAkBA,MAAa,kBAAkB,SAAwC;CACrE,MAAM,UAAU,oBAAoB,IAAI;CAExC,IAAI,KAAK,UAAU,KAAK,OAAO,SAAS,GAAG;EACzC,MAAM,SAAqB,CAAC;EAC5B,IAAI,QAAQ;EAEZ,KAAK,MAAM,SAAS,KAAK,QAAQ;GAC/B,MAAM,SAAS,MAAM,OAAO,KAAI,UAAS,aAAa,OAAO,MAAM,KAAK,OAAO,CAAC;GAChF,OAAO,KAAK,IAAI,SAAS;IAAE,MAAM,MAAM;IAAY;GAAO,CAAC,CAAC;EAC9D;EAEA,OAAO,OAAO,OAAO,MAAM;CAC7B;CAEA,OAAO,OAAO,OAAO,CAAC,IAAI,SAAS,EAAE,QAAQ,QAAQ,KAAK,OAAO,UAAU,aAAa,MAAM,OAAO,MAAM,UAAU,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC;AAClI"}
@@ -1,5 +1,5 @@
1
- import type { TileCellSource, TileSet } from '@codexo/exojs-tilemap';
2
- import { TILE_TRANSFORM_IDENTITY, TileLayer } from '@codexo/exojs-tilemap';
1
+ import type { TileCellSource, TileSet } from '@codexo/exojs/tilemap';
2
+ import { TILE_TRANSFORM_IDENTITY, TileLayer } from '@codexo/exojs/tilemap';
3
3
  import type { LdtkData, LdtkIntGridValueDef } from './LdtkData';
4
4
  import { LdtkMap } from './LdtkMap';
5
5
  /**
@@ -16,8 +16,9 @@ export interface LdtkToTileMapOptions {
16
16
  *
17
17
  * When provided, tile layers are populated with tile data from
18
18
  * `gridTiles` / `autoLayerTiles`. Without this map, tile layers are created
19
- * with the correct dimensions but no tiles are placed - only entity and
20
- * object layers carry data.
19
+ * with the correct dimensions but no tiles are placed; IntGrid layers still
20
+ * expose their raw CSV and value definitions, and level/entity metadata is
21
+ * unaffected.
21
22
  *
22
23
  * Populate via {@link import('./loadLdtkMap').loadLdtkMap} for asset-loading
23
24
  * flows, or pass a hand-crafted map for testing.
@@ -36,6 +37,10 @@ export interface LdtkToTileMapOptions {
36
37
  * Pass `options.tilesets` to populate tile data; omit it for structure-only
37
38
  * conversion (useful in unit tests that do not need textures).
38
39
  *
40
+ * Externalized levels (`layerInstances: null`) convert to empty maps -
41
+ * resolve their `.ldtkl` payloads through `loadLdtkMap` or
42
+ * {@link import('./LdtkProject').LdtkProject}.
43
+ *
39
44
  * Transparently handles both LDtk root shapes via {@link getLdtkLevelEntries}:
40
45
  * single-world (`data.levels`) and multi-world (`data.worlds[].levels`) - in
41
46
  * the latter case every converted level's `TileMap.properties` is additionally
@@ -1 +1 @@
1
- {"version":3,"file":"ldtkToT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AO,KAAK,EACV,QAAQ,EAIR,mBAAmB,EAIpB,MAAM,YAAY,CAAC;AAGpB,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAMpC;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACnC;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB;;;;;;;;;;;OAWG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,WAAW,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAClD;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,aAAa,SAAU,QAAQ,YAAY,oBAAoB,KAAG,OAS9E,CAAC;AAuOF;;;;;GAKG;AACH,eAAO,MAAM,sBAAsB,mBAAmB,CAAC;AAEvD;;;;;;GAMG;AACH,eAAO,MAAM,yBAAyB,sBAAsB,CAAC;AA2E7D;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,qBAAqB,UAAW,SAAS,KAAK,MAAM,KAAK,MAAM,KAAG,mBAAmB,GAAG,SAuBpG,CAAC;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,2BAA2B,UAAW,SAAS,KAAG,cAAc,GAAG,SA6B/E,CAAC;AAkOF,OAAO,EAAE,uBAAuB,EAAE,CAAC"}
@@ -1,10 +1,10 @@
1
- import { getLdtkLevelEntries } from "./ldtkLevelEntries.js";
2
1
  import { LDTK_FLIP_X, LDTK_FLIP_Y, isLdtkFieldEnumType } from "./LdtkData.js";
3
- import { resolveLdtkLayerParallax } from "./ldtkParallax.js";
2
+ import { getLdtkLevelEntries } from "./ldtkLevelEntries.js";
4
3
  import { LdtkMap } from "./LdtkMap.js";
5
- import { ObjectLayer, TileLayer, TileMap, TilePropertyKind } from "@codexo/exojs-tilemap";
4
+ import { resolveLdtkLayerParallax } from "./ldtkParallax.js";
5
+ import { ObjectLayer, TileLayer, TileMap, TilePropertyKind } from "@codexo/exojs/tilemap";
6
6
 
7
- //#region src/ldtkToTileMap.ts
7
+ // src/ldtkToTileMap.ts
8
8
  /**
9
9
  * Convert a raw {@link LdtkData} document into an {@link LdtkMap} containing
10
10
  * one runtime {@link TileMap} per LDtk level.
@@ -17,6 +17,10 @@ import { ObjectLayer, TileLayer, TileMap, TilePropertyKind } from "@codexo/exojs
17
17
  * Pass `options.tilesets` to populate tile data; omit it for structure-only
18
18
  * conversion (useful in unit tests that do not need textures).
19
19
  *
20
+ * Externalized levels (`layerInstances: null`) convert to empty maps -
21
+ * resolve their `.ldtkl` payloads through `loadLdtkMap` or
22
+ * {@link import('./LdtkProject').LdtkProject}.
23
+ *
20
24
  * Transparently handles both LDtk root shapes via {@link getLdtkLevelEntries}:
21
25
  * single-world (`data.levels`) and multi-world (`data.worlds[].levels`) - in
22
26
  * the latter case every converted level's `TileMap.properties` is additionally
@@ -70,9 +74,12 @@ const convertLevel = (level, worldIid, levelIndex, data, tilesets) => {
70
74
  tilesets: runtimeTilesets,
71
75
  layers: runtimeLayers,
72
76
  objectLayers: runtimeObjectLayers,
77
+ backgroundColor: parseLdtkColor(level.__bgColor ?? level.bgColor ?? data.defaultLevelBgColor),
73
78
  properties: buildLdtkLevelProperties(level, worldIid)
74
79
  });
75
80
  };
81
+ /** A `#rrggbb` LDtk colour as `0xRRGGBB`, or `null` when absent or malformed. */
82
+ const parseLdtkColor = (color) => color !== null && color !== void 0 && /^#[\da-f]{6}$/i.test(color) ? Number.parseInt(color.slice(1), 16) : null;
76
83
  /**
77
84
  * The property bag a level contributes to its runtime representation - user
78
85
  * fields first, then the reserved LDtk keys, so a same-named user field can
@@ -192,7 +199,7 @@ const ldtkIntGridValuesProperty = "ldtkIntGridValues";
192
199
  */
193
200
  const buildIntGridProperties = (layerInst, data) => {
194
201
  const csv = layerInst.intGridCsv;
195
- if (!csv || csv.length === 0) return void 0;
202
+ if (!csv || csv.length === 0) return;
196
203
  const values = data.defs.layers.find((def) => def.uid === layerInst.layerDefUid)?.intGridValues ?? [];
197
204
  return Object.freeze({
198
205
  [ldtkIntGridCsvProperty]: JSON.stringify(csv),
@@ -220,7 +227,7 @@ const getParsedIntGridData = (layer) => {
220
227
  if (cached) return cached;
221
228
  const csvRaw = layer.properties[ldtkIntGridCsvProperty];
222
229
  const valuesRaw = layer.properties[ldtkIntGridValuesProperty];
223
- if (typeof csvRaw !== "string" || typeof valuesRaw !== "string") return void 0;
230
+ if (typeof csvRaw !== "string" || typeof valuesRaw !== "string") return;
224
231
  const parsed = {
225
232
  csv: JSON.parse(csvRaw),
226
233
  values: JSON.parse(valuesRaw)
@@ -242,11 +249,11 @@ const getParsedIntGridData = (layer) => {
242
249
  * hot path (e.g. per-cell or per-frame collision/classification checks).
243
250
  */
244
251
  const getLdtkIntGridValueAt = (layer, x, y) => {
245
- if (!layer.inBounds(x, y) || layer.width === void 0) return void 0;
252
+ if (!layer.inBounds(x, y) || layer.width === void 0) return;
246
253
  const parsed = getParsedIntGridData(layer);
247
- if (!parsed) return void 0;
254
+ if (!parsed) return;
248
255
  const raw = parsed.csv[y * layer.width + x];
249
- if (raw === void 0 || raw === 0) return void 0;
256
+ if (raw === void 0 || raw === 0) return;
250
257
  return parsed.values.find((v) => v.value === raw);
251
258
  };
252
259
  /**
@@ -271,7 +278,7 @@ const getLdtkIntGridValueAt = (layer, x, y) => {
271
278
  const createLdtkIntGridCellSource = (layer) => {
272
279
  const parsed = getParsedIntGridData(layer);
273
280
  const width = layer.width;
274
- if (!parsed || width === void 0) return void 0;
281
+ if (!parsed || width === void 0) return;
275
282
  const identifiers = /* @__PURE__ */ new Map();
276
283
  for (const value of parsed.values) identifiers.set(value.value, value.identifier ?? String(value.value));
277
284
  return (tx, ty) => {
@@ -307,11 +314,25 @@ const convertEntity = (entity, id) => {
307
314
  height: entity.height,
308
315
  rotation: 0,
309
316
  visible: true,
310
- properties: convertFieldInstances(entity.fieldInstances),
317
+ properties: buildLdtkEntityProperties(entity),
311
318
  source: entity
312
319
  };
313
320
  };
314
321
  /**
322
+ * An entity's property bag: its fields, then `ldtkTags` - the tags of its
323
+ * definition - when it has any, so spawn code can dispatch on a tag such as
324
+ * `Enemy` without reading the raw entity. Like the level keys, the reserved
325
+ * key wins over a same-named field.
326
+ */
327
+ const buildLdtkEntityProperties = (entity) => {
328
+ const properties = convertFieldInstances(entity.fieldInstances);
329
+ const tags = entity.__tags ?? [];
330
+ return tags.length === 0 ? properties : {
331
+ ...properties,
332
+ ldtkTags: [...tags]
333
+ };
334
+ };
335
+ /**
315
336
  * Project LDtk field instances to a flat {@link TileProperties} bag.
316
337
  * Every LDtk field type maps to a canonical {@link TilePropertyValue}
317
338
  * (scalars and enum entries pass through as their raw value;
@@ -355,7 +376,7 @@ const convertField = (field) => {
355
376
  }
356
377
  if (isLdtkEnumField(field)) return mapLdtkFieldValue(field.__type, field.__value);
357
378
  if (isLdtkArrayField(field)) {
358
- if (field.__value === null) return void 0;
379
+ if (field.__value === null) return;
359
380
  const elementType = field.__type.slice(6, -1);
360
381
  const elements = [];
361
382
  for (const raw of field.__value) {
@@ -376,7 +397,7 @@ const convertField = (field) => {
376
397
  * unsupported field type is never mistaken for an absent or empty one.
377
398
  */
378
399
  const mapLdtkFieldValue = (typeName, value) => {
379
- if (value === null || value === void 0) return void 0;
400
+ if (value === null || value === void 0) return;
380
401
  if (isLdtkFieldEnumType(typeName)) return value;
381
402
  switch (typeName) {
382
403
  case "Int":
@@ -425,6 +446,5 @@ const pickLevelGridSize = (level, fallback) => {
425
446
  return fallback;
426
447
  };
427
448
 
428
- //#endregion
429
449
  export { buildLdtkLevelProperties, createLdtkIntGridCellSource, getLdtkIntGridValueAt, ldtkIntGridCsvProperty, ldtkIntGridValuesProperty, ldtkLevelToTileMap, ldtkToTileMap };
430
450
  //# sourceMappingURL=ldtkToTileMap.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ldtkToTileMap.js","names":[],"sources":["../../src/ldtkToTileMap.ts"],"sourcesContent":["import type { TileCellSource, TileMapObject, TileProperties, TilePropertyValue, TileSet } from '@codexo/exojs-tilemap';\nimport { ObjectLayer, TILE_TRANSFORM_IDENTITY, TileLayer, TileMap, TilePropertyKind } from '@codexo/exojs-tilemap';\n\nimport type {\n LdtkData,\n LdtkEntityInstance,\n LdtkFieldEnumType,\n LdtkFieldInstance,\n LdtkIntGridValueDef,\n LdtkLayerInstance,\n LdtkLevel,\n LdtkTileData,\n} from './LdtkData';\nimport { isLdtkFieldEnumType, LDTK_FLIP_X, LDTK_FLIP_Y } from './LdtkData';\nimport { getLdtkLevelEntries } from './ldtkLevelEntries';\nimport { LdtkMap } from './LdtkMap';\nimport type { LdtkLayerParallax } from './ldtkParallax';\nimport { resolveLdtkLayerParallax } from './ldtkParallax';\n\n// ── Public API ────────────────────────────────────────────────────────────────\n\n/**\n * Options for {@link ldtkToTileMap}.\n */\nexport interface LdtkToTileMapOptions {\n /**\n * Source URL of the loaded `.ldtk` file, used as {@link LdtkMap.source}.\n * Defaults to an empty string when omitted (e.g. programmatic / test usage).\n */\n readonly source?: string;\n /**\n * Pre-loaded runtime {@link TileSet}s keyed by LDtk tileset UID.\n *\n * When provided, tile layers are populated with tile data from\n * `gridTiles` / `autoLayerTiles`. Without this map, tile layers are created\n * with the correct dimensions but no tiles are placed - only entity and\n * object layers carry data.\n *\n * Populate via {@link import('./loadLdtkMap').loadLdtkMap} for asset-loading\n * flows, or pass a hand-crafted map for testing.\n */\n readonly tilesets?: ReadonlyMap<number, TileSet>;\n}\n\n/**\n * Convert a raw {@link LdtkData} document into an {@link LdtkMap} containing\n * one runtime {@link TileMap} per LDtk level.\n *\n * Tile layers (`Tiles` / `AutoLayer`) become renderable `TileLayer`s. IntGrid\n * layers become dimension-correct `TileLayer`s - tile data is placed only when\n * the layer carries `autoLayerTiles`. Entity layers become data-only\n * `ObjectLayer`s with entity position, size, and scalar field properties.\n *\n * Pass `options.tilesets` to populate tile data; omit it for structure-only\n * conversion (useful in unit tests that do not need textures).\n *\n * Transparently handles both LDtk root shapes via {@link getLdtkLevelEntries}:\n * single-world (`data.levels`) and multi-world (`data.worlds[].levels`) - in\n * the latter case every converted level's `TileMap.properties` is additionally\n * tagged with its owning world's iid under the reserved `ldtkWorldIid` key.\n */\nexport const ldtkToTileMap = (data: LdtkData, options?: LdtkToTileMapOptions): LdtkMap => {\n const source = options?.source ?? '';\n const tilesets = options?.tilesets ?? new Map<number, TileSet>();\n\n const levels = getLdtkLevelEntries(data).map((entry, levelIndex) => convertLevel(entry.level, entry.worldIid, levelIndex, data, tilesets));\n\n return new LdtkMap(source, data, levels);\n};\n\n// ── Level conversion ──────────────────────────────────────────────────────────\n\n/**\n * Convert one already-resolved LDtk level into its runtime {@link TileMap}.\n *\n * `level.layerInstances` must be present: an externalized level has to have its\n * `.ldtkl` payload merged in first, or the result is an empty map.\n * @internal\n */\nexport const ldtkLevelToTileMap = (\n level: LdtkLevel,\n worldIid: string | undefined,\n levelIndex: number,\n data: LdtkData,\n tilesets: ReadonlyMap<number, TileSet>,\n): TileMap => convertLevel(level, worldIid, levelIndex, data, tilesets);\n\nconst convertLevel = (level: LdtkLevel, worldIid: string | undefined, levelIndex: number, data: LdtkData, tilesets: ReadonlyMap<number, TileSet>): TileMap => {\n // Derive map-level tile size from the first non-entity layer, or fall back.\n const gridSize = pickLevelGridSize(level, data.defaultGridSize ?? 16);\n const mapWidth = Math.max(1, Math.ceil(level.pxWid / gridSize));\n const mapHeight = Math.max(1, Math.ceil(level.pxHei / gridSize));\n\n const runtimeTilesets: TileSet[] = [...tilesets.values()];\n const runtimeLayers: TileLayer[] = [];\n const runtimeObjectLayers: ObjectLayer[] = [];\n\n // LDtk stores layers top-to-bottom (first = top-most); preserve that order.\n const layerInstances = level.layerInstances ?? [];\n let entityCounter = 0;\n\n for (const layerInst of layerInstances) {\n // Layer IDs must be unique within a TileMap (= one level).\n // Use layerDefUid directly - it is unique per layer definition in the file.\n const layerId = layerInst.layerDefUid;\n const parallax = resolveLdtkLayerParallax(data, layerInst);\n\n switch (layerInst.__type) {\n case 'Tiles':\n case 'AutoLayer':\n runtimeLayers.push(convertTilesOrAutoLayer(layerInst, layerId, runtimeTilesets, tilesets, parallax));\n break;\n\n case 'IntGrid':\n runtimeLayers.push(convertIntGridLayer(layerInst, layerId, runtimeTilesets, tilesets, data, parallax));\n break;\n\n case 'Entities':\n runtimeObjectLayers.push(convertEntitiesLayer(layerInst, layerId, levelIndex, entityCounter, parallax));\n entityCounter += layerInst.entityInstances?.length ?? 0;\n break;\n }\n }\n\n return new TileMap({\n name: level.identifier,\n width: mapWidth,\n height: mapHeight,\n tileWidth: gridSize,\n tileHeight: gridSize,\n tilesets: runtimeTilesets,\n layers: runtimeLayers,\n objectLayers: runtimeObjectLayers,\n properties: buildLdtkLevelProperties(level, worldIid),\n });\n};\n\n/**\n * The property bag a level contributes to its runtime representation - user\n * fields first, then the reserved LDtk keys, so a same-named user field can\n * never clobber them. `ldtkWorldIid` is added only for multi-world documents;\n * a single-world document's properties stay exactly as they were before\n * multi-world support existed.\n * @internal\n */\nexport const buildLdtkLevelProperties = (level: LdtkLevel, worldIid: string | undefined): TileProperties => ({\n ...convertFieldInstances(level.fieldInstances ?? []),\n ldtkUid: level.uid,\n ldtkIid: level.iid,\n worldX: level.worldX,\n worldY: level.worldY,\n ...(worldIid !== undefined && { ldtkWorldIid: worldIid }),\n});\n\n// ── Helpers: per-layer-type level conversion ─────────────────────────────────\n\n/** Convert a `Tiles`/`AutoLayer` LDtk layer instance into a runtime {@link TileLayer}. */\nconst convertTilesOrAutoLayer = (\n layerInst: LdtkLayerInstance,\n layerId: number,\n runtimeTilesets: readonly TileSet[],\n tilesets: ReadonlyMap<number, TileSet>,\n parallax: LdtkLayerParallax,\n): TileLayer => {\n const rLayer = makeTileLayer(layerInst, layerId, runtimeTilesets, parallax);\n const tiles = layerInst.__type === 'Tiles' ? (layerInst.gridTiles ?? []) : (layerInst.autoLayerTiles ?? []);\n const tsUid = layerInst.__tilesetDefUid;\n if (tsUid !== undefined && tsUid !== null) {\n const rts = tilesets.get(tsUid);\n if (rts) populateTileLayer(rLayer, tiles, rts, layerInst.__gridSize);\n }\n return rLayer;\n};\n\n/** Convert an `IntGrid` LDtk layer instance into a runtime {@link TileLayer}. */\nconst convertIntGridLayer = (\n layerInst: LdtkLayerInstance,\n layerId: number,\n runtimeTilesets: readonly TileSet[],\n tilesets: ReadonlyMap<number, TileSet>,\n data: LdtkData,\n parallax: LdtkLayerParallax,\n): TileLayer => {\n const intGridProperties = buildIntGridProperties(layerInst, data);\n const rLayer = makeTileLayer(layerInst, layerId, runtimeTilesets, parallax, intGridProperties);\n // IntGrid layers may carry auto-tiles when \"Auto-layer\" rules are\n // configured. Use those for rendering; raw intGridCsv is exposed as\n // data-only layer properties (see buildIntGridProperties).\n const autoTiles = layerInst.autoLayerTiles ?? [];\n const tsUid = layerInst.__tilesetDefUid;\n if (autoTiles.length > 0 && tsUid !== undefined && tsUid !== null) {\n const rts = tilesets.get(tsUid);\n if (rts) populateTileLayer(rLayer, autoTiles, rts, layerInst.__gridSize);\n }\n return rLayer;\n};\n\n/** Convert an `Entities` LDtk layer instance into a runtime {@link ObjectLayer}. */\nconst convertEntitiesLayer = (\n layerInst: LdtkLayerInstance,\n layerId: number,\n levelIndex: number,\n entityCounter: number,\n parallax: LdtkLayerParallax,\n): ObjectLayer => {\n const objects = convertEntityLayer(layerInst, layerInst.__gridSize, levelIndex, entityCounter);\n return new ObjectLayer({\n id: layerId,\n name: layerInst.__identifier,\n visible: layerInst.visible,\n opacity: layerInst.opacity ?? 1,\n offsetX: parallax.offsetX + (layerInst.pxOffsetX ?? 0),\n offsetY: parallax.offsetY + (layerInst.pxOffsetY ?? 0),\n parallaxX: parallax.parallaxX,\n parallaxY: parallax.parallaxY,\n parallaxScale: parallax.parallaxScale,\n objects,\n });\n};\n\n// ── Helpers: TileLayer ────────────────────────────────────────────────────────\n\nconst makeTileLayer = (\n layerInst: LdtkLayerInstance,\n layerId: number,\n tilesets: readonly TileSet[],\n parallax: LdtkLayerParallax,\n properties?: TileProperties,\n): TileLayer =>\n new TileLayer({\n id: layerId,\n name: layerInst.__identifier,\n width: layerInst.__cWid,\n height: layerInst.__cHei,\n tilesets,\n tileWidth: layerInst.__gridSize,\n tileHeight: layerInst.__gridSize,\n visible: layerInst.visible,\n opacity: layerInst.opacity ?? 1,\n offsetX: parallax.offsetX + (layerInst.pxOffsetX ?? 0),\n offsetY: parallax.offsetY + (layerInst.pxOffsetY ?? 0),\n parallaxX: parallax.parallaxX,\n parallaxY: parallax.parallaxY,\n parallaxScale: parallax.parallaxScale,\n ...(properties && { properties }),\n });\n\nconst populateTileLayer = (layer: TileLayer, tiles: readonly LdtkTileData[], tileset: TileSet, gridSize: number): void => {\n for (const tile of tiles) {\n const tx = Math.floor(tile.px[0] / gridSize);\n const ty = Math.floor(tile.px[1] / gridSize);\n if (!layer.inBounds(tx, ty)) continue;\n\n const localTileId = tile.t;\n if (localTileId < 0 || localTileId >= tileset.tileCount) continue;\n\n const f = tile.f;\n layer.setTileAt(tx, ty, {\n tileset,\n localTileId,\n transform: {\n flipX: (f & LDTK_FLIP_X) !== 0,\n flipY: (f & LDTK_FLIP_Y) !== 0,\n diagonal: false,\n },\n });\n }\n};\n\n// ── Helpers: IntGrid ──────────────────────────────────────────────────────────\n\n/**\n * Reserved {@link TileLayer.properties} key holding the JSON-encoded raw\n * IntGrid CSV array (`readonly number[]`) for a `TileLayer` converted from an\n * LDtk `IntGrid` layer instance. Index = `y * layer.width + x`; `0` = empty.\n * Prefer {@link getLdtkIntGridValueAt} over reading this directly.\n */\nexport const ldtkIntGridCsvProperty = 'ldtkIntGridCsv';\n\n/**\n * Reserved {@link TileLayer.properties} key holding the JSON-encoded\n * {@link LdtkIntGridValueDef} array for a `TileLayer` converted from an LDtk\n * `IntGrid` layer instance - the raw-int → named/coloured mapping declared on\n * the owning layer definition (`data.defs.layers[].intGridValues`).\n * Prefer {@link getLdtkIntGridValueAt} over reading this directly.\n */\nexport const ldtkIntGridValuesProperty = 'ldtkIntGridValues';\n\n/**\n * Build the reserved IntGrid properties for a `TileLayer` from an LDtk\n * `IntGrid` layer instance, or `undefined` when the layer carries no\n * `intGridCsv` data (nothing to expose).\n *\n * {@link TileLayer.properties} values are scalar-only, so the raw CSV array\n * and the value-definition mapping are JSON-encoded into two reserved string\n * properties rather than stored as nested structures - the same\n * `properties`-bag mechanism the Tiled adapter already uses for per-layer\n * metadata, just serialized to fit its scalar-only value type.\n */\nconst buildIntGridProperties = (layerInst: LdtkLayerInstance, data: LdtkData): TileProperties | undefined => {\n const csv = layerInst.intGridCsv;\n if (!csv || csv.length === 0) return undefined;\n\n const layerDef = data.defs.layers.find(def => def.uid === layerInst.layerDefUid);\n const values = layerDef?.intGridValues ?? [];\n\n return Object.freeze({\n [ldtkIntGridCsvProperty]: JSON.stringify(csv),\n [ldtkIntGridValuesProperty]: JSON.stringify(values),\n });\n};\n\n/** Parsed, cached form of a `TileLayer`'s {@link ldtkIntGridCsvProperty} / {@link ldtkIntGridValuesProperty}. */\ninterface ParsedIntGridData {\n readonly csv: readonly number[];\n readonly values: readonly LdtkIntGridValueDef[];\n}\n\n/**\n * Per-`TileLayer` cache of parsed IntGrid CSV/value-defs data, populated\n * lazily on first {@link getLdtkIntGridValueAt} lookup for a given layer.\n *\n * Keyed by the `TileLayer` instance itself (`WeakMap`), so an entry is\n * naturally garbage-collected once the layer it was derived from is no\n * longer referenced - no manual invalidation needed since\n * {@link TileLayer.properties} is frozen and copied at construction time and\n * can never change afterwards.\n */\nconst intGridCache = new WeakMap<TileLayer, ParsedIntGridData>();\n\n/**\n * Parse (or retrieve from {@link intGridCache}) the IntGrid CSV/value-defs\n * data attached to `layer`, or `undefined` when `layer` carries no such data\n * (not converted from an IntGrid layer instance).\n */\nconst getParsedIntGridData = (layer: TileLayer): ParsedIntGridData | undefined => {\n const cached = intGridCache.get(layer);\n if (cached) return cached;\n\n const csvRaw = layer.properties[ldtkIntGridCsvProperty];\n const valuesRaw = layer.properties[ldtkIntGridValuesProperty];\n if (typeof csvRaw !== 'string' || typeof valuesRaw !== 'string') return undefined;\n\n const parsed: ParsedIntGridData = {\n csv: JSON.parse(csvRaw) as readonly number[],\n values: JSON.parse(valuesRaw) as readonly LdtkIntGridValueDef[],\n };\n intGridCache.set(layer, parsed);\n return parsed;\n};\n\n/**\n * Look up the named/coloured {@link LdtkIntGridValueDef} at a tile coordinate\n * on a `TileLayer` converted from an LDtk `IntGrid` layer instance.\n *\n * Returns `undefined` when the coordinate is out of bounds, the cell's raw\n * value is `0` (empty), the raw value has no matching definition, or `layer`\n * was not converted from an IntGrid layer instance (no IntGrid data attached\n * via {@link ldtkIntGridCsvProperty} / {@link ldtkIntGridValuesProperty}).\n *\n * The underlying JSON-encoded CSV/value-defs properties are parsed once per\n * layer and cached (see {@link getParsedIntGridData}) - safe to call from a\n * hot path (e.g. per-cell or per-frame collision/classification checks).\n */\nexport const getLdtkIntGridValueAt = (layer: TileLayer, x: number, y: number): LdtkIntGridValueDef | undefined => {\n // `inBounds()` is unconditionally true for an unbounded layer (it has no\n // fixed grid to be out of), but the flat IntGrid CSV this function reads\n // is inherently a bounded-grid concept - LDtk itself only ever produces\n // bounded layers today, but `layer` is typed generically, so guard here\n // rather than let `layer.width` narrow away from `number | undefined`.\n if (!layer.inBounds(x, y) || layer.width === undefined) return undefined;\n\n const parsed = getParsedIntGridData(layer);\n if (!parsed) return undefined;\n\n const raw = parsed.csv[y * layer.width + x];\n if (raw === undefined || raw === 0) return undefined;\n\n return parsed.values.find(v => v.value === raw);\n};\n\n/**\n * Per-cell collision classification for a `TileLayer` converted from an LDtk\n * `IntGrid` layer instance, or `undefined` when the layer carries no IntGrid\n * data (not converted from an IntGrid layer instance, or unbounded).\n *\n * The classification is the value's LDtk-authored identifier, falling back to\n * the raw integer as a string when the value definition declares none. Cells\n * whose raw value is `0` (empty) classify as `null`. Distinct IntGrid values\n * stay distinct strings: what they mean - solid, water, hazard - is the\n * caller's to decide, and an unrecognised value is data, not an error.\n *\n * The result reads the layer's frozen IntGrid data, so it is stable for the\n * lifetime of the layer and safe to hand to a consumer that samples it while\n * building geometry.\n *\n * ```ts\n * const geometry = buildTileCollisionGeometry(layer, { cells: createLdtkIntGridCellSource(layer) });\n * ```\n */\nexport const createLdtkIntGridCellSource = (layer: TileLayer): TileCellSource | undefined => {\n const parsed = getParsedIntGridData(layer);\n const width = layer.width;\n\n // The flat IntGrid CSV is indexed by row stride, which an unbounded layer\n // has no value for; LDtk never produces one, but `layer` is typed generically.\n if (!parsed || width === undefined) return undefined;\n\n const identifiers = new Map<number, string>();\n\n for (const value of parsed.values) {\n identifiers.set(value.value, value.identifier ?? String(value.value));\n }\n\n return (tx, ty) => {\n if (!layer.inBounds(tx, ty)) return null;\n\n const raw = parsed.csv[ty * width + tx];\n\n if (raw === undefined || raw === 0) return null;\n\n return identifiers.get(raw) ?? String(raw);\n };\n};\n\n// ── Helpers: ObjectLayer ──────────────────────────────────────────────────────\n\nconst convertEntityLayer = (layerInst: LdtkLayerInstance, _gridSize: number, levelIndex: number, baseCounter: number): TileMapObject[] => {\n const instances = layerInst.entityInstances ?? [];\n const objects: TileMapObject[] = [];\n\n for (let i = 0; i < instances.length; i++) {\n const entity = instances[i];\n if (entity === undefined) continue;\n // Build a deterministic numeric id: (levelIndex * 1_000_000) + counter.\n const id = levelIndex * 1_000_000 + baseCounter + i;\n objects.push(convertEntity(entity, id));\n }\n\n return objects;\n};\n\nconst convertEntity = (entity: LdtkEntityInstance, id: number): TileMapObject => {\n // entity.px is the pivot-adjusted anchor, not the bounding box's top-left\n // corner - undo the pivot offset to recover the corner TileMapObject expects.\n const x = entity.px[0] - entity.width * entity.__pivot[0];\n const y = entity.px[1] - entity.height * entity.__pivot[1];\n return {\n kind: 'rectangle',\n id,\n // The iid is the only identity LDtk guarantees stable across re-export and\n // level re-ordering, which is what a spawn session and a savegame key on;\n // the numeric id above is derived from document position and is not.\n sourceId: entity.iid,\n name: entity.__identifier,\n type: entity.__identifier,\n x,\n y,\n width: entity.width,\n height: entity.height,\n rotation: 0,\n visible: true,\n properties: convertFieldInstances(entity.fieldInstances),\n source: entity,\n };\n};\n\n/**\n * Project LDtk field instances to a flat {@link TileProperties} bag.\n * Every LDtk field type maps to a canonical {@link TilePropertyValue}\n * (scalars and enum entries pass through as their raw value;\n * `Point`/`EntityRef`/`Tile` become their tagged structured variants;\n * `Array<T>` fields recursively convert each element).\n * A field whose raw `__value` is `null` (LDtk's \"not set\" convention) is\n * omitted from the bag entirely, matching the property-absent case rather\n * than a present-but-null value.\n */\nconst convertFieldInstances = (fields: readonly LdtkFieldInstance[]): TileProperties => {\n if (fields.length === 0) return Object.freeze({});\n const out: Record<string, TilePropertyValue> = {};\n for (const field of fields) {\n const value = convertField(field);\n if (value !== undefined) {\n out[field.__identifier] = value;\n }\n }\n return Object.freeze(out);\n};\n\n/**\n * Type guard narrowing to the `Array<T>` member of {@link LdtkFieldInstance}.\n * `String.prototype.startsWith` alone does not narrow a template-literal\n * union member for the compiler; a predicate on `field` itself does.\n */\nconst isLdtkArrayField = (field: LdtkFieldInstance): field is Extract<LdtkFieldInstance, { readonly __type: `Array<${string}>` }> =>\n field.__type.startsWith('Array<');\n\n/** See {@link isLdtkArrayField} for why the narrowing needs a predicate on `field`. */\nconst isLdtkEnumField = (field: LdtkFieldInstance): field is Extract<LdtkFieldInstance, { readonly __type: LdtkFieldEnumType }> =>\n isLdtkFieldEnumType(field.__type);\n\n/** Convert one {@link LdtkFieldInstance} to its canonical {@link TilePropertyValue}, or `undefined` for a `null` (unset) field. */\nconst convertField = (field: LdtkFieldInstance): TilePropertyValue | undefined => {\n switch (field.__type) {\n case 'Int':\n case 'Float':\n case 'Bool':\n case 'String':\n case 'Multilines':\n case 'Color':\n case 'FilePath':\n case 'Enum':\n case 'Point':\n case 'EntityRef':\n case 'Tile':\n return mapLdtkFieldValue(field.__type, field.__value);\n\n default:\n break;\n }\n\n if (isLdtkEnumField(field)) {\n return mapLdtkFieldValue(field.__type, field.__value);\n }\n\n if (isLdtkArrayField(field)) {\n if (field.__value === null) return undefined;\n const elementType = field.__type.slice('Array<'.length, -1);\n const elements: TilePropertyValue[] = [];\n for (const raw of field.__value) {\n const converted = mapLdtkFieldValue(elementType, raw);\n if (converted !== undefined) elements.push(converted);\n }\n return Object.freeze(elements);\n }\n\n // Exhaustiveness check: if LDtk ever adds a new field type, `field` will\n // fail to narrow to `never` here and tsc will error.\n field satisfies never;\n throw new Error(`convertFieldInstances: unrecognised LDtk field type \"${(field as LdtkFieldInstance).__type}\".`);\n};\n\n/**\n * Map a single raw LDtk field value (or array element) to its canonical\n * {@link TilePropertyValue}, given the LDtk type name it was declared with.\n * Shared by {@link convertField} (top-level fields) and array-element\n * conversion (`typeName` is the `T` extracted from an `Array<T>` field).\n * Returns `undefined` for a `null` value; throws on a type name this package\n * does not model, at the top level and inside an array alike, so an\n * unsupported field type is never mistaken for an absent or empty one.\n */\nconst mapLdtkFieldValue = (typeName: string, value: unknown): TilePropertyValue | undefined => {\n if (value === null || value === undefined) return undefined;\n\n // An enum entry is its identifier; the enum's own name is only in the type.\n if (isLdtkFieldEnumType(typeName)) {\n return value as string;\n }\n\n switch (typeName) {\n case 'Int':\n case 'Float':\n case 'Bool':\n case 'String':\n case 'Multilines':\n case 'Color':\n case 'FilePath':\n case 'Enum':\n return value as string | number | boolean;\n\n case 'Point': {\n const v = value as { cx: number; cy: number };\n return { kind: TilePropertyKind.Point, cx: v.cx, cy: v.cy };\n }\n\n case 'EntityRef': {\n const v = value as { entityIid: string; layerIid: string; levelIid: string; worldIid: string };\n return {\n kind: TilePropertyKind.ObjectRef,\n id: v.entityIid,\n layerIid: v.layerIid,\n levelIid: v.levelIid,\n worldIid: v.worldIid,\n };\n }\n\n case 'Tile': {\n const v = value as { tilesetUid: number; x: number; y: number; w: number; h: number };\n return { kind: TilePropertyKind.TileRef, tilesetUid: v.tilesetUid, x: v.x, y: v.y, w: v.w, h: v.h };\n }\n\n default:\n throw new Error(`convertFieldInstances: unrecognised LDtk field type \"${typeName}\".`);\n }\n};\n\n// ── Helpers: grid size ────────────────────────────────────────────────────────\n\nconst pickLevelGridSize = (level: LdtkLevel, fallback: number): number => {\n const instances = level.layerInstances ?? [];\n for (const layer of instances) {\n if (layer.__type !== 'Entities' && layer.__gridSize > 0) {\n return layer.__gridSize;\n }\n }\n return fallback;\n};\n\n// Re-export identity transform constant for convenience (tree-shake friendly).\nexport { TILE_TRANSFORM_IDENTITY };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA6DA,MAAa,iBAAiB,MAAgB,YAA4C;CACxF,MAAM,SAAS,SAAS,UAAU;CAClC,MAAM,WAAW,SAAS,4BAAY,IAAI,IAAqB;CAE/D,MAAM,SAAS,oBAAoB,IAAI,CAAC,CAAC,KAAK,OAAO,eAAe,aAAa,MAAM,OAAO,MAAM,UAAU,YAAY,MAAM,QAAQ,CAAC;CAEzI,OAAO,IAAI,QAAQ,QAAQ,MAAM,MAAM;AACzC;;;;;;;;AAWA,MAAa,sBACX,OACA,UACA,YACA,MACA,aACY,aAAa,OAAO,UAAU,YAAY,MAAM,QAAQ;AAEtE,MAAM,gBAAgB,OAAkB,UAA8B,YAAoB,MAAgB,aAAoD;CAE5J,MAAM,WAAW,kBAAkB,OAAO,KAAK,mBAAmB,EAAE;CACpE,MAAM,WAAW,KAAK,IAAI,GAAG,KAAK,KAAK,MAAM,QAAQ,QAAQ,CAAC;CAC9D,MAAM,YAAY,KAAK,IAAI,GAAG,KAAK,KAAK,MAAM,QAAQ,QAAQ,CAAC;CAE/D,MAAM,kBAA6B,CAAC,GAAG,SAAS,OAAO,CAAC;CACxD,MAAM,gBAA6B,CAAC;CACpC,MAAM,sBAAqC,CAAC;CAG5C,MAAM,iBAAiB,MAAM,kBAAkB,CAAC;CAChD,IAAI,gBAAgB;CAEpB,KAAK,MAAM,aAAa,gBAAgB;EAGtC,MAAM,UAAU,UAAU;EAC1B,MAAM,WAAW,yBAAyB,MAAM,SAAS;EAEzD,QAAQ,UAAU,QAAlB;GACE,KAAK;GACL,KAAK;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,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,QACH,OAAO;EAET,KAAK,SAAS;GACZ,MAAM,IAAI;GACV,OAAO;IAAE,MAAM,iBAAiB;IAAO,IAAI,EAAE;IAAI,IAAI,EAAE;GAAG;EAC5D;EAEA,KAAK,aAAa;GAChB,MAAM,IAAI;GACV,OAAO;IACL,MAAM,iBAAiB;IACvB,IAAI,EAAE;IACN,UAAU,EAAE;IACZ,UAAU,EAAE;IACZ,UAAU,EAAE;GACd;EACF;EAEA,KAAK,QAAQ;GACX,MAAM,IAAI;GACV,OAAO;IAAE,MAAM,iBAAiB;IAAS,YAAY,EAAE;IAAY,GAAG,EAAE;IAAG,GAAG,EAAE;IAAG,GAAG,EAAE;IAAG,GAAG,EAAE;GAAE;EACpG;EAEA,SACE,MAAM,IAAI,MAAM,wDAAwD,SAAS,GAAG;CACxF;AACF;AAIA,MAAM,qBAAqB,OAAkB,aAA6B;CACxE,MAAM,YAAY,MAAM,kBAAkB,CAAC;CAC3C,KAAK,MAAM,SAAS,WAClB,IAAI,MAAM,WAAW,cAAc,MAAM,aAAa,GACpD,OAAO,MAAM;CAGjB,OAAO;AACT"}
1
+ {"version":3,"file":"ldtkToTileMap.js","names":[],"sources":["../../src/ldtkToTileMap.ts"],"sourcesContent":["import type { TileCellSource, TileMapObject, TileProperties, TilePropertyValue, TileSet } from '@codexo/exojs/tilemap';\nimport { ObjectLayer, TILE_TRANSFORM_IDENTITY, TileLayer, TileMap, TilePropertyKind } from '@codexo/exojs/tilemap';\n\nimport type {\n LdtkData,\n LdtkEntityInstance,\n LdtkFieldEnumType,\n LdtkFieldInstance,\n LdtkIntGridValueDef,\n LdtkLayerInstance,\n LdtkLevel,\n LdtkTileData,\n} from './LdtkData';\nimport { isLdtkFieldEnumType, LDTK_FLIP_X, LDTK_FLIP_Y } from './LdtkData';\nimport { getLdtkLevelEntries } from './ldtkLevelEntries';\nimport { LdtkMap } from './LdtkMap';\nimport type { LdtkLayerParallax } from './ldtkParallax';\nimport { resolveLdtkLayerParallax } from './ldtkParallax';\n\n// ── Public API ────────────────────────────────────────────────────────────────\n\n/**\n * Options for {@link ldtkToTileMap}.\n */\nexport interface LdtkToTileMapOptions {\n /**\n * Source URL of the loaded `.ldtk` file, used as {@link LdtkMap.source}.\n * Defaults to an empty string when omitted (e.g. programmatic / test usage).\n */\n readonly source?: string;\n /**\n * Pre-loaded runtime {@link TileSet}s keyed by LDtk tileset UID.\n *\n * When provided, tile layers are populated with tile data from\n * `gridTiles` / `autoLayerTiles`. Without this map, tile layers are created\n * with the correct dimensions but no tiles are placed; IntGrid layers still\n * expose their raw CSV and value definitions, and level/entity metadata is\n * unaffected.\n *\n * Populate via {@link import('./loadLdtkMap').loadLdtkMap} for asset-loading\n * flows, or pass a hand-crafted map for testing.\n */\n readonly tilesets?: ReadonlyMap<number, TileSet>;\n}\n\n/**\n * Convert a raw {@link LdtkData} document into an {@link LdtkMap} containing\n * one runtime {@link TileMap} per LDtk level.\n *\n * Tile layers (`Tiles` / `AutoLayer`) become renderable `TileLayer`s. IntGrid\n * layers become dimension-correct `TileLayer`s - tile data is placed only when\n * the layer carries `autoLayerTiles`. Entity layers become data-only\n * `ObjectLayer`s with entity position, size, and scalar field properties.\n *\n * Pass `options.tilesets` to populate tile data; omit it for structure-only\n * conversion (useful in unit tests that do not need textures).\n *\n * Externalized levels (`layerInstances: null`) convert to empty maps -\n * resolve their `.ldtkl` payloads through `loadLdtkMap` or\n * {@link import('./LdtkProject').LdtkProject}.\n *\n * Transparently handles both LDtk root shapes via {@link getLdtkLevelEntries}:\n * single-world (`data.levels`) and multi-world (`data.worlds[].levels`) - in\n * the latter case every converted level's `TileMap.properties` is additionally\n * tagged with its owning world's iid under the reserved `ldtkWorldIid` key.\n */\nexport const ldtkToTileMap = (data: LdtkData, options?: LdtkToTileMapOptions): LdtkMap => {\n const source = options?.source ?? '';\n const tilesets = options?.tilesets ?? new Map<number, TileSet>();\n\n const levels = getLdtkLevelEntries(data).map((entry, levelIndex) =>\n convertLevel(entry.level, entry.worldIid, levelIndex, data, tilesets),\n );\n\n return new LdtkMap(source, data, levels);\n};\n\n// ── Level conversion ──────────────────────────────────────────────────────────\n\n/**\n * Convert one already-resolved LDtk level into its runtime {@link TileMap}.\n *\n * `level.layerInstances` must be present: an externalized level has to have its\n * `.ldtkl` payload merged in first, or the result is an empty map.\n * @internal\n */\nexport const ldtkLevelToTileMap = (\n level: LdtkLevel,\n worldIid: string | undefined,\n levelIndex: number,\n data: LdtkData,\n tilesets: ReadonlyMap<number, TileSet>,\n): TileMap => convertLevel(level, worldIid, levelIndex, data, tilesets);\n\nconst convertLevel = (\n level: LdtkLevel,\n worldIid: string | undefined,\n levelIndex: number,\n data: LdtkData,\n tilesets: ReadonlyMap<number, TileSet>,\n): TileMap => {\n // Derive map-level tile size from the first non-entity layer, or fall back.\n const gridSize = pickLevelGridSize(level, data.defaultGridSize ?? 16);\n const mapWidth = Math.max(1, Math.ceil(level.pxWid / gridSize));\n const mapHeight = Math.max(1, Math.ceil(level.pxHei / gridSize));\n\n const runtimeTilesets: TileSet[] = [...tilesets.values()];\n const runtimeLayers: TileLayer[] = [];\n const runtimeObjectLayers: ObjectLayer[] = [];\n\n // LDtk stores layers top-to-bottom (first = top-most); preserve that order.\n const layerInstances = level.layerInstances ?? [];\n let entityCounter = 0;\n\n for (const layerInst of layerInstances) {\n // Layer IDs must be unique within a TileMap (= one level).\n // Use layerDefUid directly - it is unique per layer definition in the file.\n const layerId = layerInst.layerDefUid;\n const parallax = resolveLdtkLayerParallax(data, layerInst);\n\n switch (layerInst.__type) {\n case 'Tiles':\n case 'AutoLayer':\n runtimeLayers.push(convertTilesOrAutoLayer(layerInst, layerId, runtimeTilesets, tilesets, parallax));\n break;\n\n case 'IntGrid':\n runtimeLayers.push(convertIntGridLayer(layerInst, layerId, runtimeTilesets, tilesets, data, parallax));\n break;\n\n case 'Entities':\n runtimeObjectLayers.push(convertEntitiesLayer(layerInst, layerId, levelIndex, entityCounter, parallax));\n entityCounter += layerInst.entityInstances?.length ?? 0;\n break;\n }\n }\n\n return new TileMap({\n name: level.identifier,\n width: mapWidth,\n height: mapHeight,\n tileWidth: gridSize,\n tileHeight: gridSize,\n tilesets: runtimeTilesets,\n layers: runtimeLayers,\n objectLayers: runtimeObjectLayers,\n backgroundColor: parseLdtkColor(level.__bgColor ?? level.bgColor ?? data.defaultLevelBgColor),\n properties: buildLdtkLevelProperties(level, worldIid),\n });\n};\n\n/** A `#rrggbb` LDtk colour as `0xRRGGBB`, or `null` when absent or malformed. */\nconst parseLdtkColor = (color: string | null | undefined): number | null =>\n color !== null && color !== undefined && /^#[\\da-f]{6}$/i.test(color) ? Number.parseInt(color.slice(1), 16) : null;\n\n/**\n * The property bag a level contributes to its runtime representation - user\n * fields first, then the reserved LDtk keys, so a same-named user field can\n * never clobber them. `ldtkWorldIid` is added only for multi-world documents;\n * a single-world document's properties stay exactly as they were before\n * multi-world support existed.\n * @internal\n */\nexport const buildLdtkLevelProperties = (level: LdtkLevel, worldIid: string | undefined): TileProperties => ({\n ...convertFieldInstances(level.fieldInstances ?? []),\n ldtkUid: level.uid,\n ldtkIid: level.iid,\n worldX: level.worldX,\n worldY: level.worldY,\n ...(worldIid !== undefined && { ldtkWorldIid: worldIid }),\n});\n\n// ── Helpers: per-layer-type level conversion ─────────────────────────────────\n\n/** Convert a `Tiles`/`AutoLayer` LDtk layer instance into a runtime {@link TileLayer}. */\nconst convertTilesOrAutoLayer = (\n layerInst: LdtkLayerInstance,\n layerId: number,\n runtimeTilesets: readonly TileSet[],\n tilesets: ReadonlyMap<number, TileSet>,\n parallax: LdtkLayerParallax,\n): TileLayer => {\n const rLayer = makeTileLayer(layerInst, layerId, runtimeTilesets, parallax);\n const tiles = layerInst.__type === 'Tiles' ? (layerInst.gridTiles ?? []) : (layerInst.autoLayerTiles ?? []);\n const tsUid = layerInst.__tilesetDefUid;\n\n if (tsUid !== undefined && tsUid !== null) {\n const rts = tilesets.get(tsUid);\n\n if (rts) {\n populateTileLayer(rLayer, tiles, rts, layerInst.__gridSize);\n }\n }\n\n return rLayer;\n};\n\n/** Convert an `IntGrid` LDtk layer instance into a runtime {@link TileLayer}. */\nconst convertIntGridLayer = (\n layerInst: LdtkLayerInstance,\n layerId: number,\n runtimeTilesets: readonly TileSet[],\n tilesets: ReadonlyMap<number, TileSet>,\n data: LdtkData,\n parallax: LdtkLayerParallax,\n): TileLayer => {\n const intGridProperties = buildIntGridProperties(layerInst, data);\n const rLayer = makeTileLayer(layerInst, layerId, runtimeTilesets, parallax, intGridProperties);\n // IntGrid layers may carry auto-tiles when \"Auto-layer\" rules are\n // configured. Use those for rendering; raw intGridCsv is exposed as\n // data-only layer properties (see buildIntGridProperties).\n const autoTiles = layerInst.autoLayerTiles ?? [];\n const tsUid = layerInst.__tilesetDefUid;\n\n if (autoTiles.length > 0 && tsUid !== undefined && tsUid !== null) {\n const rts = tilesets.get(tsUid);\n\n if (rts) {\n populateTileLayer(rLayer, autoTiles, rts, layerInst.__gridSize);\n }\n }\n\n return rLayer;\n};\n\n/** Convert an `Entities` LDtk layer instance into a runtime {@link ObjectLayer}. */\nconst convertEntitiesLayer = (\n layerInst: LdtkLayerInstance,\n layerId: number,\n levelIndex: number,\n entityCounter: number,\n parallax: LdtkLayerParallax,\n): ObjectLayer => {\n const objects = convertEntityLayer(layerInst, layerInst.__gridSize, levelIndex, entityCounter);\n\n return new ObjectLayer({\n id: layerId,\n name: layerInst.__identifier,\n visible: layerInst.visible,\n opacity: layerInst.opacity ?? 1,\n offsetX: parallax.offsetX + (layerInst.pxOffsetX ?? 0),\n offsetY: parallax.offsetY + (layerInst.pxOffsetY ?? 0),\n parallaxX: parallax.parallaxX,\n parallaxY: parallax.parallaxY,\n parallaxScale: parallax.parallaxScale,\n objects,\n });\n};\n\n// ── Helpers: TileLayer ────────────────────────────────────────────────────────\n\nconst makeTileLayer = (\n layerInst: LdtkLayerInstance,\n layerId: number,\n tilesets: readonly TileSet[],\n parallax: LdtkLayerParallax,\n properties?: TileProperties,\n): TileLayer =>\n new TileLayer({\n id: layerId,\n name: layerInst.__identifier,\n width: layerInst.__cWid,\n height: layerInst.__cHei,\n tilesets,\n tileWidth: layerInst.__gridSize,\n tileHeight: layerInst.__gridSize,\n visible: layerInst.visible,\n opacity: layerInst.opacity ?? 1,\n offsetX: parallax.offsetX + (layerInst.pxOffsetX ?? 0),\n offsetY: parallax.offsetY + (layerInst.pxOffsetY ?? 0),\n parallaxX: parallax.parallaxX,\n parallaxY: parallax.parallaxY,\n parallaxScale: parallax.parallaxScale,\n ...(properties && { properties }),\n });\n\nconst populateTileLayer = (layer: TileLayer, tiles: readonly LdtkTileData[], tileset: TileSet, gridSize: number): void => {\n for (const tile of tiles) {\n const tx = Math.floor(tile.px[0] / gridSize);\n const ty = Math.floor(tile.px[1] / gridSize);\n\n if (!layer.inBounds(tx, ty)) {\n continue;\n }\n\n const localTileId = tile.t;\n\n if (localTileId < 0 || localTileId >= tileset.tileCount) {\n continue;\n }\n\n const f = tile.f;\n layer.setTileAt(tx, ty, {\n tileset,\n localTileId,\n transform: {\n flipX: (f & LDTK_FLIP_X) !== 0,\n flipY: (f & LDTK_FLIP_Y) !== 0,\n diagonal: false,\n },\n });\n }\n};\n\n// ── Helpers: IntGrid ──────────────────────────────────────────────────────────\n\n/**\n * Reserved {@link TileLayer.properties} key holding the JSON-encoded raw\n * IntGrid CSV array (`readonly number[]`) for a `TileLayer` converted from an\n * LDtk `IntGrid` layer instance. Index = `y * layer.width + x`; `0` = empty.\n * Prefer {@link getLdtkIntGridValueAt} over reading this directly.\n */\nexport const ldtkIntGridCsvProperty = 'ldtkIntGridCsv';\n\n/**\n * Reserved {@link TileLayer.properties} key holding the JSON-encoded\n * {@link LdtkIntGridValueDef} array for a `TileLayer` converted from an LDtk\n * `IntGrid` layer instance - the raw-int → named/coloured mapping declared on\n * the owning layer definition (`data.defs.layers[].intGridValues`).\n * Prefer {@link getLdtkIntGridValueAt} over reading this directly.\n */\nexport const ldtkIntGridValuesProperty = 'ldtkIntGridValues';\n\n/**\n * Build the reserved IntGrid properties for a `TileLayer` from an LDtk\n * `IntGrid` layer instance, or `undefined` when the layer carries no\n * `intGridCsv` data (nothing to expose).\n *\n * {@link TileLayer.properties} values are scalar-only, so the raw CSV array\n * and the value-definition mapping are JSON-encoded into two reserved string\n * properties rather than stored as nested structures - the same\n * `properties`-bag mechanism the Tiled adapter already uses for per-layer\n * metadata, just serialized to fit its scalar-only value type.\n */\nconst buildIntGridProperties = (layerInst: LdtkLayerInstance, data: LdtkData): TileProperties | undefined => {\n const csv = layerInst.intGridCsv;\n\n if (!csv || csv.length === 0) {\n return undefined;\n }\n\n const layerDef = data.defs.layers.find(def => def.uid === layerInst.layerDefUid);\n const values = layerDef?.intGridValues ?? [];\n\n return Object.freeze({\n [ldtkIntGridCsvProperty]: JSON.stringify(csv),\n [ldtkIntGridValuesProperty]: JSON.stringify(values),\n });\n};\n\n/** Parsed, cached form of a `TileLayer`'s {@link ldtkIntGridCsvProperty} / {@link ldtkIntGridValuesProperty}. */\ninterface ParsedIntGridData {\n readonly csv: readonly number[];\n readonly values: readonly LdtkIntGridValueDef[];\n}\n\n/**\n * Per-`TileLayer` cache of parsed IntGrid CSV/value-defs data, populated\n * lazily on first {@link getLdtkIntGridValueAt} lookup for a given layer.\n *\n * Keyed by the `TileLayer` instance itself (`WeakMap`), so an entry is\n * naturally garbage-collected once the layer it was derived from is no\n * longer referenced - no manual invalidation needed since\n * {@link TileLayer.properties} is frozen and copied at construction time and\n * can never change afterwards.\n */\nconst intGridCache = new WeakMap<TileLayer, ParsedIntGridData>();\n\n/**\n * Parse (or retrieve from {@link intGridCache}) the IntGrid CSV/value-defs\n * data attached to `layer`, or `undefined` when `layer` carries no such data\n * (not converted from an IntGrid layer instance).\n */\nconst getParsedIntGridData = (layer: TileLayer): ParsedIntGridData | undefined => {\n const cached = intGridCache.get(layer);\n\n if (cached) {\n return cached;\n }\n\n const csvRaw = layer.properties[ldtkIntGridCsvProperty];\n const valuesRaw = layer.properties[ldtkIntGridValuesProperty];\n\n if (typeof csvRaw !== 'string' || typeof valuesRaw !== 'string') {\n return undefined;\n }\n\n const parsed: ParsedIntGridData = {\n csv: JSON.parse(csvRaw) as readonly number[],\n values: JSON.parse(valuesRaw) as readonly LdtkIntGridValueDef[],\n };\n intGridCache.set(layer, parsed);\n\n return parsed;\n};\n\n/**\n * Look up the named/coloured {@link LdtkIntGridValueDef} at a tile coordinate\n * on a `TileLayer` converted from an LDtk `IntGrid` layer instance.\n *\n * Returns `undefined` when the coordinate is out of bounds, the cell's raw\n * value is `0` (empty), the raw value has no matching definition, or `layer`\n * was not converted from an IntGrid layer instance (no IntGrid data attached\n * via {@link ldtkIntGridCsvProperty} / {@link ldtkIntGridValuesProperty}).\n *\n * The underlying JSON-encoded CSV/value-defs properties are parsed once per\n * layer and cached (see {@link getParsedIntGridData}) - safe to call from a\n * hot path (e.g. per-cell or per-frame collision/classification checks).\n */\nexport const getLdtkIntGridValueAt = (layer: TileLayer, x: number, y: number): LdtkIntGridValueDef | undefined => {\n // `inBounds()` is unconditionally true for an unbounded layer (it has no\n // fixed grid to be out of), but the flat IntGrid CSV this function reads\n // is inherently a bounded-grid concept - LDtk itself only ever produces\n // bounded layers today, but `layer` is typed generically, so guard here\n // rather than let `layer.width` narrow away from `number | undefined`.\n if (!layer.inBounds(x, y) || layer.width === undefined) {\n return undefined;\n }\n\n const parsed = getParsedIntGridData(layer);\n\n if (!parsed) {\n return undefined;\n }\n\n const raw = parsed.csv[y * layer.width + x];\n\n if (raw === undefined || raw === 0) {\n return undefined;\n }\n\n return parsed.values.find(v => v.value === raw);\n};\n\n/**\n * Per-cell collision classification for a `TileLayer` converted from an LDtk\n * `IntGrid` layer instance, or `undefined` when the layer carries no IntGrid\n * data (not converted from an IntGrid layer instance, or unbounded).\n *\n * The classification is the value's LDtk-authored identifier, falling back to\n * the raw integer as a string when the value definition declares none. Cells\n * whose raw value is `0` (empty) classify as `null`. Distinct IntGrid values\n * stay distinct strings: what they mean - solid, water, hazard - is the\n * caller's to decide, and an unrecognised value is data, not an error.\n *\n * The result reads the layer's frozen IntGrid data, so it is stable for the\n * lifetime of the layer and safe to hand to a consumer that samples it while\n * building geometry.\n *\n * ```ts\n * const geometry = buildTileCollisionGeometry(layer, { cells: createLdtkIntGridCellSource(layer) });\n * ```\n */\nexport const createLdtkIntGridCellSource = (layer: TileLayer): TileCellSource | undefined => {\n const parsed = getParsedIntGridData(layer);\n const width = layer.width;\n\n // The flat IntGrid CSV is indexed by row stride, which an unbounded layer\n // has no value for; LDtk never produces one, but `layer` is typed generically.\n if (!parsed || width === undefined) {\n return undefined;\n }\n\n const identifiers = new Map<number, string>();\n\n for (const value of parsed.values) {\n identifiers.set(value.value, value.identifier ?? String(value.value));\n }\n\n return (tx, ty) => {\n if (!layer.inBounds(tx, ty)) {\n return null;\n }\n\n const raw = parsed.csv[ty * width + tx];\n\n if (raw === undefined || raw === 0) {\n return null;\n }\n\n return identifiers.get(raw) ?? String(raw);\n };\n};\n\n// ── Helpers: ObjectLayer ──────────────────────────────────────────────────────\n\nconst convertEntityLayer = (layerInst: LdtkLayerInstance, _gridSize: number, levelIndex: number, baseCounter: number): TileMapObject[] => {\n const instances = layerInst.entityInstances ?? [];\n const objects: TileMapObject[] = [];\n\n for (let i = 0; i < instances.length; i++) {\n const entity = instances[i];\n\n if (entity === undefined) {\n continue;\n }\n\n // Build a deterministic numeric id: (levelIndex * 1_000_000) + counter.\n const id = levelIndex * 1_000_000 + baseCounter + i;\n objects.push(convertEntity(entity, id));\n }\n\n return objects;\n};\n\nconst convertEntity = (entity: LdtkEntityInstance, id: number): TileMapObject => {\n // entity.px is the pivot-adjusted anchor, not the bounding box's top-left\n // corner - undo the pivot offset to recover the corner TileMapObject expects.\n const x = entity.px[0] - entity.width * entity.__pivot[0];\n const y = entity.px[1] - entity.height * entity.__pivot[1];\n\n return {\n kind: 'rectangle',\n id,\n // The iid is the only identity LDtk guarantees stable across re-export and\n // level re-ordering, which is what a spawn session and a savegame key on;\n // the numeric id above is derived from document position and is not.\n sourceId: entity.iid,\n name: entity.__identifier,\n type: entity.__identifier,\n x,\n y,\n width: entity.width,\n height: entity.height,\n rotation: 0,\n visible: true,\n properties: buildLdtkEntityProperties(entity),\n source: entity,\n };\n};\n\n/**\n * An entity's property bag: its fields, then `ldtkTags` - the tags of its\n * definition - when it has any, so spawn code can dispatch on a tag such as\n * `Enemy` without reading the raw entity. Like the level keys, the reserved\n * key wins over a same-named field.\n */\nconst buildLdtkEntityProperties = (entity: LdtkEntityInstance): TileProperties => {\n const properties = convertFieldInstances(entity.fieldInstances);\n const tags = entity.__tags ?? [];\n\n return tags.length === 0 ? properties : { ...properties, ldtkTags: [...tags] };\n};\n\n/**\n * Project LDtk field instances to a flat {@link TileProperties} bag.\n * Every LDtk field type maps to a canonical {@link TilePropertyValue}\n * (scalars and enum entries pass through as their raw value;\n * `Point`/`EntityRef`/`Tile` become their tagged structured variants;\n * `Array<T>` fields recursively convert each element).\n * A field whose raw `__value` is `null` (LDtk's \"not set\" convention) is\n * omitted from the bag entirely, matching the property-absent case rather\n * than a present-but-null value.\n */\nconst convertFieldInstances = (fields: readonly LdtkFieldInstance[]): TileProperties => {\n if (fields.length === 0) {\n return Object.freeze({});\n }\n\n const out: Record<string, TilePropertyValue> = {};\n\n for (const field of fields) {\n const value = convertField(field);\n\n if (value !== undefined) {\n out[field.__identifier] = value;\n }\n }\n\n return Object.freeze(out);\n};\n\n/**\n * Type guard narrowing to the `Array<T>` member of {@link LdtkFieldInstance}.\n * `String.prototype.startsWith` alone does not narrow a template-literal\n * union member for the compiler; a predicate on `field` itself does.\n */\nconst isLdtkArrayField = (field: LdtkFieldInstance): field is Extract<LdtkFieldInstance, { readonly __type: `Array<${string}>` }> =>\n field.__type.startsWith('Array<');\n\n/** See {@link isLdtkArrayField} for why the narrowing needs a predicate on `field`. */\nconst isLdtkEnumField = (field: LdtkFieldInstance): field is Extract<LdtkFieldInstance, { readonly __type: LdtkFieldEnumType }> =>\n isLdtkFieldEnumType(field.__type);\n\n/** Convert one {@link LdtkFieldInstance} to its canonical {@link TilePropertyValue}, or `undefined` for a `null` (unset) field. */\nconst convertField = (field: LdtkFieldInstance): TilePropertyValue | undefined => {\n switch (field.__type) {\n case 'Int':\n case 'Float':\n case 'Bool':\n case 'String':\n case 'Multilines':\n case 'Color':\n case 'FilePath':\n case 'Enum':\n case 'Point':\n case 'EntityRef':\n case 'Tile':\n return mapLdtkFieldValue(field.__type, field.__value);\n\n default:\n break;\n }\n\n if (isLdtkEnumField(field)) {\n return mapLdtkFieldValue(field.__type, field.__value);\n }\n\n if (isLdtkArrayField(field)) {\n if (field.__value === null) {\n return undefined;\n }\n\n const elementType = field.__type.slice('Array<'.length, -1);\n const elements: TilePropertyValue[] = [];\n\n for (const raw of field.__value) {\n const converted = mapLdtkFieldValue(elementType, raw);\n\n if (converted !== undefined) {\n elements.push(converted);\n }\n }\n\n return Object.freeze(elements);\n }\n\n // Exhaustiveness check: if LDtk ever adds a new field type, `field` will\n // fail to narrow to `never` here and tsc will error.\n field satisfies never;\n\n throw new Error(`convertFieldInstances: unrecognised LDtk field type \"${(field as LdtkFieldInstance).__type}\".`);\n};\n\n/**\n * Map a single raw LDtk field value (or array element) to its canonical\n * {@link TilePropertyValue}, given the LDtk type name it was declared with.\n * Shared by {@link convertField} (top-level fields) and array-element\n * conversion (`typeName` is the `T` extracted from an `Array<T>` field).\n * Returns `undefined` for a `null` value; throws on a type name this package\n * does not model, at the top level and inside an array alike, so an\n * unsupported field type is never mistaken for an absent or empty one.\n */\nconst mapLdtkFieldValue = (typeName: string, value: unknown): TilePropertyValue | undefined => {\n if (value === null || value === undefined) {\n return undefined;\n }\n\n // An enum entry is its identifier; the enum's own name is only in the type.\n if (isLdtkFieldEnumType(typeName)) {\n return value as string;\n }\n\n switch (typeName) {\n case 'Int':\n case 'Float':\n case 'Bool':\n case 'String':\n case 'Multilines':\n case 'Color':\n case 'FilePath':\n case 'Enum':\n return value as string | number | boolean;\n\n case 'Point': {\n const v = value as { cx: number; cy: number };\n\n return { kind: TilePropertyKind.Point, cx: v.cx, cy: v.cy };\n }\n\n case 'EntityRef': {\n const v = value as { entityIid: string; layerIid: string; levelIid: string; worldIid: string };\n\n return {\n kind: TilePropertyKind.ObjectRef,\n id: v.entityIid,\n layerIid: v.layerIid,\n levelIid: v.levelIid,\n worldIid: v.worldIid,\n };\n }\n\n case 'Tile': {\n const v = value as { tilesetUid: number; x: number; y: number; w: number; h: number };\n\n return { kind: TilePropertyKind.TileRef, tilesetUid: v.tilesetUid, x: v.x, y: v.y, w: v.w, h: v.h };\n }\n\n default:\n throw new Error(`convertFieldInstances: unrecognised LDtk field type \"${typeName}\".`);\n }\n};\n\n// ── Helpers: grid size ────────────────────────────────────────────────────────\n\nconst pickLevelGridSize = (level: LdtkLevel, fallback: number): number => {\n const instances = level.layerInstances ?? [];\n\n for (const layer of instances) {\n if (layer.__type !== 'Entities' && layer.__gridSize > 0) {\n return layer.__gridSize;\n }\n }\n\n return fallback;\n};\n\n// Re-export identity transform constant for convenience (tree-shake friendly).\nexport { TILE_TRANSFORM_IDENTITY };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkEA,MAAa,iBAAiB,MAAgB,YAA4C;CACxF,MAAM,SAAS,SAAS,UAAU;CAClC,MAAM,WAAW,SAAS,4BAAY,IAAI,IAAqB;CAE/D,MAAM,SAAS,oBAAoB,IAAI,CAAC,CAAC,KAAK,OAAO,eACnD,aAAa,MAAM,OAAO,MAAM,UAAU,YAAY,MAAM,QAAQ,CACtE;CAEA,OAAO,IAAI,QAAQ,QAAQ,MAAM,MAAM;AACzC;;;;;;;;AAWA,MAAa,sBACX,OACA,UACA,YACA,MACA,aACY,aAAa,OAAO,UAAU,YAAY,MAAM,QAAQ;AAEtE,MAAM,gBACJ,OACA,UACA,YACA,MACA,aACY;CAEZ,MAAM,WAAW,kBAAkB,OAAO,KAA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AAO,MAAM,WAAW,kBAAyB,CAAC;AAClD,iFAAiF;AACjF,eAAO,MAAM,eAAe,sBAA6B,CAAC"}
1
+ {"version":3,"file":"ldtkTypes.d.ts","sources":["../../src/ldtkTypes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAE1C,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAI5C;;;;;;;GAOG;AACH,qBAAa,gBAAiB,SAAQ,SAAS,CAAC,IAAI,EAAE,OAAO,CAAC;IAC5D,SAAgB,EAAE,aAAa;IAC/B,SAAyB,UAAU,WAAY;IAC/C,SAAyB,MAAM,iBAAW;IAE1C;;;OAGG;IACa,gBAAgB,IAAI;QAAE,MAAM,EAAE,IAAI,CAAA;KAAE,CAEnD;IAEM,aAAa,IAAI,YAAY,CAAC,IAAI,EAAE,OAAO,CAAC,CAElD;CACF;AAED;;;;;;;;GAQG;AACH,qBAAa,oBAAqB,SAAQ,SAAS,CAAC,IAAI,EAAE,WAAW,CAAC;IACpE,SAAgB,EAAE,iBAAiB;IACnC,SAAyB,MAAM,qBAAe;IAE9B,gBAAgB,IAAI;QAAE,MAAM,EAAE,IAAI,CAAA;KAAE,CAEnD;IAEM,aAAa,IAAI,YAAY,CAAC,IAAI,EAAE,WAAW,CAAC,CAEtD;CACF;AAED,2EAA2E;AAC3E,eAAO,MAAM,WAAW,kBAAyB,CAAC;AAClD,iFAAiF;AACjF,eAAO,MAAM,eAAe,sBAA6B,CAAC"}
@@ -4,7 +4,7 @@ import { loadLdtkMap } from "./loadLdtkMap.js";
4
4
  import { loadLdtkProject } from "./loadLdtkProject.js";
5
5
  import { AssetType } from "@codexo/exojs";
6
6
 
7
- //#region src/ldtkTypes.ts
7
+ // src/ldtkTypes.ts
8
8
  /**
9
9
  * A fully assembled LDtk world: every referenced tileset image loaded, every
10
10
  * externalized `.ldtkl` level resolved, and one runtime
@@ -52,6 +52,5 @@ const ldtkMapType = new LdtkMapAssetType();
52
52
  /** The streaming LDtk project asset type. Install it through `ldtkExtension`. */
53
53
  const ldtkProjectType = new LdtkProjectAssetType();
54
54
 
55
- //#endregion
56
55
  export { LdtkMapAssetType, LdtkProjectAssetType, ldtkMapType, ldtkProjectType };
57
56
  //# sourceMappingURL=ldtkTypes.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"loadLdtkMap.d.ts","sourceRoot":"","sources":["../../src/loadLdtkMap.ts"],"names":[],"mappings":""}
1
+ {"version":3,"file":"loadLdtkMap.d.ts","sources":["../../src/loadLdtkMap.ts"],"names":[],"mappings":""}
@@ -2,10 +2,10 @@ import { getLdtkLevelEntries } from "./ldtkLevelEntries.js";
2
2
  import { ldtkToTileMap } from "./ldtkToTileMap.js";
3
3
  import { resolveLdtkUrl } from "./url.js";
4
4
  import { LdtkFormatError, validateLdtkData, validateLdtkLevelData } from "./validate.js";
5
- import { TileSet } from "@codexo/exojs-tilemap";
6
- import { Asset, TextureRegion, logger } from "@codexo/exojs";
5
+ import { TileSet } from "@codexo/exojs/tilemap";
6
+ import { TextureRegion, logger } from "@codexo/exojs";
7
7
 
8
- //#region src/loadLdtkMap.ts
8
+ // src/loadLdtkMap.ts
9
9
  /**
10
10
  * Load one LDtk tileset definition into a runtime {@link TileSet}.
11
11
  *
@@ -25,7 +25,10 @@ const loadLdtkTileset = async (def, ldtkSource, context) => {
25
25
  return null;
26
26
  }
27
27
  const imageUrl = resolveLdtkUrl(def.relPath, ldtkSource);
28
- const texture = await context.dependencies.load(Asset.type("texture", imageUrl));
28
+ const texture = await context.dependencies.load({
29
+ type: "texture",
30
+ source: imageUrl
31
+ });
29
32
  const tileSize = def.tileGridSize;
30
33
  const spacing = def.spacing ?? 0;
31
34
  const margin = def.padding ?? 0;
@@ -41,7 +44,7 @@ const loadLdtkTileset = async (def, ldtkSource, context) => {
41
44
  width: def.pxWid,
42
45
  height: def.pxHei
43
46
  });
44
- return new TileSet({
47
+ const tileset = new TileSet({
45
48
  name: def.identifier,
46
49
  texture: region,
47
50
  tileWidth: tileSize,
@@ -51,6 +54,39 @@ const loadLdtkTileset = async (def, ldtkSource, context) => {
51
54
  spacing,
52
55
  margin
53
56
  });
57
+ const definitions = buildLdtkTileDefinitions(def, tileCount);
58
+ if (definitions.length > 0) tileset.setDefinitions(definitions);
59
+ return tileset;
60
+ };
61
+ /**
62
+ * Per-tile metadata authored in the LDtk tileset editor, as tile properties:
63
+ * `ldtkCustomData` holds a tile's custom text and `ldtkEnumTags` the enum
64
+ * values tagged on it. Ids outside the atlas are skipped.
65
+ * @internal
66
+ */
67
+ const buildLdtkTileDefinitions = (def, tileCount) => {
68
+ const properties = /* @__PURE__ */ new Map();
69
+ const entry = (tileId) => {
70
+ if (tileId >= tileCount) return;
71
+ let bag = properties.get(tileId);
72
+ if (bag === void 0) {
73
+ bag = {};
74
+ properties.set(tileId, bag);
75
+ }
76
+ return bag;
77
+ };
78
+ for (const { tileId, data } of def.customData ?? []) {
79
+ const bag = entry(tileId);
80
+ if (bag !== void 0) bag.ldtkCustomData = data;
81
+ }
82
+ for (const { enumValueId, tileIds } of def.enumTags ?? []) for (const tileId of tileIds) {
83
+ const bag = entry(tileId);
84
+ if (bag !== void 0) bag.ldtkEnumTags = [...bag.ldtkEnumTags ?? [], enumValueId];
85
+ }
86
+ return [...properties].map(([localTileId, bag]) => ({
87
+ localTileId,
88
+ properties: bag
89
+ }));
54
90
  };
55
91
  /**
56
92
  * Resolve a level's external `.ldtkl` payload and merge its layer/field data
@@ -67,7 +103,10 @@ const loadLdtkTileset = async (def, ldtkSource, context) => {
67
103
  const loadExternalLevel = async (level, ldtkSource, context) => {
68
104
  if (level.layerInstances !== null || level.externalRelPath === void 0 || level.externalRelPath === null || level.externalRelPath === "") return level;
69
105
  const externalUrl = resolveLdtkUrl(level.externalRelPath, ldtkSource);
70
- const external = validateLdtkLevelData(await context.dependencies.load(Asset.type("json", externalUrl)), externalUrl);
106
+ const external = validateLdtkLevelData(await context.dependencies.load({
107
+ type: "json",
108
+ source: externalUrl
109
+ }), externalUrl);
71
110
  const fieldInstances = external.fieldInstances ?? level.fieldInstances;
72
111
  return {
73
112
  ...level,
@@ -127,7 +166,10 @@ const withResolvedLevels = (data, resolvedLevels) => {
127
166
  */
128
167
  const loadLdtkMap = async (context) => {
129
168
  const source = context.source;
130
- const data = validateLdtkData(await context.dependencies.load(Asset.type("json", source)), source);
169
+ const data = validateLdtkData(await context.dependencies.load({
170
+ type: "json",
171
+ source
172
+ }), source);
131
173
  const [tilesetEntries, resolvedLevels] = await Promise.all([Promise.all(data.defs.tilesets.map(async (def) => {
132
174
  const ts = await loadLdtkTileset(def, source, context);
133
175
  return [def.uid, ts];
@@ -140,6 +182,5 @@ const loadLdtkMap = async (context) => {
140
182
  });
141
183
  };
142
184
 
143
- //#endregion
144
- export { loadLdtkMap, loadLdtkTileset };
185
+ export { buildLdtkTileDefinitions, loadLdtkMap, loadLdtkTileset };
145
186
  //# sourceMappingURL=loadLdtkMap.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"loadLdtkMap.js","names":[],"sources":["../../src/loadLdtkMap.ts"],"sourcesContent":["import type { AssetFactoryContext } from '@codexo/exojs';\nimport { Asset, logger, TextureRegion } from '@codexo/exojs';\nimport { TileSet } from '@codexo/exojs-tilemap';\n\nimport type { LdtkData, LdtkLevel, LdtkTilesetDef } from './LdtkData';\nimport { getLdtkLevelEntries } from './ldtkLevelEntries';\nimport type { LdtkMap } from './LdtkMap';\nimport { ldtkToTileMap } from './ldtkToTileMap';\nimport { resolveLdtkUrl } from './url';\nimport { LdtkFormatError, validateLdtkData, validateLdtkLevelData } from './validate';\n\n// ── Tileset loading ───────────────────────────────────────────────────────────\n\n/**\n * Load one LDtk tileset definition into a runtime {@link TileSet}.\n *\n * Returns `null` only for an embed-atlas tileset (`relPath` null or empty),\n * whose image ships with the LDtk editor and cannot be resolved from the\n * document - that case warns rather than passing unnoticed, because every tile\n * drawn from it is missing from the runtime map.\n *\n * @throws {LdtkFormatError} when the tileset names an atlas that cannot yield a\n * single tile (its declared size is smaller than one padded tile). Dropping it\n * would make every cell and entity referencing it vanish without a diagnostic.\n * @internal\n */\nexport const loadLdtkTileset = async (def: LdtkTilesetDef, ldtkSource: string, context: AssetFactoryContext): Promise<TileSet | null> => {\n if (def.relPath === null || def.relPath === '') {\n logger.warn(\n `LDtk: tileset \"${def.identifier}\" in \"${ldtkSource}\" has no atlas image (relPath is null) — it is an ` +\n 'embed-atlas tileset whose image lives inside the LDtk editor. Every tile drawn from it is omitted ' +\n 'from the runtime map. Re-export the tileset as a regular image atlas to render it.',\n { source: 'ldtk' },\n );\n\n return null;\n }\n\n const imageUrl = resolveLdtkUrl(def.relPath, ldtkSource);\n const texture = await context.dependencies.load(Asset.type('texture', imageUrl));\n\n const tileSize = def.tileGridSize;\n const spacing = def.spacing ?? 0;\n const margin = def.padding ?? 0;\n\n // Compute columns / tileCount from atlas dimensions.\n const innerWidth = def.pxWid - margin * 2;\n const innerHeight = def.pxHei - margin * 2;\n const columns = Math.floor((innerWidth + spacing) / (tileSize + spacing));\n const rows = Math.floor((innerHeight + spacing) / (tileSize + spacing));\n\n if (columns <= 0 || rows <= 0) {\n throw new LdtkFormatError(\n ldtkSource,\n `defs.tilesets/${def.identifier}`,\n `tileset \"${def.identifier}\" declares a ${def.pxWid}×${def.pxHei}px atlas with ` +\n `tileGridSize ${tileSize}, spacing ${spacing} and padding ${margin}, which does not fit a single tile`,\n );\n }\n\n const tileCount = columns * rows;\n const region = new TextureRegion(texture, {\n x: 0,\n y: 0,\n width: def.pxWid,\n height: def.pxHei,\n });\n\n return new TileSet({\n name: def.identifier,\n texture: region,\n tileWidth: tileSize,\n tileHeight: tileSize,\n tileCount,\n columns,\n spacing,\n margin,\n });\n};\n\n// ── External level loading ───────────────────────────────────────────────────\n\n/**\n * Resolve a level's external `.ldtkl` payload and merge its layer/field data\n * into the level record.\n *\n * LDtk's \"Save levels to separate files\" project option nulls out\n * `layerInstances` on the root document; the real layer data lives in a\n * sibling `<levelIdentifier>.ldtkl` file referenced by {@link LdtkLevel.externalRelPath}.\n * That file also carries its own `fieldInstances`, which is authoritative -\n * the root document's copy is typically stripped or stale for externalized\n * levels. Levels that already carry `layerInstances` (not externalized) are\n * returned unchanged.\n */\nconst loadExternalLevel = async (level: LdtkLevel, ldtkSource: string, context: AssetFactoryContext): Promise<LdtkLevel> => {\n // Already-inlined level, or no external file to fetch: return as-is.\n if (level.layerInstances !== null || level.externalRelPath === undefined || level.externalRelPath === null || level.externalRelPath === '') {\n return level;\n }\n\n const externalUrl = resolveLdtkUrl(level.externalRelPath, ldtkSource);\n // Validated against the same level shape as an inlined level, with the\n // `.ldtkl` file itself as the error source - a malformed external payload\n // must fail as loudly as a malformed root document.\n const external = validateLdtkLevelData(await context.dependencies.load(Asset.type('json', externalUrl)), externalUrl);\n const fieldInstances = external.fieldInstances ?? level.fieldInstances;\n\n return {\n ...level,\n layerInstances: external.layerInstances,\n ...(fieldInstances !== undefined && { fieldInstances }),\n };\n};\n\n/**\n * Rebuild an {@link LdtkData} document with its levels replaced by\n * `resolvedLevels` (external `.ldtkl` payloads merged in via\n * {@link loadExternalLevel}), preserving whichever root shape the source\n * document used - single-world (`levels`) or multi-world (`worlds[].levels`).\n *\n * `resolvedLevels` must be in the same flattened order\n * {@link getLdtkLevelEntries} produced for `data` - each world's slice is\n * recovered by walking `data.worlds` in that same order, so a second pass\n * through {@link getLdtkLevelEntries} (performed inside {@link ldtkToTileMap})\n * reproduces an identical flattened list, now with external levels resolved.\n */\nconst withResolvedLevels = (data: LdtkData, resolvedLevels: readonly LdtkLevel[]): LdtkData => {\n if (data.worlds && data.worlds.length > 0) {\n let cursor = 0;\n const worlds = data.worlds.map(world => {\n const levels = resolvedLevels.slice(cursor, cursor + world.levels.length);\n cursor += world.levels.length;\n return { ...world, levels };\n });\n return { ...data, worlds };\n }\n\n return { ...data, levels: resolvedLevels };\n};\n\n// ── Public loader ─────────────────────────────────────────────────────────────\n\n/**\n * Read a `.ldtk` document, load all referenced tileset images, resolve any\n * externalized (`.ldtkl`) levels, and return a fully assembled {@link LdtkMap}\n * with one runtime {@link import('@codexo/exojs-tilemap').TileMap} per level.\n *\n * The fetched document - and every external `.ldtkl` payload - is validated\n * before use; a structural problem throws\n * {@link import('./validate').LdtkFormatError} naming the file and the\n * offending property path.\n *\n * A tileset whose declared atlas cannot hold a single tile is a\n * {@link import('./validate').LdtkFormatError} too - dropping it would make\n * every cell referencing it disappear without a diagnostic. An embed-atlas\n * tileset (`relPath = null`) is the one case that is skipped rather than\n * rejected, since its image lives inside the LDtk editor; that skip warns.\n * @internal\n */\nexport const loadLdtkMap = async (context: AssetFactoryContext): Promise<LdtkMap> => {\n const source = context.source;\n const data = validateLdtkData(await context.dependencies.load(Asset.type('json', source)), source);\n\n // Load all referenced tilesets and resolve externalized levels concurrently.\n // Iterate the flattened level list (not raw data.levels) so multi-world\n // documents - whose levels live under worlds[].levels, with an empty root\n // levels[] - still get their external .ldtkl files resolved.\n const [tilesetEntries, resolvedLevels] = await Promise.all([\n Promise.all(\n data.defs.tilesets.map(async def => {\n const ts = await loadLdtkTileset(def, source, context);\n return [def.uid, ts] as const;\n }),\n ),\n Promise.all(getLdtkLevelEntries(data).map(entry => loadExternalLevel(entry.level, source, context))),\n ]);\n\n const tilesets = new Map<number, TileSet>();\n for (const [uid, ts] of tilesetEntries) {\n if (ts !== null) tilesets.set(uid, ts);\n }\n\n return ldtkToTileMap(withResolvedLevels(data, resolvedLevels), { source, tilesets });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,kBAAkB,OAAO,KAAqB,YAAoB,YAA0D;CACvI,IAAI,IAAI,YAAY,QAAQ,IAAI,YAAY,IAAI;EAC9C,OAAO,KACL,kBAAkB,IAAI,WAAW,QAAQ,WAAW,yOAGpD,EAAE,QAAQ,OA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ojs';\nimport { logger, TextureRegion } from '@codexo/exojs';\nimport { type TileDefinition, TileSet } from '@codexo/exojs/tilemap';\n\nimport type { LdtkData, LdtkLevel, LdtkTilesetDef } from './LdtkData';\nimport { getLdtkLevelEntries } from './ldtkLevelEntries';\nimport type { LdtkMap } from './LdtkMap';\nimport { ldtkToTileMap } from './ldtkToTileMap';\nimport { resolveLdtkUrl } from './url';\nimport { LdtkFormatError, validateLdtkData, validateLdtkLevelData } from './validate';\n\n// ── Tileset loading ───────────────────────────────────────────────────────────\n\n/**\n * Load one LDtk tileset definition into a runtime {@link TileSet}.\n *\n * Returns `null` only for an embed-atlas tileset (`relPath` null or empty),\n * whose image ships with the LDtk editor and cannot be resolved from the\n * document - that case warns rather than passing unnoticed, because every tile\n * drawn from it is missing from the runtime map.\n *\n * @throws {LdtkFormatError} when the tileset names an atlas that cannot yield a\n * single tile (its declared size is smaller than one padded tile). Dropping it\n * would make every cell and entity referencing it vanish without a diagnostic.\n * @internal\n */\nexport const loadLdtkTileset = async (def: LdtkTilesetDef, ldtkSource: string, context: AssetFactoryContext): Promise<TileSet | null> => {\n if (def.relPath === null || def.relPath === '') {\n logger.warn(\n `LDtk: tileset \"${def.identifier}\" in \"${ldtkSource}\" has no atlas image (relPath is null) — it is an ` +\n 'embed-atlas tileset whose image lives inside the LDtk editor. Every tile drawn from it is omitted ' +\n 'from the runtime map. Re-export the tileset as a regular image atlas to render it.',\n { source: 'ldtk' },\n );\n\n return null;\n }\n\n const imageUrl = resolveLdtkUrl(def.relPath, ldtkSource);\n const texture = await context.dependencies.load({ type: 'texture', source: imageUrl });\n\n const tileSize = def.tileGridSize;\n const spacing = def.spacing ?? 0;\n const margin = def.padding ?? 0;\n\n // Compute columns / tileCount from atlas dimensions.\n const innerWidth = def.pxWid - margin * 2;\n const innerHeight = def.pxHei - margin * 2;\n const columns = Math.floor((innerWidth + spacing) / (tileSize + spacing));\n const rows = Math.floor((innerHeight + spacing) / (tileSize + spacing));\n\n if (columns <= 0 || rows <= 0) {\n throw new LdtkFormatError(\n ldtkSource,\n `defs.tilesets/${def.identifier}`,\n `tileset \"${def.identifier}\" declares a ${def.pxWid}×${def.pxHei}px atlas with ` +\n `tileGridSize ${tileSize}, spacing ${spacing} and padding ${margin}, which does not fit a single tile`,\n );\n }\n\n const tileCount = columns * rows;\n const region = new TextureRegion(texture, {\n x: 0,\n y: 0,\n width: def.pxWid,\n height: def.pxHei,\n });\n\n const tileset = new TileSet({\n name: def.identifier,\n texture: region,\n tileWidth: tileSize,\n tileHeight: tileSize,\n tileCount,\n columns,\n spacing,\n margin,\n });\n const definitions = buildLdtkTileDefinitions(def, tileCount);\n\n if (definitions.length > 0) {\n tileset.setDefinitions(definitions);\n }\n\n return tileset;\n};\n\n/**\n * Per-tile metadata authored in the LDtk tileset editor, as tile properties:\n * `ldtkCustomData` holds a tile's custom text and `ldtkEnumTags` the enum\n * values tagged on it. Ids outside the atlas are skipped.\n * @internal\n */\nexport const buildLdtkTileDefinitions = (def: LdtkTilesetDef, tileCount: number): TileDefinition[] => {\n const properties = new Map<number, { ldtkCustomData?: string; ldtkEnumTags?: string[] }>();\n\n const entry = (tileId: number): { ldtkCustomData?: string; ldtkEnumTags?: string[] } | undefined => {\n if (tileId >= tileCount) {\n return undefined;\n }\n\n let bag = properties.get(tileId);\n\n if (bag === undefined) {\n bag = {};\n properties.set(tileId, bag);\n }\n\n return bag;\n };\n\n for (const { tileId, data } of def.customData ?? []) {\n const bag = entry(tileId);\n\n if (bag !== undefined) {\n bag.ldtkCustomData = data;\n }\n }\n\n for (const { enumValueId, tileIds } of def.enumTags ?? []) {\n for (const tileId of tileIds) {\n const bag = entry(tileId);\n\n if (bag !== undefined) {\n bag.ldtkEnumTags = [...(bag.ldtkEnumTags ?? []), enumValueId];\n }\n }\n }\n\n return [...properties].map(([localTileId, bag]) => ({ localTileId, properties: bag }));\n};\n\n// ── External level loading ───────────────────────────────────────────────────\n\n/**\n * Resolve a level's external `.ldtkl` payload and merge its layer/field data\n * into the level record.\n *\n * LDtk's \"Save levels to separate files\" project option nulls out\n * `layerInstances` on the root document; the real layer data lives in a\n * sibling `<levelIdentifier>.ldtkl` file referenced by {@link LdtkLevel.externalRelPath}.\n * That file also carries its own `fieldInstances`, which is authoritative -\n * the root document's copy is typically stripped or stale for externalized\n * levels. Levels that already carry `layerInstances` (not externalized) are\n * returned unchanged.\n */\nconst loadExternalLevel = async (level: LdtkLevel, ldtkSource: string, context: AssetFactoryContext): Promise<LdtkLevel> => {\n // Already-inlined level, or no external file to fetch: return as-is.\n if (\n level.layerInstances !== null ||\n level.externalRelPath === undefined ||\n level.externalRelPath === null ||\n level.externalRelPath === ''\n ) {\n return level;\n }\n\n const externalUrl = resolveLdtkUrl(level.externalRelPath, ldtkSource);\n // Validated against the same level shape as an inlined level, with the\n // `.ldtkl` file itself as the error source - a malformed external payload\n // must fail as loudly as a malformed root document.\n const external = validateLdtkLevelData(await context.dependencies.load({ type: 'json', source: externalUrl }), externalUrl);\n const fieldInstances = external.fieldInstances ?? level.fieldInstances;\n\n return {\n ...level,\n layerInstances: external.layerInstances,\n ...(fieldInstances !== undefined && { fieldInstances }),\n };\n};\n\n/**\n * Rebuild an {@link LdtkData} document with its levels replaced by\n * `resolvedLevels` (external `.ldtkl` payloads merged in via\n * {@link loadExternalLevel}), preserving whichever root shape the source\n * document used - single-world (`levels`) or multi-world (`worlds[].levels`).\n *\n * `resolvedLevels` must be in the same flattened order\n * {@link getLdtkLevelEntries} produced for `data` - each world's slice is\n * recovered by walking `data.worlds` in that same order, so a second pass\n * through {@link getLdtkLevelEntries} (performed inside {@link ldtkToTileMap})\n * reproduces an identical flattened list, now with external levels resolved.\n */\nconst withResolvedLevels = (data: LdtkData, resolvedLevels: readonly LdtkLevel[]): LdtkData => {\n if (data.worlds && data.worlds.length > 0) {\n let cursor = 0;\n const worlds = data.worlds.map(world => {\n const levels = resolvedLevels.slice(cursor, cursor + world.levels.length);\n cursor += world.levels.length;\n\n return { ...world, levels };\n });\n\n return { ...data, worlds };\n }\n\n return { ...data, levels: resolvedLevels };\n};\n\n// ── Public loader ─────────────────────────────────────────────────────────────\n\n/**\n * Read a `.ldtk` document, load all referenced tileset images, resolve any\n * externalized (`.ldtkl`) levels, and return a fully assembled {@link LdtkMap}\n * with one runtime {@link import('@codexo/exojs-tilemap').TileMap} per level.\n *\n * The fetched document - and every external `.ldtkl` payload - is validated\n * before use; a structural problem throws\n * {@link import('./validate').LdtkFormatError} naming the file and the\n * offending property path.\n *\n * A tileset whose declared atlas cannot hold a single tile is a\n * {@link import('./validate').LdtkFormatError} too - dropping it would make\n * every cell referencing it disappear without a diagnostic. An embed-atlas\n * tileset (`relPath = null`) is the one case that is skipped rather than\n * rejected, since its image lives inside the LDtk editor; that skip warns.\n * @internal\n */\nexport const loadLdtkMap = async (context: AssetFactoryContext): Promise<LdtkMap> => {\n const source = context.source;\n const data = validateLdtkData(await context.dependencies.load({ type: 'json', source }), source);\n\n // Load all referenced tilesets and resolve externalized levels concurrently.\n // Iterate the flattened level list (not raw data.levels) so multi-world\n // documents - whose levels live under worlds[].levels, with an empty root\n // levels[] - still get their external .ldtkl files resolved.\n const [tilesetEntries, resolvedLevels] = await Promise.all([\n Promise.all(\n data.defs.tilesets.map(async def => {\n const ts = await loadLdtkTileset(def, source, context);\n\n return [def.uid, ts] as const;\n }),\n ),\n Promise.all(getLdtkLevelEntries(data).map(entry => loadExternalLevel(entry.level, source, context))),\n ]);\n\n const tilesets = new Map<number, TileSet>();\n\n for (const [uid, ts] of tilesetEntries) {\n if (ts !== null) {\n tilesets.set(uid, ts);\n }\n }\n\n return ldtkToTileMap(withResolvedLevels(data, resolvedLevels), { source, tilesets });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,kBAAkB,OAAO,KAAqB,YAAoB,YAA0D;CACvI,IAAI,IAAI,YAAY,QAAQ,IAAI,YAAY,IAAI;EAC9C,OAAO,KACL,kBAAkB,IAAI,WAAW,QAAQ,WAAW,yOAGpD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,OAAO;EAAE,GAAG;EAAM,QAAQ;CAAe;AAC3C;;;;;;;;;;;;;;;;;;AAqBA,MAAa,cAAc,OAAO,YAAmD;CACnF,MAAM,SAAS,QAAQ;CACvB,MAAM,OAAO,iBAAiB,MAAM,QAAQ,aAAa,KAAK;EAAE,MAAM;EAAQ;CAAO,CAAC,GAAG,MAAM;CAM/F,MAAM,CAAC,gBAAgB,kBAAkB,MAAM,QAAQ,IAAI,CACzD,QAAQ,IACN,KAAK,KAAK,SAAS,IAAI,OAAM,QAAO;EAClC,MAAM,KAAK,MAAM,gBAAgB,KAAK,QAAQ,OAAO;EAErD,OAAO,CAAC,IAAI,KAAK,EAAE;CACrB,CAAC,CACH,GACA,QAAQ,IAAI,oBAAoB,IAAI,CAAC,CAAC,KAAI,UAAS,kBAAkB,MAAM,OAAO,QAAQ,OAAO,CAAC,CAAC,CACrG,CAAC;CAED,MAAM,2BAAW,IAAI,IAAqB;CAE1C,KAAK,MAAM,CAAC,KAAK,OAAO,gBACtB,IAAI,OAAO,MACT,SAAS,IAAI,KAAK,EAAE;CAIxB,OAAO,cAAc,mBAAmB,MAAM,cAAc,GAAG;EAAE;EAAQ;CAAS,CAAC;AACrF"}
@@ -1 +1 @@
1
- {"version":3,"file":"loadLdtkProject.d.ts","sourceRoot":"","sources":["../../src/loadLdtkProject.ts"],"names":[],"mappings":""}
1
+ {"version":3,"file":"loadLdtkProject.d.ts","sources":["../../src/loadLdtkProject.ts"],"names":[],"mappings":""}
@@ -1,9 +1,8 @@
1
- import { validateLdtkData } from "./validate.js";
2
1
  import { LdtkProject } from "./LdtkProject.js";
3
2
  import { loadLdtkTileset } from "./loadLdtkMap.js";
4
- import { Asset } from "@codexo/exojs";
3
+ import { validateLdtkData } from "./validate.js";
5
4
 
6
- //#region src/loadLdtkProject.ts
5
+ // src/loadLdtkProject.ts
7
6
  /**
8
7
  * Read and validate a `.ldtk` document and load every tileset atlas it
9
8
  * references, without touching any level payload.
@@ -19,13 +18,15 @@ import { Asset } from "@codexo/exojs";
19
18
  */
20
19
  const loadLdtkProject = async (context) => {
21
20
  const source = context.source;
22
- const data = validateLdtkData(await context.dependencies.load(Asset.type("json", source)), source);
21
+ const data = validateLdtkData(await context.dependencies.load({
22
+ type: "json",
23
+ source
24
+ }), source);
23
25
  const tilesetEntries = await Promise.all(data.defs.tilesets.map(async (def) => [def.uid, await loadLdtkTileset(def, source, context)]));
24
26
  const tilesets = /* @__PURE__ */ new Map();
25
27
  for (const [uid, tileset] of tilesetEntries) if (tileset !== null) tilesets.set(uid, tileset);
26
28
  return new LdtkProject(source, data, tilesets);
27
29
  };
28
30
 
29
- //#endregion
30
31
  export { loadLdtkProject };
31
32
  //# sourceMappingURL=loadLdtkProject.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"loadLdtkProject.js","names":[],"sources":["../../src/loadLdtkProject.ts"],"sourcesContent":["import type { AssetFactoryContext } from '@codexo/exojs';\nimport { Asset } from '@codexo/exojs';\nimport type { TileSet } from '@codexo/exojs-tilemap';\n\nimport { LdtkProject } from './LdtkProject';\nimport { loadLdtkTileset } from './loadLdtkMap';\nimport { validateLdtkData } from './validate';\n\n/**\n * Read and validate a `.ldtk` document and load every tileset atlas it\n * references, without touching any level payload.\n *\n * External `.ldtkl` levels are deliberately left unfetched - that is the whole\n * point of {@link LdtkProject}: the world layout arrives, the levels arrive\n * when a level runtime asks for them.\n *\n * @throws {import('./validate').LdtkFormatError} for a structurally invalid\n * document, or a tileset whose declared atlas cannot hold a single tile. An\n * embed-atlas tileset (`relPath = null`) is skipped with a warning instead.\n * @internal\n */\nexport const loadLdtkProject = async (context: AssetFactoryContext): Promise<LdtkProject> => {\n const source = context.source;\n const data = validateLdtkData(await context.dependencies.load(Asset.type('json', source)), source);\n\n const tilesetEntries = await Promise.all(data.defs.tilesets.map(async def => [def.uid, await loadLdtkTileset(def, source, context)] as const));\n\n const tilesets = new Map<number, TileSet>();\n\n for (const [uid, tileset] of tilesetEntries) {\n if (tileset !== null) tilesets.set(uid, tileset);\n }\n\n return new LdtkProject(source, data, tilesets);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAqBA,MAAa,kBAAkB,OAAO,YAAuD;CAC3F,MAAM,SAAS,QAAQ;CACvB,MAAM,OAAO,iBAAiB,MAAM,QAAQ,aAAa,KAAK,MAAM,KAAK,QAAQ,MAAM,CAAC,GAAG,MAAM;CAEjG,MAAM,iBAAiB,MAAM,QAAQ,IAAI,KAAK,KAAK,SAAS,IAAI,OAAM,QAAO,CAAC,IAAI,KAAK,MAAM,gBAAgB,KAAK,QAAQ,OAAO,CAAC,CAAU,CAAC;CAE7I,MAAM,2BAAW,IAAI,IAAqB;CAE1C,KAAK,MAAM,CAAC,KAAK,YAAY,gBAC3B,IAAI,YAAY,MAAM,SAAS,IAAI,KAAK,OAAO;CAGjD,OAAO,IAAI,YAAY,QAAQ,MAAM,QAAQ;AAC/C"}
1
+ {"version":3,"file":"loadLdtkProject.js","names":[],"sources":["../../src/loadLdtkProject.ts"],"sourcesContent":["import type { AssetFactoryContext } from '@codexo/exojs';\nimport type { TileSet } from '@codexo/exojs/tilemap';\n\nimport { LdtkProject } from './LdtkProject';\nimport { loadLdtkTileset } from './loadLdtkMap';\nimport { validateLdtkData } from './validate';\n\n/**\n * Read and validate a `.ldtk` document and load every tileset atlas it\n * references, without touching any level payload.\n *\n * External `.ldtkl` levels are deliberately left unfetched - that is the whole\n * point of {@link LdtkProject}: the world layout arrives, the levels arrive\n * when a level runtime asks for them.\n *\n * @throws {import('./validate').LdtkFormatError} for a structurally invalid\n * document, or a tileset whose declared atlas cannot hold a single tile. An\n * embed-atlas tileset (`relPath = null`) is skipped with a warning instead.\n * @internal\n */\nexport const loadLdtkProject = async (context: AssetFactoryContext): Promise<LdtkProject> => {\n const source = context.source;\n const data = validateLdtkData(await context.dependencies.load({ type: 'json', source }), source);\n\n const tilesetEntries = await Promise.all(\n data.defs.tilesets.map(async def => [def.uid, await loadLdtkTileset(def, source, context)] as const),\n );\n\n const tilesets = new Map<number, TileSet>();\n\n for (const [uid, tileset] of tilesetEntries) {\n if (tileset !== null) {\n tilesets.set(uid, tileset);\n }\n }\n\n return new LdtkProject(source, data, tilesets);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAoBA,MAAa,kBAAkB,OAAO,YAAuD;CAC3F,MAAM,SAAS,QAAQ;CACvB,MAAM,OAAO,iBAAiB,MAAM,QAAQ,aAAa,KAAK;EAAE,MAAM;EAAQ;CAAO,CAAC,GAAG,MAAM;CAE/F,MAAM,iBAAiB,MAAM,QAAQ,IACnC,KAAK,KAAK,SAAS,IAAI,OAAM,QAAO,CAAC,IAAI,KAAK,MAAM,gBAAgB,KAAK,QAAQ,OAAO,CAAC,CAAU,CACrG;CAEA,MAAM,2BAAW,IAAI,IAAqB;CAE1C,KAAK,MAAM,CAAC,KAAK,YAAY,gBAC3B,IAAI,YAAY,MACd,SAAS,IAAI,KAAK,OAAO;CAI7B,OAAO,IAAI,YAAY,QAAQ,MAAM,QAAQ;AAC/C"}