@ignifx/editor-host 0.14.0 → 0.16.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.
package/dist/index.js CHANGED
@@ -187,8 +187,9 @@ const HostKind = {
187
187
  * The play controls send `"heartbeat"`, `"playControls"`, `"logRelay"` and `"queryRuntime"`, plus
188
188
  * `"screenshot"` when the game has a canvas and `"sendInput"` when it has `app.input`. The scene
189
189
  * host sends `"heartbeat"` and whichever of `"gizmos"`, `"screenshot"`, `"viewMode2d"`,
190
- * `"pick2d"`, `"gameView"` and `"thumbnails"` it supports; every `SceneMethod` not tied to one of
191
- * them is required of a 0.3 scene host.
190
+ * `"pick2d"`, `"gameView"`, `"thumbnails"`, `"grid"`, `"tilemapCells"`, `"editorLines"` and
191
+ * `"spriteAnimation"` it supports; every `SceneMethod` not tied to one of them is required of a
192
+ * 0.3 scene host.
192
193
  *
193
194
  * @public
194
195
  */
@@ -254,7 +255,34 @@ const HostCapability = {
254
255
  * (`RenderViewMethod`). From engine ask E8 (additive in 0.3); without it, the host answers it with
255
256
  * `RpcErrorCode.methodNotFound`.
256
257
  */
257
- thumbnails: "thumbnails"
258
+ thumbnails: "thumbnails",
259
+ /**
260
+ * The scene host draws a grid in the view and answers `setGrid`: a ground grid at `y = 0` in 3D
261
+ * view mode and a unit grid (a pixel grid when zoomed in) over the 2D view. From engine ask E31
262
+ * (additive in 0.3); without it, the scene host answers `setGrid` with
263
+ * `RpcErrorCode.methodNotFound`.
264
+ */
265
+ grid: "grid",
266
+ /**
267
+ * The scene host answers `setTilemapCells`: it writes cells into the open scene's live tilemaps,
268
+ * so a tilemap editor's painting shows without a save. Additive in 0.3; without it, the scene
269
+ * host answers `setTilemapCells` with `RpcErrorCode.methodNotFound`.
270
+ */
271
+ tilemapCells: "tilemapCells",
272
+ /**
273
+ * The scene host answers `setEditorLines` and `clearEditorLines`: it draws the editor's own line
274
+ * segments (collider outlines, handles) over the view in both view modes, never in a game view or
275
+ * the play view. Additive in 0.3; without it, the scene host answers both with
276
+ * `RpcErrorCode.methodNotFound`.
277
+ */
278
+ editorLines: "editorLines",
279
+ /**
280
+ * The scene host answers `sampleSpriteAnimation`: one frame of a clip on an entity's
281
+ * `SpriteAnimator` (`@ignifx/2d`), for the editor's sprite animation panel. From engine ask E51
282
+ * (additive in 0.3); without it, the scene host answers `sampleSpriteAnimation` with
283
+ * `RpcErrorCode.methodNotFound`.
284
+ */
285
+ spriteAnimation: "spriteAnimation"
258
286
  };
259
287
  /**
260
288
  * The longest string, in UTF-16 code units, the editor accepts from a host in `ready` (the engine
@@ -1098,7 +1126,35 @@ const SceneMethod = {
1098
1126
  * amendment 2026-10-20). Answers {@link SampleAnimationResult}. A host from before it answers
1099
1127
  * `RpcErrorCode.methodNotFound`. Additive in 0.3.
1100
1128
  */
1101
- sampleAnimation: "sampleAnimation"
1129
+ sampleAnimation: "sampleAnimation",
1130
+ /**
1131
+ * Shows one frame of a clip on an entity's `SpriteAnimator` without playing it (engine ask E51).
1132
+ * Needs `HostCapability.spriteAnimation`. Answers {@link SampleSpriteAnimationResult}. A host from
1133
+ * before it answers `RpcErrorCode.methodNotFound`. Additive in 0.3.
1134
+ */
1135
+ sampleSpriteAnimation: "sampleSpriteAnimation",
1136
+ /**
1137
+ * Shows or hides the view's grid and sets its spacing (engine ask E31). Needs
1138
+ * `HostCapability.grid`. Answers `null`. Additive in 0.3.
1139
+ */
1140
+ setGrid: "setGrid",
1141
+ /**
1142
+ * Writes cells of a tilemap asset into every live `Tilemap` of the open scene that shows it, so
1143
+ * painting is seen at once, without a save or a reopen. The file on disk is not touched. Needs
1144
+ * `HostCapability.tilemapCells`. Answers {@link SetTilemapCellsResult}. Additive in 0.3.
1145
+ */
1146
+ setTilemapCells: "setTilemapCells",
1147
+ /**
1148
+ * Draws a set of world-space line segments over the view, such as collider outlines or handles,
1149
+ * replacing the set of the same id. Needs `HostCapability.editorLines`. Answers `null`. Additive
1150
+ * in 0.3.
1151
+ */
1152
+ setEditorLines: "setEditorLines",
1153
+ /**
1154
+ * Removes one set of lines `setEditorLines` drew, or every set. Needs `HostCapability.editorLines`.
1155
+ * Answers `null`. Additive in 0.3.
1156
+ */
1157
+ clearEditorLines: "clearEditorLines"
1102
1158
  };
1103
1159
  /**
1104
1160
  * Scene host → editor: the notifications of protocol 0.3. None has an answer.
@@ -1275,6 +1331,44 @@ const ViewMode = {
1275
1331
  twoD: "2d"
1276
1332
  };
1277
1333
  /**
1334
+ * The smallest grid spacing `setGrid` accepts, in metres.
1335
+ *
1336
+ * @public
1337
+ */
1338
+ const GRID_MIN_SIZE = .001;
1339
+ /**
1340
+ * The largest grid spacing `setGrid` accepts, in metres.
1341
+ *
1342
+ * @public
1343
+ */
1344
+ const GRID_MAX_SIZE = 1e3;
1345
+ /**
1346
+ * The most numbers the `cells` of one `setTilemapCells` request may hold: a million cells. A request
1347
+ * with more fails with `invalidParams`.
1348
+ *
1349
+ * @public
1350
+ */
1351
+ const TILEMAP_CELLS_MAX_NUMBERS = 2e6;
1352
+ /**
1353
+ * The most numbers the `lines` of one `setEditorLines` request may hold: 100 000 segments.
1354
+ *
1355
+ * @public
1356
+ */
1357
+ const EDITOR_LINES_MAX_NUMBERS = 6e5;
1358
+ /**
1359
+ * The most line sets the view draws at once; a `setEditorLines` for a new id past it fails with
1360
+ * `invalidParams`.
1361
+ *
1362
+ * @public
1363
+ */
1364
+ const EDITOR_LINES_MAX_SETS = 64;
1365
+ /**
1366
+ * The longest line set id, in UTF-16 code units.
1367
+ *
1368
+ * @public
1369
+ */
1370
+ const EDITOR_LINES_MAX_ID_LENGTH = 256;
1371
+ /**
1278
1372
  * Tells whether a value is one of an `as const` object's values.
1279
1373
  *
1280
1374
  * @param names - The object.
@@ -1590,6 +1684,79 @@ function isSetAnimateMaterialsParams(value) {
1590
1684
  return isRecord(value) && isBoolean(value["enabled"]);
1591
1685
  }
1592
1686
  /**
1687
+ * Checks the parameters of `setGrid`.
1688
+ *
1689
+ * @param value - The received `params`.
1690
+ * @returns True for an object whose `visible`, if present, is a boolean and whose `size`, if
1691
+ * present, is a number from {@link GRID_MIN_SIZE} to {@link GRID_MAX_SIZE}.
1692
+ *
1693
+ * @public
1694
+ */
1695
+ function isSetGridParams(value) {
1696
+ if (!isRecord(value)) return false;
1697
+ const size = value["size"];
1698
+ return optionalField(value, "visible", isBoolean) && (size === void 0 || isFiniteNumber(size) && size >= .001 && size <= 1e3);
1699
+ }
1700
+ /**
1701
+ * Checks the parameters of `setTilemapCells`.
1702
+ *
1703
+ * @param value - The received `params`.
1704
+ * @returns True for a non-empty `asset`, a layer name or index, and an even-length list of at most
1705
+ * {@link TILEMAP_CELLS_MAX_NUMBERS} non-negative integers.
1706
+ *
1707
+ * @public
1708
+ */
1709
+ function isSetTilemapCellsParams(value) {
1710
+ if (!isRecord(value)) return false;
1711
+ const { asset, layer, cells } = value;
1712
+ return isUidString(asset) && (isString(layer) || isCount(layer)) && Array.isArray(cells) && cells.length % 2 === 0 && cells.length <= 2e6 && cells.every((item) => isCount(item));
1713
+ }
1714
+ /**
1715
+ * Checks the result of `setTilemapCells`.
1716
+ *
1717
+ * @param value - The received `result`.
1718
+ * @returns True for two counts.
1719
+ *
1720
+ * @public
1721
+ */
1722
+ function isSetTilemapCellsResult(value) {
1723
+ return isRecord(value) && isCount(value["tilemaps"]) && isCount(value["changed"]);
1724
+ }
1725
+ /**
1726
+ * Tells whether a value is a line set id.
1727
+ *
1728
+ * @param value - The value to test.
1729
+ * @returns True for a non-empty string of at most {@link EDITOR_LINES_MAX_ID_LENGTH} code units.
1730
+ */
1731
+ function isLineSetId(value) {
1732
+ return isUidString(value) && value.length <= 256;
1733
+ }
1734
+ /**
1735
+ * Checks the parameters of `setEditorLines`.
1736
+ *
1737
+ * @param value - The received `params`.
1738
+ * @returns True for an id, a list of finite numbers whose length is a multiple of six and at most
1739
+ * {@link EDITOR_LINES_MAX_NUMBERS}, and an optional colour of three or four numbers from 0 to 1.
1740
+ *
1741
+ * @public
1742
+ */
1743
+ function isSetEditorLinesParams(value) {
1744
+ if (!isRecord(value)) return false;
1745
+ const { lines, color } = value;
1746
+ return isLineSetId(value["id"]) && isArrayOf(lines, isFiniteNumber) && lines.length % 6 === 0 && lines.length <= 6e5 && (color === void 0 || (isNumberTuple(color, 3) || isNumberTuple(color, 4)) && isArrayOf(color, isFiniteNumber) && color.every((channel) => channel >= 0 && channel <= 1));
1747
+ }
1748
+ /**
1749
+ * Checks the parameters of `clearEditorLines`.
1750
+ *
1751
+ * @param value - The received `params`.
1752
+ * @returns True for an object whose `id`, if present, is a line set id.
1753
+ *
1754
+ * @public
1755
+ */
1756
+ function isClearEditorLinesParams(value) {
1757
+ return isRecord(value) && optionalField(value, "id", isLineSetId);
1758
+ }
1759
+ /**
1593
1760
  * Checks one record of `getColliderOutlines`.
1594
1761
  *
1595
1762
  * @param value - The value to test.
@@ -1663,6 +1830,32 @@ function isSampleAnimationResult(value) {
1663
1830
  return isRecord(value) && isBoolean(value["posed"]);
1664
1831
  }
1665
1832
  /**
1833
+ * Checks the parameters of `sampleSpriteAnimation`.
1834
+ *
1835
+ * @param value - The received `params`.
1836
+ * @returns True for a uid, a clip name within {@link SAMPLE_ANIMATION_MAX_NAME_LENGTH}, and exactly
1837
+ * one of a finite `frame` and a finite `time`.
1838
+ *
1839
+ * @public
1840
+ */
1841
+ function isSampleSpriteAnimationParams(value) {
1842
+ if (!isRecord(value) || !isUidString(value["entity"]) || !isBoundedName(value["entity"]) || !isBoundedName(value["clip"])) return false;
1843
+ const frame = value["frame"];
1844
+ const time = value["time"];
1845
+ return frame === void 0 ? isFiniteNumber(time) : isFiniteNumber(frame) && time === void 0;
1846
+ }
1847
+ /**
1848
+ * Checks the result of `sampleSpriteAnimation`.
1849
+ *
1850
+ * @param value - The received `result`.
1851
+ * @returns True for `{ posed: boolean }`.
1852
+ *
1853
+ * @public
1854
+ */
1855
+ function isSampleSpriteAnimationResult(value) {
1856
+ return isRecord(value) && isBoolean(value["posed"]);
1857
+ }
1858
+ /**
1666
1859
  * Checks the parameters of `sceneOpened`.
1667
1860
  *
1668
1861
  * @param value - The received `params`.
@@ -4335,7 +4528,7 @@ function isSpriteLike(component) {
4335
4528
  * @param component - The component.
4336
4529
  * @returns True when it reports its cell size and layer sizes.
4337
4530
  */
4338
- function isTilemapLike(component) {
4531
+ function isTilemapLike$1(component) {
4339
4532
  return typeof Reflect.get(component, "cellSize") === "number" && typeof Reflect.get(component, "layerCount") === "number" && typeof Reflect.get(component, "layerSize") === "function";
4340
4533
  }
4341
4534
  /**
@@ -4369,7 +4562,7 @@ function boundsOf2D(app, entities) {
4369
4562
  });
4370
4563
  }
4371
4564
  for (const component of tilemap === null ? [] : entity.getComponentsInChildren(tilemap, true)) {
4372
- const extent = isTilemapLike(component) ? tilemapBox(component) : null;
4565
+ const extent = isTilemapLike$1(component) ? tilemapBox(component) : null;
4373
4566
  if (extent !== null) box = union(box, extent);
4374
4567
  }
4375
4568
  }
@@ -4700,6 +4893,37 @@ var EditorCamera2D = class extends Script {
4700
4893
  }
4701
4894
  };
4702
4895
  //#endregion
4896
+ //#region src/scene/editor-grid.ts
4897
+ /**
4898
+ * The scene view's grid (engine ask E31): a script on the `Scene Grid` entity of the host's
4899
+ * persistent `editor` scene, which moves the grid with the editor camera every frame.
4900
+ */
4901
+ /**
4902
+ * Places the view's grid every frame, where {@link EditorGrid.placement} says.
4903
+ *
4904
+ * @remarks
4905
+ * The host sets both fields: `view` once a canvas has the grid's meshes (never headless), and
4906
+ * `placement` to read the editor cameras and the `setGrid` settings.
4907
+ */
4908
+ var EditorGrid = class extends Script {
4909
+ /** The type id; the host leaves it out of the schemas it reports. */
4910
+ static typeId = "ignifx-editor/EditorGrid";
4911
+ /** The scene view runs in edit mode, where only these scripts get callbacks. */
4912
+ static runInEditMode = true;
4913
+ /** The grid's meshes, or `null` while there is nothing to draw on. */
4914
+ view = null;
4915
+ /**
4916
+ * Reads this frame's grid.
4917
+ *
4918
+ * @returns The placement, or `null` to hide the grid.
4919
+ */
4920
+ placement = () => null;
4921
+ /** Moves the grid after the cameras have moved. */
4922
+ lateUpdate() {
4923
+ this.view?.place(this.placement());
4924
+ }
4925
+ };
4926
+ //#endregion
4703
4927
  //#region src/scene/view-math.ts
4704
4928
  /**
4705
4929
  * The arithmetic of the scene view's methods that needs no GPU: the `pick` unit rule, the ray and
@@ -5230,6 +5454,74 @@ var GizmoDragRelay = class {
5230
5454
  }
5231
5455
  };
5232
5456
  //#endregion
5457
+ //#region src/scene/grid.ts
5458
+ /** Every how many minor lines a major line falls. */
5459
+ const MAJOR_EVERY = 10;
5460
+ /** The 3D grid's spacing grows tenfold for each tenfold of eye height above this many minor lines. */
5461
+ const GROUND_LINES_PER_HEIGHT = 25;
5462
+ /** The 3D grid reaches this many eye heights from the eye before it has faded out. */
5463
+ const GROUND_REACH_PER_HEIGHT = 40;
5464
+ /** The 3D grid reaches at least this many lines from the eye. */
5465
+ const GROUND_MIN_REACH_LINES = 100;
5466
+ /** The 2D grid's lines are never closer than this, in screen pixels; denser ones step up tenfold. */
5467
+ const MIN_LINE_GAP_PX = 8;
5468
+ /**
5469
+ * The 3D view's ground grid: centred under the eye, coarser the higher the eye is, and large enough
5470
+ * that it fades out before its edge is in view.
5471
+ *
5472
+ * @param eye - The editor camera's position, in metres.
5473
+ * @param size - The spacing `setGrid` asked for, in metres.
5474
+ * @param far - The camera's far plane, in metres; the grid stays inside it.
5475
+ * @returns The placement.
5476
+ */
5477
+ function groundGridPlacement(eye, size, far) {
5478
+ const height = Math.max(Math.abs(eye.y), size);
5479
+ const step = size * 10 ** Math.max(0, Math.floor(Math.log10(height / (size * GROUND_LINES_PER_HEIGHT))));
5480
+ const reach = Math.min(Math.max(height * GROUND_REACH_PER_HEIGHT, step * GROUND_MIN_REACH_LINES), far * .9);
5481
+ return {
5482
+ plane: "ground",
5483
+ centerX: eye.x,
5484
+ centerY: eye.z,
5485
+ extent: reach * 2,
5486
+ step,
5487
+ majorEvery: MAJOR_EVERY
5488
+ };
5489
+ }
5490
+ /**
5491
+ * The 2D view's grid: lines `size` apart (tenfold coarser while they would be closer than a few
5492
+ * screen pixels), or one line per layer pixel from {@link PIXEL_GRID_ZOOM} on, with a major line
5493
+ * every `size`. It covers the whole view.
5494
+ *
5495
+ * @param view - What the 2D editor camera shows.
5496
+ * @param size - The spacing `setGrid` asked for, in metres.
5497
+ * @returns The placement.
5498
+ */
5499
+ function screenGridPlacement(view, size) {
5500
+ const pixelsPerMetre = Math.max(view.zoom * view.pixelsPerUnit, Number.MIN_VALUE);
5501
+ const extent = 2 * Math.max(view.widthPx, view.heightPx) / pixelsPerMetre;
5502
+ const base = {
5503
+ plane: "screen",
5504
+ centerX: view.centerX,
5505
+ centerY: view.centerY,
5506
+ extent
5507
+ };
5508
+ if (view.zoom >= 8 && view.pixelsPerUnit > 0) {
5509
+ const step = 1 / view.pixelsPerUnit;
5510
+ return {
5511
+ ...base,
5512
+ step,
5513
+ majorEvery: Math.max(1, Math.round(size / step))
5514
+ };
5515
+ }
5516
+ let step = size;
5517
+ while (step * pixelsPerMetre < MIN_LINE_GAP_PX) step *= MAJOR_EVERY;
5518
+ return {
5519
+ ...base,
5520
+ step,
5521
+ majorEvery: MAJOR_EVERY
5522
+ };
5523
+ }
5524
+ //#endregion
5233
5525
  //#region src/scene/json.ts
5234
5526
  /**
5235
5527
  * The uid of a referenced entity or component.
@@ -6234,6 +6526,41 @@ function sampleAnimation(app, mirror, params) {
6234
6526
  }
6235
6527
  }
6236
6528
  //#endregion
6529
+ //#region src/scene/sample-sprite-animation.ts
6530
+ /**
6531
+ * `sampleSpriteAnimation`: the scene view shows one frame of a clip on an entity's `SpriteAnimator`
6532
+ * (engine ask E51), through `@ignifx/2d`'s `SpriteAnimator.sample` and `sampleTime`. The host
6533
+ * depends on core only, so it finds the `SpriteAnimator` by its type id and calls them by shape.
6534
+ */
6535
+ /** The type id `@ignifx/2d` registers its `SpriteAnimator` under. */
6536
+ const SPRITE_ANIMATOR_TYPE_ID = "ignifx/SpriteAnimator";
6537
+ /**
6538
+ * Answers `sampleSpriteAnimation` on the open document.
6539
+ *
6540
+ * @param app - The scene view's app.
6541
+ * @param mirror - The open document.
6542
+ * @param params - The received `params`.
6543
+ * @returns Whether the frame was written.
6544
+ * @throws InvalidParamsError for malformed params, an entity the document lacks or one without a
6545
+ * `SpriteAnimator`, and any `IgnifxError` the engine throws, whose code it carries as `data.code`.
6546
+ */
6547
+ function sampleSpriteAnimation(app, mirror, params) {
6548
+ if (!isSampleSpriteAnimationParams(params)) throw new InvalidParamsError(`sampleSpriteAnimation takes { entity: uid, clip: string, frame: number } or { entity: uid, clip: string, time: number }, with names of at most ${String(256)} characters.`);
6549
+ const entity = mirror.index()?.entities.get(params.entity);
6550
+ if (entity === void 0) throw new InvalidParamsError(`sampleSpriteAnimation names ${params.entity}, which is not an entity of the open scene.`);
6551
+ const type = componentTypeOf(app, SPRITE_ANIMATOR_TYPE_ID);
6552
+ const animator = type === null ? null : entity.getComponent(type);
6553
+ const byTime = params.frame === void 0;
6554
+ const method = animator === null ? void 0 : Reflect.get(animator, byTime ? "sampleTime" : "sample");
6555
+ if (animator === null || typeof method !== "function") throw new InvalidParamsError(`The entity ${params.entity} has no SpriteAnimator to sample.`);
6556
+ try {
6557
+ return { posed: Reflect.apply(method, animator, [params.clip, params.frame ?? params.time ?? 0]) === true };
6558
+ } catch (error) {
6559
+ if (isIgnifxError(error)) throw new InvalidParamsError(error.message, { code: error.code });
6560
+ throw error;
6561
+ }
6562
+ }
6563
+ //#endregion
6237
6564
  //#region src/scene/schemas.ts
6238
6565
  /**
6239
6566
  * `getSchemas` and `schemasChanged`: every registered component's schema, as the inspector reads
@@ -6686,6 +7013,81 @@ function frameCamera(camera, bounds) {
6686
7013
  camera.far = distance + radius * 1.5;
6687
7014
  }
6688
7015
  //#endregion
7016
+ //#region src/scene/tilemap-cells.ts
7017
+ /**
7018
+ * `setTilemapCells`: a tilemap editor's painting, written into the open scene's live `Tilemap`s so
7019
+ * it shows at once. The host reaches `Tilemap` by type id and its members by shape, as
7020
+ * `./view-2d.ts` does, so it does not depend on `@ignifx/2d`.
7021
+ */
7022
+ /**
7023
+ * Turns the file-ordered `[index, tile, …]` pairs of `setTilemapCells` into `Tilemap.setCells`
7024
+ * writes, whose rows count from the bottom.
7025
+ *
7026
+ * @param layers - The document's layers.
7027
+ * @param layer - The layer's name or index.
7028
+ * @param cells - The flat pairs, the index row-major with the top row first.
7029
+ * @returns The writes, or why the request does not fit the document.
7030
+ */
7031
+ function planTileWrites(layers, layer, cells) {
7032
+ const index = typeof layer === "number" ? layer : layers.findIndex((candidate) => candidate.name === layer);
7033
+ const declared = layers[index];
7034
+ if (declared === void 0) return `The tilemap has no layer ${JSON.stringify(layer)}.`;
7035
+ const { width, height } = declared;
7036
+ const writes = [];
7037
+ for (let at = 0; at + 1 < cells.length; at += 2) {
7038
+ const cell = cells[at] ?? 0;
7039
+ if (cell >= width * height) return `Cell ${String(cell)} is outside layer ${JSON.stringify(declared.name)} (${String(width)}×${String(height)}).`;
7040
+ const row = Math.floor(cell / width);
7041
+ writes.push({
7042
+ layer: index,
7043
+ x: cell % width,
7044
+ y: height - 1 - row,
7045
+ tileId: cells[at + 1] ?? 0
7046
+ });
7047
+ }
7048
+ return writes;
7049
+ }
7050
+ /**
7051
+ * Tells whether a component has the `Tilemap` members the host uses.
7052
+ *
7053
+ * @param component - The component.
7054
+ * @returns True for a `map`, a `definition` and a `setCells` method.
7055
+ */
7056
+ function isTilemapLike(component) {
7057
+ return Reflect.has(component, "map") && Reflect.has(component, "definition") && typeof Reflect.get(component, "setCells") === "function";
7058
+ }
7059
+ /**
7060
+ * Writes the cells into every `Tilemap` under the roots whose `map` is the asset and has loaded.
7061
+ * Every tilemap's writes are checked before any is made.
7062
+ *
7063
+ * @param app - The scene view's app.
7064
+ * @param roots - The open scene's root entities.
7065
+ * @param params - The request.
7066
+ * @returns How many tilemaps were written and how many cells changed.
7067
+ * @throws InvalidParamsError when the layer or a cell does not fit a tilemap's document.
7068
+ */
7069
+ function setTilemapCells(app, roots, params) {
7070
+ const type = componentTypeOf(app, TILEMAP_TYPE);
7071
+ if (type === null) return {
7072
+ tilemaps: 0,
7073
+ changed: 0
7074
+ };
7075
+ const planned = [];
7076
+ for (const root of roots) for (const component of root.getComponentsInChildren(type, true)) {
7077
+ const layers = isTilemapLike(component) ? component.definition?.layers : void 0;
7078
+ if (!isTilemapLike(component) || component.map?.address !== params.asset || layers === void 0) continue;
7079
+ const writes = planTileWrites(layers, params.layer, params.cells);
7080
+ if (typeof writes === "string") throw new InvalidParamsError(`setTilemapCells: ${params.asset}: ${writes}`);
7081
+ planned.push([component, writes]);
7082
+ }
7083
+ let changed = 0;
7084
+ for (const [tilemap, writes] of planned) changed += tilemap.setCells(writes);
7085
+ return {
7086
+ tilemaps: planned.length,
7087
+ changed
7088
+ };
7089
+ }
7090
+ //#endregion
6689
7091
  //#region src/scene/scene-host.ts
6690
7092
  /**
6691
7093
  * The scene methods and notifications of protocol 0.3: what the scene view's host does with the
@@ -6693,6 +7095,13 @@ function frameCamera(camera, bounds) {
6693
7095
  */
6694
7096
  /** The name of the host's persistent scene instance for its own objects. */
6695
7097
  const EDITOR_SCENE_NAME = "editor";
7098
+ /** The colour of an editor line set that names none: a light green, as collider gizmos usually are. */
7099
+ const DEFAULT_LINE_COLOR = {
7100
+ r: .55,
7101
+ g: 1,
7102
+ b: .55,
7103
+ a: 1
7104
+ };
6696
7105
  /** The editor camera's priority: above any camera a document can hold. */
6697
7106
  const EDITOR_CAMERA_PRIORITY = 1e6;
6698
7107
  /**
@@ -6727,6 +7136,16 @@ var SceneHost = class {
6727
7136
  space: GizmoSpace.world,
6728
7137
  snap: null
6729
7138
  };
7139
+ /** The script that moves the grid, on the `editor` scene's `Scene Grid` entity. */
7140
+ #grid = null;
7141
+ #gridSettings = {
7142
+ visible: true,
7143
+ size: 1
7144
+ };
7145
+ /** The editor's line sets, as `setEditorLines` last set them, by id; drawn once `#lines` exists. */
7146
+ #lineSets = /* @__PURE__ */ new Map();
7147
+ /** The line sets' meshes, once a canvas has an overlay (never headless). */
7148
+ #lines = null;
6730
7149
  #drag;
6731
7150
  #gameView = new GameView();
6732
7151
  #thumbnails;
@@ -6763,6 +7182,7 @@ var SceneHost = class {
6763
7182
  [SceneMethod.getColliderOutlines, (params) => this.#getColliderOutlines(params)],
6764
7183
  [SceneMethod.sampleAnimation, (params) => this.#sampleAnimation(params)]
6765
7184
  ]);
7185
+ if (has(HostCapability.spriteAnimation)) methods.set(SceneMethod.sampleSpriteAnimation, (params) => this.#sampleSpriteAnimation(params));
6766
7186
  if (has(HostCapability.gizmos)) methods.set(SceneMethod.setGizmo, (params) => this.#setGizmo(params));
6767
7187
  if (has(HostCapability.screenshot)) methods.set(SceneMethod.screenshot, async (params) => this.#screenshot(params));
6768
7188
  if (has(HostCapability.gameView)) {
@@ -6783,6 +7203,12 @@ var SceneHost = class {
6783
7203
  this.#requireMirror(RenderViewMethod.renderThumbnail);
6784
7204
  return thumbnails.render(params);
6785
7205
  });
7206
+ if (has(HostCapability.grid)) methods.set(SceneMethod.setGrid, (params) => this.#setGrid(params));
7207
+ if (has(HostCapability.tilemapCells)) methods.set(SceneMethod.setTilemapCells, (params) => this.#setTilemapCells(params));
7208
+ if (has(HostCapability.editorLines)) {
7209
+ methods.set(SceneMethod.setEditorLines, (params) => this.#setEditorLines(params));
7210
+ methods.set(SceneMethod.clearEditorLines, (params) => this.#clearEditorLines(params));
7211
+ }
6786
7212
  this.methods = new Map([...methods].map(([name, handler]) => [name, async (params) => this.#serial(() => handler(params))]));
6787
7213
  }
6788
7214
  /**
@@ -6794,7 +7220,7 @@ var SceneHost = class {
6794
7220
  return this.#editorScene;
6795
7221
  }
6796
7222
  /**
6797
- * Prepares the app before it starts: the persistent `editor` scene with the editor camera, and
7223
+ * Prepares the app before it starts: the persistent `editor` scene with the editor camera and grid, and
6798
7224
  * the log, error and hot-reload relays.
6799
7225
  *
6800
7226
  * @param app - The scene view's app, created and not yet started.
@@ -6804,7 +7230,11 @@ var SceneHost = class {
6804
7230
  this.#mirror = new DocumentMirror(app);
6805
7231
  const scene = app.world.createScene(EDITOR_SCENE_NAME, { persistent: true });
6806
7232
  this.#editorScene = scene;
6807
- app.registerComponents([EditorCamera, EditorCamera2D]);
7233
+ app.registerComponents([
7234
+ EditorCamera,
7235
+ EditorCamera2D,
7236
+ EditorGrid
7237
+ ]);
6808
7238
  const eye = app.world.createEntity("Editor Camera", { scene });
6809
7239
  this.#eye = eye.addComponent(Camera, {
6810
7240
  fov: 50,
@@ -6826,6 +7256,11 @@ var SceneHost = class {
6826
7256
  twoD.attach(this.#eye, isCamera2DLike(camera2D) ? camera2D : null);
6827
7257
  twoD.pixelsPerUnit = () => twoDServiceOf(app)?.pixelsPerUnit ?? 100;
6828
7258
  this.#camera2D = twoD;
7259
+ if (this.methods.has(SceneMethod.setGrid)) {
7260
+ const grid = app.world.createEntity("Scene Grid", { scene }).addComponent(EditorGrid);
7261
+ grid.placement = () => this.#gridPlacement();
7262
+ this.#grid = grid;
7263
+ }
6829
7264
  this.#cleanups.push(relayAppReports(app, {
6830
7265
  log: (params) => {
6831
7266
  this.#notify(SceneNotification.log, params);
@@ -6849,12 +7284,23 @@ var SceneHost = class {
6849
7284
  const app = this.#requireApp();
6850
7285
  this.#canvas = canvas;
6851
7286
  if (canvas !== null && !app.isHeadless && this.methods.has(SceneMethod.setGizmo) && isDomCanvas(canvas)) {
6852
- const view = createEditorView(app.lite, await app.renderer.openOverlay(), canvas);
7287
+ const overlay = await app.renderer.openOverlay();
7288
+ const view = createEditorView(app.lite, overlay, canvas);
6853
7289
  view.onDrag((phase, drag) => {
6854
7290
  this.#onDrag(phase, drag);
6855
7291
  });
6856
7292
  this.#view = view;
6857
7293
  this.#applyGizmo();
7294
+ if (this.methods.has(SceneMethod.setGrid) && this.#grid !== null) {
7295
+ const { createEditorGrid } = await import("./grid.js");
7296
+ this.#grid.view = createEditorGrid(app.lite, overlay);
7297
+ }
7298
+ if (this.methods.has(SceneMethod.setEditorLines)) {
7299
+ const { createEditorLines } = await import("./editor-lines.js");
7300
+ const lines = createEditorLines(app.lite, overlay);
7301
+ for (const [id, set] of this.#lineSets) lines.set(id, set.lines, set.color);
7302
+ this.#lines = lines;
7303
+ }
6858
7304
  const onClick = (click) => {
6859
7305
  this.#onClick(click).catch((error) => {
6860
7306
  const params = {
@@ -6988,6 +7434,12 @@ var SceneHost = class {
6988
7434
  dispose() {
6989
7435
  for (const pending of this.#reloads) pending.cancel();
6990
7436
  for (const cleanup of this.#cleanups.splice(0)) cleanup();
7437
+ if (this.#grid !== null) {
7438
+ this.#grid.view?.dispose();
7439
+ this.#grid.view = null;
7440
+ }
7441
+ this.#lines?.dispose();
7442
+ this.#lines = null;
6991
7443
  this.#view?.dispose();
6992
7444
  this.#view = null;
6993
7445
  this.#gameView.dispose();
@@ -7191,6 +7643,88 @@ var SceneHost = class {
7191
7643
  return null;
7192
7644
  }
7193
7645
  /**
7646
+ * `setGrid`: shows or hides the view's grid and sets its spacing. A field left out takes its
7647
+ * default.
7648
+ *
7649
+ * @param params - `{ visible?, size? }`.
7650
+ * @returns `null`.
7651
+ */
7652
+ #setGrid(params) {
7653
+ this.#requireMirror(SceneMethod.setGrid);
7654
+ if (!isSetGridParams(params)) throw new InvalidParamsError("setGrid takes { visible?: boolean, size?: number from 0.001 to 1000 }.");
7655
+ this.#gridSettings = {
7656
+ visible: params.visible ?? true,
7657
+ size: params.size ?? 1
7658
+ };
7659
+ return null;
7660
+ }
7661
+ /**
7662
+ * `setTilemapCells`: writes a tilemap editor's cells into the open scene's live tilemaps that
7663
+ * show the asset. The file on disk is the editor's to save.
7664
+ *
7665
+ * @param params - `{ asset, layer, cells }`.
7666
+ * @returns How many tilemaps were written and how many cells changed.
7667
+ */
7668
+ #setTilemapCells(params) {
7669
+ const mirror = this.#requireMirror(SceneMethod.setTilemapCells);
7670
+ if (!isSetTilemapCellsParams(params)) throw new InvalidParamsError("setTilemapCells takes { asset: string, layer: string | number, cells: [index, tile, …] } of non-negative integers.");
7671
+ this.#requireOpen(SceneMethod.setTilemapCells);
7672
+ return setTilemapCells(this.#requireApp(), mirror.scene?.roots ?? [], params);
7673
+ }
7674
+ /**
7675
+ * `setEditorLines`: draws a set of the editor's world-space lines over the view, replacing the
7676
+ * set of the same id. Kept across scene opens; a page load starts with none.
7677
+ *
7678
+ * @param params - `{ id, lines, color? }`.
7679
+ * @returns `null`.
7680
+ */
7681
+ #setEditorLines(params) {
7682
+ this.#requireMirror(SceneMethod.setEditorLines);
7683
+ if (!isSetEditorLinesParams(params)) throw new InvalidParamsError("setEditorLines takes { id: string, lines: number[] (six per segment), color?: [r, g, b, a?] from 0 to 1 }.");
7684
+ if (!this.#lineSets.has(params.id) && this.#lineSets.size >= 64) throw new InvalidParamsError(`The view draws at most ${String(64)} line sets; clear one first.`);
7685
+ const [r = 0, g = 0, b = 0, a = 1] = params.color ?? [];
7686
+ const color = params.color === void 0 ? DEFAULT_LINE_COLOR : {
7687
+ r,
7688
+ g,
7689
+ b,
7690
+ a
7691
+ };
7692
+ this.#lineSets.set(params.id, {
7693
+ lines: params.lines,
7694
+ color
7695
+ });
7696
+ this.#lines?.set(params.id, params.lines, color);
7697
+ return null;
7698
+ }
7699
+ /**
7700
+ * `clearEditorLines`: removes one line set, or every set.
7701
+ *
7702
+ * @param params - `{ id? }`.
7703
+ * @returns `null`.
7704
+ */
7705
+ #clearEditorLines(params) {
7706
+ this.#requireMirror(SceneMethod.clearEditorLines);
7707
+ if (!isClearEditorLinesParams(params)) throw new InvalidParamsError("clearEditorLines takes { id?: string }.");
7708
+ const id = params.id ?? null;
7709
+ if (id === null) this.#lineSets.clear();
7710
+ else this.#lineSets.delete(id);
7711
+ this.#lines?.clear(id);
7712
+ return null;
7713
+ }
7714
+ /**
7715
+ * Where the grid draws this frame: on the ground under the 3D editor camera, or over the 2D view.
7716
+ *
7717
+ * @returns The placement, or `null` while the grid is hidden.
7718
+ */
7719
+ #gridPlacement() {
7720
+ const { visible, size } = this.#gridSettings;
7721
+ if (!visible) return null;
7722
+ const camera2D = this.#camera2D;
7723
+ if (this.#viewMode === ViewMode.twoD && camera2D !== null) return screenGridPlacement(camera2D.view(), size);
7724
+ const eye = this.#eye;
7725
+ return eye === null ? null : groundGridPlacement(eye.transform.position, size, eye.far);
7726
+ }
7727
+ /**
7194
7728
  * `getColliderOutlines`: the world-space outlines of the requested entities' colliders, from the
7195
7729
  * project's physics extensions, for the editor's collider gizmos. Changes nothing.
7196
7730
  *
@@ -7216,6 +7750,17 @@ var SceneHost = class {
7216
7750
  return sampleAnimation(this.#requireApp(), mirror, params);
7217
7751
  }
7218
7752
  /**
7753
+ * `sampleSpriteAnimation`: shows one frame of a clip on an entity's `SpriteAnimator`.
7754
+ *
7755
+ * @param params - `{ entity, clip, frame }` or `{ entity, clip, time }`.
7756
+ * @returns `{ posed }`.
7757
+ */
7758
+ #sampleSpriteAnimation(params) {
7759
+ const mirror = this.#requireMirror(SceneMethod.sampleSpriteAnimation);
7760
+ this.#requireOpen(SceneMethod.sampleSpriteAnimation);
7761
+ return sampleSpriteAnimation(this.#requireApp(), mirror, params);
7762
+ }
7763
+ /**
7219
7764
  * `setViewMode`: switches the view between the 3D editor camera and the 2D one. The first switch
7220
7765
  * to 2D on a document starts where the level's own `Camera2D` looks, or frames the document.
7221
7766
  *
@@ -7536,7 +8081,11 @@ var SceneHost = class {
7536
8081
  * @returns The set.
7537
8082
  */
7538
8083
  #schemas() {
7539
- return schemaSet(this.#requireApp(), /* @__PURE__ */ new Set([EditorCamera.typeId, EditorCamera2D.typeId]));
8084
+ return schemaSet(this.#requireApp(), /* @__PURE__ */ new Set([
8085
+ EditorCamera.typeId,
8086
+ EditorCamera2D.typeId,
8087
+ EditorGrid.typeId
8088
+ ]));
7540
8089
  }
7541
8090
  /**
7542
8091
  * The app, once {@link SceneHost.prepare} has run.
@@ -7641,11 +8190,16 @@ async function startEditorHost(options) {
7641
8190
  HostCapability.logRelay,
7642
8191
  HostCapability.hotReloadDefaults,
7643
8192
  HostCapability.gameView,
7644
- ...canRenderThumbnails(options) ? [HostCapability.thumbnails] : []
8193
+ ...canRenderThumbnails(options) ? [HostCapability.thumbnails] : [],
8194
+ HostCapability.grid,
8195
+ HostCapability.tilemapCells,
8196
+ HostCapability.editorLines,
8197
+ HostCapability.spriteAnimation
7645
8198
  ] : [
7646
8199
  HostCapability.heartbeat,
7647
8200
  HostCapability.logRelay,
7648
- HostCapability.hotReloadDefaults
8201
+ HostCapability.hotReloadDefaults,
8202
+ HostCapability.spriteAnimation
7649
8203
  ];
7650
8204
  let channel = null;
7651
8205
  const scene = new SceneHost({
@@ -8475,6 +9029,6 @@ function listenForEditorPlayControls(options) {
8475
9029
  };
8476
9030
  }
8477
9031
  //#endregion
8478
- export { ApplyOpFailureCode, COLLIDER_OUTLINES_MAX_ENTITIES, COLLIDER_OUTLINES_MAX_NUMBERS, DEFAULT_HEARTBEAT_INTERVAL_MS, EDITOR_CONNECT_MESSAGE_TYPE, EditorHostErrorCode, GAME_VIEW_DEFAULT_SIZE, GAME_VIEW_MAX_SIZE, GizmoMode, GizmoSpace, HOST_LIST_MAX_LENGTH, HOST_TEXT_MAX_LENGTH, HandshakeMethod, HostCapability, HostKind, HostNotification, JSON_RPC_VERSION, PROTOCOL_VERSION, PickUnit, PlayMethod, PlayNotification, PlayPhase, QUERY_RUNTIME_MAX_COMPONENTS, QUERY_RUNTIME_MAX_JSON_LENGTH, QUERY_RUNTIME_MAX_KEYS, QUERY_RUNTIME_MAX_STRING_LENGTH, RenderViewMethod, RpcErrorCode, SAMPLE_ANIMATION_MAX_NAME_LENGTH, SAMPLE_ANIMATION_MAX_PARAMETERS, SCREENSHOT_MAX_SIZE, SEND_INPUT_MAX_EVENTS, SceneMethod, SceneNotification, SceneOpKind, ScreenshotFormat, THUMBNAIL_DEFAULT_SIZE, THUMBNAIL_MAX_SIZE, TRANSFORM_DRAGGING_INTERVAL_MS, ViewMode, isAppErrorData, isApplyOpsParams, isApplyOpsResult, isAssetReloadedParams, isColliderOutlineRecord, isColliderOutlineSet, isEditorConnectMessage, isEditorOrigin, isEntitySelection, isFrameParams, isGameViewFrameParams, isGameViewFrameResult, isGameViewState, isHostErrorParams, isHotReloadedParams, isIncompatibleProtocolData, isInvalidSceneFileData, isJsonObject, isJsonValue, isLogParams, isOpenSceneParams, isOpenSceneResult, isPickParams, isPickResult, isPlayState, isPlayStateReport, isPlayStats, isProtocolVersion, isQueryRuntimeParams, isQueryRuntimeResult, isReadBackParams, isReadBackResult, isReadyResult, isRenderThumbnailParams, isRpcMessage, isSampleAnimationParams, isSampleAnimationResult, isSceneFile, isSceneFileAssetRef, isSceneFileComponent, isSceneFileEntity, isSceneFileInstance, isSceneFileOverride, isSceneFileTransform, isSceneIssue, isSceneOp, isSceneOpenedParams, isSchemaSet, isScreenshotParams, isScreenshotResult, isSendInputEvent, isSendInputParams, isSendInputResult, isSetAnimateMaterialsParams, isSetGameViewParams, isSetGizmoParams, isSetViewModeParams, isSettingsSet, isThumbnailResult, isTransformDraggedParams, isTransformDraggingParams, listenForEditorPlayControls, protocolVersionIsCompatible, startEditorHost, startEditorPlayControls };
9032
+ export { ApplyOpFailureCode, COLLIDER_OUTLINES_MAX_ENTITIES, COLLIDER_OUTLINES_MAX_NUMBERS, DEFAULT_HEARTBEAT_INTERVAL_MS, EDITOR_CONNECT_MESSAGE_TYPE, EDITOR_LINES_MAX_ID_LENGTH, EDITOR_LINES_MAX_NUMBERS, EDITOR_LINES_MAX_SETS, EditorHostErrorCode, GAME_VIEW_DEFAULT_SIZE, GAME_VIEW_MAX_SIZE, GRID_MAX_SIZE, GRID_MIN_SIZE, GizmoMode, GizmoSpace, HOST_LIST_MAX_LENGTH, HOST_TEXT_MAX_LENGTH, HandshakeMethod, HostCapability, HostKind, HostNotification, JSON_RPC_VERSION, PROTOCOL_VERSION, PickUnit, PlayMethod, PlayNotification, PlayPhase, QUERY_RUNTIME_MAX_COMPONENTS, QUERY_RUNTIME_MAX_JSON_LENGTH, QUERY_RUNTIME_MAX_KEYS, QUERY_RUNTIME_MAX_STRING_LENGTH, RenderViewMethod, RpcErrorCode, SAMPLE_ANIMATION_MAX_NAME_LENGTH, SAMPLE_ANIMATION_MAX_PARAMETERS, SCREENSHOT_MAX_SIZE, SEND_INPUT_MAX_EVENTS, SceneMethod, SceneNotification, SceneOpKind, ScreenshotFormat, THUMBNAIL_DEFAULT_SIZE, THUMBNAIL_MAX_SIZE, TILEMAP_CELLS_MAX_NUMBERS, TRANSFORM_DRAGGING_INTERVAL_MS, ViewMode, isAppErrorData, isApplyOpsParams, isApplyOpsResult, isAssetReloadedParams, isClearEditorLinesParams, isColliderOutlineRecord, isColliderOutlineSet, isEditorConnectMessage, isEditorOrigin, isEntitySelection, isFrameParams, isGameViewFrameParams, isGameViewFrameResult, isGameViewState, isHostErrorParams, isHotReloadedParams, isIncompatibleProtocolData, isInvalidSceneFileData, isJsonObject, isJsonValue, isLogParams, isOpenSceneParams, isOpenSceneResult, isPickParams, isPickResult, isPlayState, isPlayStateReport, isPlayStats, isProtocolVersion, isQueryRuntimeParams, isQueryRuntimeResult, isReadBackParams, isReadBackResult, isReadyResult, isRenderThumbnailParams, isRpcMessage, isSampleAnimationParams, isSampleAnimationResult, isSampleSpriteAnimationParams, isSampleSpriteAnimationResult, isSceneFile, isSceneFileAssetRef, isSceneFileComponent, isSceneFileEntity, isSceneFileInstance, isSceneFileOverride, isSceneFileTransform, isSceneIssue, isSceneOp, isSceneOpenedParams, isSchemaSet, isScreenshotParams, isScreenshotResult, isSendInputEvent, isSendInputParams, isSendInputResult, isSetAnimateMaterialsParams, isSetEditorLinesParams, isSetGameViewParams, isSetGizmoParams, isSetGridParams, isSetTilemapCellsParams, isSetTilemapCellsResult, isSetViewModeParams, isSettingsSet, isThumbnailResult, isTransformDraggedParams, isTransformDraggingParams, listenForEditorPlayControls, protocolVersionIsCompatible, startEditorHost, startEditorPlayControls };
8479
9033
 
8480
9034
  //# sourceMappingURL=index.js.map