@playcanvas/inspector 0.4.0 → 0.6.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/src/inspector.js CHANGED
@@ -1,25 +1,27 @@
1
1
  import {
2
- Asset, Color, Component, Entity, FramePass, GraphNode, LAYERID_UI, Material, Mesh, MeshInstance, RenderPassForward, RenderTarget, Shader, Texture
2
+ Asset, Color, Component, Entity, FramePass, GraphNode, Layer, LAYERID_UI, Material, Mesh, MeshInstance, RenderPassForward, RenderTarget, Shader, Texture
3
3
  } from 'playcanvas';
4
4
 
5
5
  import { TextureRenderer } from './renderers/texture-renderer.js';
6
6
  import { WireRenderer } from './renderers/wire-renderer.js';
7
7
 
8
8
  import { pushResourceUsage } from './asset-usage.js';
9
- import { ASSET_SORTS, assetRows, buildAssetModel, collectAssets } from './asset-view.js';
9
+ import { ASSET_SORTS, assetRows, assetSnapshot, buildAssetModel, collectAssets } from './asset-view.js';
10
10
  import { buildCameraModel, cameraRows, collectCameras } from './camera-view.js';
11
+ import { buildLayerModel, collectSubLayers, layerRows } from './layer-view.js';
11
12
  import { ContextMenu } from './context-menu.js';
12
13
  import { copyGroup, copyList, copyListRow, copySubject, stringifyCopy } from './copy-json.js';
13
14
  import { INSTANCES_PER_PAGE, LayerStepSelection, buildPassModel, buildStepModel, captureFrameGraph, passRows, profilerName } from './frame-graph-view.js';
14
- import { bufferKind, bufferOwners, buildBufferModel, KIND_NAMES, memoryRows, videoMemory } from './memory-view.js';
15
+ import { bufferKind, bufferOwners, buildBufferModel, KIND_NAMES, memoryRows, memorySnapshot, videoMemory } from './memory-view.js';
15
16
  import { HierarchyView, filterSuggestions } from './hierarchy-view.js';
16
17
  import { ListView } from './list-view.js';
17
18
  import {
18
19
  buildMaterialModel, materialListRows, materialsUsingShader, materialsUsingTexture, surveyMaterials,
19
20
  usedByMaterialsSection
20
21
  } from './material-view.js';
21
- import { buildMeshModel, meshBytes, meshListRows, meshNote, surveyMeshes } from './mesh-view.js';
22
+ import { buildMeshModel, meshBytes, meshListRows, meshNote, meshSnapshot, surveyMeshes } from './mesh-view.js';
22
23
  import { formatBytes, formatName, passDisplayName } from './model.js';
24
+ import { TOOLS as MCP_TOOLS, endPerfSession, validate as validateMcpArgs } from './mcp-tools.js';
23
25
  import { buildComponentModel, buildNodeModel, meshInstanceRows } from './node-model.js';
24
26
  import { PerfCapture } from './perf-capture.js';
25
27
  import { PerfCharts } from './perf-chart.js';
@@ -27,10 +29,15 @@ import { captureJson, frameJson, rangeJson, seriesRows, toCsv } from './perf-cop
27
29
  import { buildPerfModel, captureNorms, formatMs, isHitch } from './perf-view.js';
28
30
  import { AmmoDebugDraw, DEBUG_DRAW } from './physics-debug.js';
29
31
  import { bodyRows, drawCollisionShape, drawJoint, jointRows, physicsStats } from './physics-view.js';
32
+ import { ImageCapture } from './image-capture.js';
33
+ import { LogCapture } from './log-capture.js';
30
34
  import { PropertyView } from './property-view.js';
35
+ import { RefRegistry } from './ref-registry.js';
31
36
  import { buildScriptModel, isScriptClass, scriptListRows, surveyScripts } from './script-view.js';
32
- import { buildRenderTargetModel, formatChannels, isDepthFormat, previewAttachments, previewSupport, renderTargetRows, storedBottomUp } from './render-target-view.js';
33
- import { buildShaderModel, collectShaders, shaderRows, stateName } from './shader-view.js';
37
+ import { buildRenderTargetModel, formatChannels, isDepthFormat, previewAttachments, previewSupport, renderTargetRows, renderTargetSnapshot, storedBottomUp } from './render-target-view.js';
38
+ import { buildShaderModel, collectShaders, shaderRows, shaderSnapshot, stateName } from './shader-view.js';
39
+ import { SnapshotPanel, createSnapshotList } from './snapshot-view.js';
40
+ import { TreemapView } from './treemap-view.js';
34
41
  import { styles } from './styles.js';
35
42
  import { installTooltip, setTip } from './tooltip.js';
36
43
  import { CameraFly, CameraOrbit, CanvasCapture, RENDER_MODES, ViewportPicker, WireframeMode, isScreenCamera, screenCameraAt } from './viewport-tools.js';
@@ -45,6 +52,9 @@ import { TRANSFORM_POINTER_EVENTS, TransformTool } from './transform-tool.js';
45
52
  /** @import { CopyOptions } from './copy-json.js' */
46
53
  /** @import { CopyTarget } from './property-view.js' */
47
54
  /** @import { TransformMode } from './transform-tool.js' */
55
+ /** @import { McpHost, McpTool } from './mcp-tools.js' */
56
+ /** @import { SnapshotContent, SnapshotList } from './snapshot-view.js' */
57
+ /** @import { TreemapData } from './treemap-view.js' */
48
58
 
49
59
  /**
50
60
  * Options for {@link Inspector}.
@@ -66,13 +76,16 @@ import { TRANSFORM_POINTER_EVENTS, TransformTool } from './transform-tool.js';
66
76
  * @property {boolean} [record] - Whether to start recording frames for the Performance tab right
67
77
  * away, as if Record were pressed, so the capture begins with the first frame the app runs after
68
78
  * the inspector is created. Defaults to false. See {@link Inspector#recording}.
79
+ * @property {boolean} [mcp] - Whether to offer the inspector's tools to AI agents right
80
+ * away, as if the MCP button was pressed. Defaults to false. A setting stored by the button takes
81
+ * precedence. See {@link Inspector#mcp}.
69
82
  * @property {(visible: boolean) => void} [onVisibleChange] - Called with the new visibility
70
83
  * whenever the panel is shown or hidden, whether through {@link Inspector#visible}, the toggle key
71
84
  * or the panel's own close button.
72
85
  * @property {string|null} [storageKey] - The local storage key the panel's settings are kept
73
86
  * under, so they survive a reload or a restart of the app: the physics drawing switch and options,
74
- * the bodies excluded from it (by entity path), the active tab, the panel width, the GPU
75
- * timings switch, and on the Performance tab the script timing switch, whether the CPU chart
87
+ * the bodies excluded from it (by entity path), the active tab, the panel width, the MCP switch,
88
+ * the GPU timings switch, and on the Performance tab the script timing switch, whether the CPU chart
76
89
  * includes the inspector's time, the charts collapsed and lines hidden, and the script types the
77
90
  * Scripts chart shows. Stored settings take
78
91
  * precedence over the defaults given here. Defaults to
@@ -141,6 +154,7 @@ const PERF_SERIES_NAMES = {
141
154
  const TAB_TIPS = {
142
155
  hierarchy: 'The entity tree, and the components and properties of the selected entity',
143
156
  cameras: 'The cameras of the scene in render order, with where they draw, their render mode and a way to fly each',
157
+ layers: 'The layers of the composition in the order they render, each opaque and transparent half apart, with the cameras, lights and mesh instances of each and a way to hide it',
144
158
  assets: 'The assets of the registry, and what uses each',
145
159
  passes: 'The passes that rendered the last frame, with the layers, draws and targets of each',
146
160
  perf: 'Record frames and chart their CPU and GPU time, draw calls, memory and events over the whole capture.\nClick a frame to see everything recorded for it, drag to select frames, scroll to zoom, Shift+drag to pan,\ndouble-click to see the whole capture. A dashed line marks the display interval, red ticks the hitches',
@@ -459,7 +473,9 @@ class Inspector {
459
473
  _nextPropertyRefresh = 0;
460
474
 
461
475
  /**
462
- * @type {'hierarchy'|'cameras'|'assets'|'passes'|'perf'|'targets'|'textures'|'meshes'|'materials'|'scripts'|'memory'|'shaders'|'physics'}
476
+ * The tab shown: one of the fixed tabs, or a treemap tab, by its id.
477
+ *
478
+ * @type {'hierarchy'|'cameras'|'layers'|'assets'|'passes'|'perf'|'targets'|'textures'|'meshes'|'materials'|'scripts'|'memory'|'shaders'|'physics'|`treemap${number}`}
463
479
  * @private
464
480
  */
465
481
  _tab = 'hierarchy';
@@ -724,6 +740,79 @@ class Inspector {
724
740
  */
725
741
  _cameraList;
726
742
 
743
+ /**
744
+ * @type {ListView}
745
+ * @private
746
+ */
747
+ _layerList;
748
+
749
+ /**
750
+ * The layers hidden from the Layers tab, each turned off until shown again, reset or the panel
751
+ * closes. A layer the app turns back on itself meanwhile is left to it.
752
+ *
753
+ * @type {Set<Layer>}
754
+ * @private
755
+ */
756
+ _hiddenLayers = new Set();
757
+
758
+ /**
759
+ * The snapshots captured on each tab that takes them, kept here rather than with the panel's
760
+ * elements, which are built again when the panel docks back from its own window.
761
+ *
762
+ * @type {Map<string, SnapshotList>}
763
+ * @private
764
+ */
765
+ _snapshots = new Map();
766
+
767
+ /**
768
+ * The snapshots section of each tab that takes them, by tab.
769
+ *
770
+ * @type {Record<string, SnapshotPanel>}
771
+ * @private
772
+ */
773
+ _snapshotPanels = {};
774
+
775
+ /**
776
+ * The treemap tabs open, by id, each showing a snapshot or two compared, with the tab the
777
+ * snapshots came from. Kept here, so the tabs are built again with the panel.
778
+ *
779
+ * @type {Map<string, { source: string, key: string, data: TreemapData, view: TreemapView|null }>}
780
+ * @private
781
+ */
782
+ _treemapTabs = new Map();
783
+
784
+ /**
785
+ * The number the id of the next treemap tab takes.
786
+ *
787
+ * @type {number}
788
+ * @private
789
+ */
790
+ _nextTreemap = 1;
791
+
792
+ /**
793
+ * The tab bar.
794
+ *
795
+ * @type {HTMLElement}
796
+ * @private
797
+ */
798
+ _tabsEl;
799
+
800
+ /**
801
+ * The body of the panel: the tabs over the properties.
802
+ *
803
+ * @type {HTMLElement}
804
+ * @private
805
+ */
806
+ _bodyEl;
807
+
808
+ /**
809
+ * The button on the Layers tab that shows the hidden layers again.
810
+ *
811
+ * @type {HTMLButtonElement}
812
+ * @private
813
+ */
814
+ _showLayersBtn;
815
+
727
816
  /**
728
817
  * The render mode applied from the Cameras tab.
729
818
  *
@@ -943,6 +1032,21 @@ class Inspector {
943
1032
  }
944
1033
  });
945
1034
 
1035
+ /**
1036
+ * Model builder for the property view when a layer is selected.
1037
+ *
1038
+ * @param {Layer} layer - The layer.
1039
+ * @returns {PropertySection[]} The sections.
1040
+ * @private
1041
+ */
1042
+ _layerModel = layer => buildLayerModel(layer, {
1043
+ app: this._app,
1044
+ layerActions: {
1045
+ hide: (target, hidden) => this._hideLayer(target, hidden),
1046
+ hidden: target => this._hiddenLayers.has(target)
1047
+ }
1048
+ });
1049
+
946
1050
  /**
947
1051
  * Model builder for the property view when a script class is selected.
948
1052
  *
@@ -1095,6 +1199,114 @@ class Inspector {
1095
1199
  */
1096
1200
  _storageKey = 'pc-inspector';
1097
1201
 
1202
+ /**
1203
+ * Whether the tools are offered to agents, see {@link Inspector#mcp}.
1204
+ *
1205
+ * @type {boolean}
1206
+ * @private
1207
+ */
1208
+ _mcp = false;
1209
+
1210
+ /**
1211
+ * Aborted to withdraw the tools registered with WebMCP.
1212
+ *
1213
+ * @type {AbortController|null}
1214
+ * @private
1215
+ */
1216
+ _mcpAbort = null;
1217
+
1218
+ /**
1219
+ * @type {HTMLButtonElement}
1220
+ * @private
1221
+ */
1222
+ _mcpBtn;
1223
+
1224
+ /**
1225
+ * The ids of the objects the tools return, which stay the same for the life of the inspector.
1226
+ *
1227
+ * @type {RefRegistry}
1228
+ * @private
1229
+ */
1230
+ _refs = new RefRegistry();
1231
+
1232
+ /**
1233
+ * What the tools read the app through.
1234
+ *
1235
+ * @type {McpHost}
1236
+ * @private
1237
+ */
1238
+ _mcpHost = {
1239
+ app: /** @type {any} */ (null),
1240
+ refs: this._refs,
1241
+ modelFor: (obj, subject) => this._mcpModel(obj, subject),
1242
+ opaque: (obj) => {
1243
+ this._mcpOpaque ??= this._opaqueObjects();
1244
+ return this._mcpOpaque.has(obj);
1245
+ },
1246
+ exclude: obj => obj === this._transformTool?.root,
1247
+ frame: () => {
1248
+ this._mcpFrame ??= this._frozen && this._frame ? this._frame : captureFrameGraph(this._app);
1249
+ return this._mcpFrame;
1250
+ },
1251
+ perf: {
1252
+ capture: /** @type {any} */ (null),
1253
+ setRecording: (on) => {
1254
+ this._setRecording(on);
1255
+ },
1256
+ setGpuTimings: (on) => {
1257
+ this._setGpuTimings(on);
1258
+ },
1259
+ setScriptTiming: (on) => {
1260
+ this._setScriptTiming(on);
1261
+ },
1262
+ clear: () => {
1263
+ this._perf.clear();
1264
+ this._perfCharts.reset();
1265
+ },
1266
+ gpuSupported: () => !!this._app.graphicsDevice.gpuProfiler,
1267
+ gpuTimings: () => !!this._app.graphicsDevice.gpuProfiler?.enabled,
1268
+ paused: () => this._paused,
1269
+ device: () => this._deviceInfo(),
1270
+ byAgent: false,
1271
+ session: null
1272
+ },
1273
+ logs: new LogCapture(() => this._app?.frame ?? 0),
1274
+ images: () => {
1275
+ this._images ??= new ImageCapture(this._app);
1276
+ return this._images;
1277
+ },
1278
+ time: {
1279
+ paused: () => this._paused,
1280
+ setPaused: (paused) => {
1281
+ this.paused = paused;
1282
+ },
1283
+ step: (frames, timeout) => this._stepFrames(frames, timeout),
1284
+ frame: () => this._app.frame ?? 0
1285
+ }
1286
+ };
1287
+
1288
+ /**
1289
+ * Captures images for the screenshot tool, made on first use.
1290
+ *
1291
+ * @type {ImageCapture|null}
1292
+ * @private
1293
+ */
1294
+ _images = null;
1295
+
1296
+ /**
1297
+ * The frame graph and the app's own objects, found once per tool call.
1298
+ *
1299
+ * @type {*}
1300
+ * @private
1301
+ */
1302
+ _mcpFrame = null;
1303
+
1304
+ /**
1305
+ * @type {Set<object>|null}
1306
+ * @private
1307
+ */
1308
+ _mcpOpaque = null;
1309
+
1098
1310
  /**
1099
1311
  * True while the panel is being built and restored, when nothing should be saved.
1100
1312
  *
@@ -1171,7 +1383,11 @@ class Inspector {
1171
1383
  this._physicsDraw = false;
1172
1384
  this._setTab('hierarchy');
1173
1385
  this._storageKey = options.storageKey === undefined ? 'pc-inspector' : options.storageKey;
1386
+ this._mcpHost.app = app;
1387
+ this._mcpHost.perf.capture = this._perf;
1388
+ this._mcp = !!options.mcp;
1174
1389
  this._loadSettings();
1390
+ this._applyMcp();
1175
1391
  this._applyLayout();
1176
1392
  this._applyVisibility();
1177
1393
  this._applyPauseState();
@@ -1208,6 +1424,12 @@ class Inspector {
1208
1424
  this._picker = null;
1209
1425
 
1210
1426
  this.paused = false;
1427
+ this._mcpAbort?.abort();
1428
+ this._mcpAbort = null;
1429
+ endPerfSession(this._mcpHost, 'inspector destroyed');
1430
+ this._mcpHost.logs.stop();
1431
+ this._images?.destroy();
1432
+ this._images = null;
1211
1433
  this._perf.destroy();
1212
1434
  this._perfCharts.destroy();
1213
1435
  const profiler = app.graphicsDevice?.gpuProfiler;
@@ -1250,6 +1472,157 @@ class Inspector {
1250
1472
  return this._visible;
1251
1473
  }
1252
1474
 
1475
+ /**
1476
+ * Whether the inspector offers its tools to AI agents: tools that read the app as the panel
1477
+ * shows it, the hierarchy, the lists of its tabs and any object by id, and tools that record
1478
+ * frames on the Performance tab and read what they recorded. None of them changes the app;
1479
+ * the recording tools change only the inspector's capture and its timing switches. Toggled by
1480
+ * the MCP button of the toolbar, and kept on while the panel is hidden.
1481
+ *
1482
+ * While on, the tools are registered with WebMCP (`document.modelContext`) where the browser
1483
+ * has it, for agents running in the browser, and can be called from the page through
1484
+ * {@link Inspector#getTools} and {@link Inspector#executeTool}, for agents driving the page,
1485
+ * such as through Puppeteer.
1486
+ *
1487
+ * @type {boolean}
1488
+ */
1489
+ set mcp(value) {
1490
+ value = !!value;
1491
+ if (value === this._mcp || this._destroyed) return;
1492
+ this._mcp = value;
1493
+ this._applyMcp();
1494
+ this._saveSettings();
1495
+ }
1496
+
1497
+ get mcp() {
1498
+ return this._mcp;
1499
+ }
1500
+
1501
+ /**
1502
+ * Whether the browser has WebMCP, through which agents running in the browser find the tools
1503
+ * of {@link Inspector#mcp}. Without it, the tools are still offered through
1504
+ * {@link Inspector#executeTool}.
1505
+ *
1506
+ * @type {boolean}
1507
+ */
1508
+ static get webMcpSupported() {
1509
+ return typeof document !== 'undefined' && typeof /** @type {any} */ (document).modelContext?.registerTool === 'function';
1510
+ }
1511
+
1512
+ /**
1513
+ * The tools offered while {@link Inspector#mcp} is on, described the way MCP describes them.
1514
+ *
1515
+ * @returns {McpTool[]} The tools, none while it is off.
1516
+ */
1517
+ getTools() {
1518
+ if (!this._mcp) return [];
1519
+ return MCP_TOOLS.map(({ name, description, inputSchema, annotations }) => ({ name, description, inputSchema, annotations }));
1520
+ }
1521
+
1522
+ /**
1523
+ * Calls one of the tools of {@link Inspector#getTools}.
1524
+ *
1525
+ * @param {string} name - The name of the tool.
1526
+ * @param {object} [args] - Its arguments, as its input schema describes them.
1527
+ * @returns {Promise<*>} The result, as JSON-ready data. Rejects when the tools are off, the tool
1528
+ * is unknown or the arguments are wrong.
1529
+ * @example
1530
+ * inspector.mcp = true;
1531
+ * const { entities } = await inspector.executeTool('playcanvas_find_entities', { name: 'Robot' });
1532
+ * const robot = await inspector.executeTool('playcanvas_get', { id: entities[0].$id });
1533
+ */
1534
+ async executeTool(name, args = {}) {
1535
+ if (!this._mcp) throw new Error('The inspector\'s MCP tools are off');
1536
+ const tool = MCP_TOOLS.find(t => t.name === name);
1537
+ if (!tool) throw new Error(`Unknown tool "${name}"`);
1538
+ validateMcpArgs(tool, args ?? {});
1539
+ try {
1540
+ return await tool.execute(this._mcpHost, args ?? {});
1541
+ } finally {
1542
+ this._mcpFrame = null;
1543
+ this._mcpOpaque = null;
1544
+ }
1545
+ }
1546
+
1547
+ /**
1548
+ * Registers the tools with WebMCP while {@link Inspector#mcp} is on, withdraws them while it is
1549
+ * off, and shows the state on the toolbar button.
1550
+ *
1551
+ * @private
1552
+ */
1553
+ _applyMcp() {
1554
+ if (this._mcp && !this._mcpAbort) {
1555
+ this._mcpAbort = new AbortController();
1556
+ this._mcpHost.logs.start();
1557
+ const context = Inspector.webMcpSupported ? /** @type {any} */ (document).modelContext : null;
1558
+ if (context) {
1559
+ const signal = this._mcpAbort.signal;
1560
+ for (const { name, description, inputSchema, annotations } of MCP_TOOLS) {
1561
+ // a failure is returned as an error result rather than thrown, as the browser
1562
+ // hands the agent a generic error in place of a thrown one's message
1563
+ const execute = async (args) => {
1564
+ try {
1565
+ const result = await this.executeTool(name, args);
1566
+ // an image goes to the agent as an image, with what it shows as text
1567
+ if (result?.$image) {
1568
+ const { $image, ...rest } = result;
1569
+ return { content: [{ type: 'image', data: $image.data, mimeType: $image.mimeType }, { type: 'text', text: JSON.stringify(rest) }] };
1570
+ }
1571
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
1572
+ } catch (e) {
1573
+ return { content: [{ type: 'text', text: `${e?.message ?? e}` }], isError: true };
1574
+ }
1575
+ };
1576
+ // registering returns a promise, which rejects on a name already registered,
1577
+ // such as by a second inspector in the page
1578
+ Promise.resolve()
1579
+ .then(() => context.registerTool({ name, description, inputSchema, annotations, execute }, { signal }))
1580
+ .catch(e => console.warn(`Inspector: could not register the WebMCP tool ${name}: ${e?.message ?? e}`));
1581
+ }
1582
+ }
1583
+ } else if (!this._mcp && this._mcpAbort) {
1584
+ this._mcpAbort.abort();
1585
+ this._mcpAbort = null;
1586
+ // a recording the tools were to stop stops with them
1587
+ endPerfSession(this._mcpHost, 'MCP turned off');
1588
+ this._mcpHost.logs.stop();
1589
+ }
1590
+
1591
+ if (this._mcpBtn) {
1592
+ this._mcpBtn.classList.toggle('pci-active', this._mcp);
1593
+ const how = Inspector.webMcpSupported ?
1594
+ 'registered with WebMCP, and callable from the page through executeTool' :
1595
+ 'callable from the page through executeTool. This browser has no WebMCP, so agents in the browser do not see them';
1596
+ setTip(this._mcpBtn, this._mcp ?
1597
+ `MCP on: tools for AI agents are ${how}. They stay on while the panel is hidden. Click to turn them off` :
1598
+ 'MCP: offer tools to AI agents, which read the hierarchy, the lists of the tabs and any object by id, take screenshots of the canvas and of textures, read what the page logs, record on the Performance tab, and pause and step the app. Nothing else in the app is changed');
1599
+ }
1600
+ }
1601
+
1602
+ /**
1603
+ * The model the tools show an object with: for the object asked for, what its tab shows,
1604
+ * with the lists of what uses it; for an object reached through a link, what a copy follows,
1605
+ * see {@link Inspector#_copyModel}. Neither narrows to the filter of the panel.
1606
+ *
1607
+ * @param {object} obj - The object.
1608
+ * @param {boolean} subject - Whether it is the object asked for.
1609
+ * @returns {PropertySection[]|PropertyRow[]|null} The model, or null for an object no tab shows.
1610
+ * @private
1611
+ */
1612
+ _mcpModel(obj, subject) {
1613
+ const ctx = { ...this._context(), frame: this._mcpHost.frame(), filter: '' };
1614
+ if (!subject) return this._copyModel(obj, { ...ctx, backlinks: false });
1615
+ if (obj instanceof Texture) return [...buildTextureModel(obj, ctx), usedByMaterialsSection(materialsUsingTexture(this._app, obj))];
1616
+ if (obj instanceof Shader) return [...buildShaderModel(obj), usedByMaterialsSection(materialsUsingShader(this._app, obj))];
1617
+ if (obj instanceof Asset) {
1618
+ const sections = buildAssetModel(obj, ctx);
1619
+ const users = sections.find(section => section.key === 'users');
1620
+ if (users) pushResourceUsage(users, obj, this._app);
1621
+ return sections;
1622
+ }
1623
+ return this._copyModel(obj, { ...ctx, backlinks: true });
1624
+ }
1625
+
1253
1626
  /**
1254
1627
  * Whether the app is paused. Pausing sets {@link AppBase#timeScale} to zero and suspends the
1255
1628
  * sound manager; resuming restores the time scale that was in effect.
@@ -1363,6 +1736,35 @@ class Inspector {
1363
1736
  });
1364
1737
  }
1365
1738
 
1739
+ /**
1740
+ * Pauses the app if it is not, then runs frames with time moving, as pressing Step that many
1741
+ * times does, and holds it paused again.
1742
+ *
1743
+ * @param {number} frames - How many frames to run.
1744
+ * @param {number} timeout - How long to wait for them, in milliseconds.
1745
+ * @returns {Promise<number>} How many frames ran: fewer when the timeout came first.
1746
+ * @private
1747
+ */
1748
+ _stepFrames(frames, timeout) {
1749
+ this.paused = true;
1750
+ const app = this._app;
1751
+ app.timeScale = this._savedTimeScale;
1752
+ return new Promise((resolve) => {
1753
+ const pending = { ran: 0, timer: /** @type {any} */ (null) };
1754
+ // called after each frame, and once by the timeout
1755
+ const tick = (timedOut = false) => {
1756
+ if (!timedOut && ++pending.ran < frames && this._paused) return;
1757
+ app.off('frameend', tick);
1758
+ clearTimeout(pending.timer);
1759
+ if (this._paused) app.timeScale = 0;
1760
+ this._refresh();
1761
+ resolve(pending.ran);
1762
+ };
1763
+ pending.timer = setTimeout(() => tick(true), timeout);
1764
+ app.on('frameend', tick);
1765
+ });
1766
+ }
1767
+
1366
1768
  /**
1367
1769
  * Refreshes the active list and the property view immediately.
1368
1770
  *
@@ -1612,12 +2014,14 @@ class Inspector {
1612
2014
 
1613
2015
  // body: a tabbed list over the properties, with a draggable splitter
1614
2016
  const body = el('div', 'pci-body');
2017
+ this._bodyEl = body;
1615
2018
  this._hierarchyEl = el('div', 'pci-hierarchy');
1616
2019
 
1617
2020
  const tabs = el('div', 'pci-tabs');
2021
+ this._tabsEl = tabs;
1618
2022
  this._tabButtons = {};
1619
2023
  const tabList = [
1620
- ['hierarchy', 'Hierarchy'], ['cameras', 'Cameras'], ['assets', 'Assets'], ['passes', 'Frame graph'], ['perf', 'Performance'],
2024
+ ['hierarchy', 'Hierarchy'], ['cameras', 'Cameras'], ['layers', 'Layers'], ['assets', 'Assets'], ['passes', 'Frame graph'], ['perf', 'Performance'],
1621
2025
  ['targets', 'Render targets'], ['textures', 'Textures'], ['meshes', 'Meshes'], ['materials', 'Materials'], ['scripts', 'Scripts'], ['memory', 'Memory'],
1622
2026
  ['shaders', 'Shaders'], ['physics', 'Physics']
1623
2027
  ];
@@ -1744,7 +2148,8 @@ class Inspector {
1744
2148
  this._previewNote = el('div', 'pci-note pci-note-info');
1745
2149
  this._previewNote.style.display = 'none';
1746
2150
  const targetList = el('div', 'pci-list');
1747
- targetPanel.append(targetBar, this._previewNote, targetList);
2151
+ targetPanel.append(targetBar, this._previewNote, targetList,
2152
+ this._snapshotSection('targets', 'Render targets', () => renderTargetSnapshot(this._app.graphicsDevice)));
1748
2153
 
1749
2154
  // textures: the same live preview for the selected texture
1750
2155
  const texturePanel = el('div', 'pci-listpanel');
@@ -1765,14 +2170,14 @@ class Inspector {
1765
2170
  const assetBar = el('div', 'pci-subbar');
1766
2171
  this._assetSort = this._makeSelect(assetBar, 'Sort by', ASSET_SORTS, 'The order of the asset list');
1767
2172
  const assetList = el('div', 'pci-list');
1768
- assetPanel.append(assetBar, assetList);
2173
+ assetPanel.append(assetBar, assetList, this._snapshotSection('assets', 'Assets', () => assetSnapshot(this._app.assets)));
1769
2174
 
1770
2175
  // meshes: a note when some vertex buffers belong to no mesh found, over the list
1771
2176
  const meshPanel = el('div', 'pci-listpanel');
1772
2177
  this._meshNote = el('div', 'pci-note pci-note-info');
1773
2178
  this._meshNote.style.display = 'none';
1774
2179
  const meshList = el('div', 'pci-list');
1775
- meshPanel.append(this._meshNote, meshList);
2180
+ meshPanel.append(this._meshNote, meshList, this._snapshotSection('meshes', 'Meshes', () => meshSnapshot(surveyMeshes(this._app), this._app.assets)));
1776
2181
 
1777
2182
  // materials: a plain list
1778
2183
  const materialPanel = el('div', 'pci-listpanel');
@@ -1794,6 +2199,17 @@ class Inspector {
1794
2199
  cameraBar.appendChild(this._resetViewBtn);
1795
2200
  const cameraList = el('div', 'pci-list');
1796
2201
  cameraPanel.append(cameraBar, cameraList);
2202
+
2203
+ // layers: the composition in render order, with a way to show the hidden ones again
2204
+ const layerPanel = el('div', 'pci-listpanel');
2205
+ const layerBar = el('div', 'pci-subbar');
2206
+ this._showLayersBtn = /** @type {HTMLButtonElement} */ (el('button', 'pci-btn', 'Show all'));
2207
+ setTip(this._showLayersBtn, 'Turn the layers hidden here back on');
2208
+ this._showLayersBtn.disabled = true;
2209
+ this._showLayersBtn.addEventListener('click', () => this._showHiddenLayers());
2210
+ layerBar.appendChild(this._showLayersBtn);
2211
+ const layerList = el('div', 'pci-list');
2212
+ layerPanel.append(layerBar, layerList);
1797
2213
  this._renderMode.addEventListener('change', () => this._applyRenderMode());
1798
2214
  // choosing a camera shows its render mode, and changes nothing until a mode is picked
1799
2215
  this._renderScope.addEventListener('change', () => {
@@ -1810,12 +2226,13 @@ class Inspector {
1810
2226
  // memory: a group per kind of resource, each opening to its buffers
1811
2227
  const memoryPanel = el('div', 'pci-listpanel');
1812
2228
  const bufferList = el('div', 'pci-list');
1813
- memoryPanel.append(bufferList);
2229
+ memoryPanel.append(bufferList,
2230
+ this._snapshotSection('memory', 'Memory', () => memorySnapshot(this._app.graphicsDevice, bufferOwners(this._app))));
1814
2231
 
1815
2232
  // shaders: a plain list
1816
2233
  const shaderPanel = el('div', 'pci-listpanel');
1817
2234
  const shaderList = el('div', 'pci-list');
1818
- shaderPanel.append(shaderList);
2235
+ shaderPanel.append(shaderList, this._snapshotSection('shaders', 'Shaders', () => shaderSnapshot(this._app.graphicsDevice)));
1819
2236
 
1820
2237
  for (const input of [this._previewToggle, this._previewAttachment, this._previewChannels, this._texturePreviewToggle, this._textureChannels, this._assetSort]) {
1821
2238
  input.addEventListener('change', () => this._saveSettings());
@@ -1877,11 +2294,13 @@ class Inspector {
1877
2294
  materials: materialPanel,
1878
2295
  scripts: scriptPanel,
1879
2296
  cameras: cameraPanel,
2297
+ layers: layerPanel,
1880
2298
  memory: memoryPanel,
1881
2299
  shaders: shaderPanel,
1882
2300
  physics: physicsPanel
1883
2301
  };
1884
- this._hierarchyEl.append(tabs, filter, tree, cameraPanel, assetPanel, passPanel, perfPanel, targetPanel, texturePanel, meshPanel, materialPanel, scriptPanel, memoryPanel, shaderPanel, physicsPanel);
2302
+ this._hierarchyEl.append(tabs, filter, tree, cameraPanel, layerPanel, assetPanel, passPanel, perfPanel, targetPanel, texturePanel, meshPanel, materialPanel, scriptPanel, memoryPanel, shaderPanel, physicsPanel);
2303
+ for (const [id, tab] of this._treemapTabs) this._addTreemapTab(id, tab);
1885
2304
 
1886
2305
  const splitter = el('div', 'pci-splitter');
1887
2306
  const properties = el('div', 'pci-properties');
@@ -1929,7 +2348,13 @@ class Inspector {
1929
2348
  this._debugEl = el('span', 'pci-paused');
1930
2349
  this._modeEl = el('span', 'pci-paused');
1931
2350
  this._pathEl = el('span', 'pci-path');
1932
- status.append(this._countsEl, this._pausedEl, this._debugEl, this._modeEl, this._pathEl);
2351
+ // the MCP switch sits here rather than on the toolbar, which has no room left, and shows
2352
+ // while it is on that the app is open to agents
2353
+ this._mcpBtn = /** @type {HTMLButtonElement} */ (el('button', 'pci-mcp', 'MCP'));
2354
+ this._mcpBtn.addEventListener('click', () => {
2355
+ this.mcp = !this._mcp;
2356
+ });
2357
+ status.append(this._countsEl, this._pausedEl, this._debugEl, this._modeEl, this._pathEl, this._mcpBtn);
1933
2358
 
1934
2359
  // width handle on the inner edge
1935
2360
  const edge = el('div', 'pci-edge');
@@ -2000,6 +2425,10 @@ class Inspector {
2000
2425
  if (this._tab === 'cameras') this._properties.setSubject(camera, this._cameraModel, key);
2001
2426
  this._updateStatus();
2002
2427
  }, target => this._selectAny(target));
2428
+ this._layerList = new ListView(layerList, (layer, key) => {
2429
+ if (this._tab === 'layers') this._properties.setSubject(layer, this._layerModel, key);
2430
+ this._updateStatus();
2431
+ }, target => this._selectAny(target));
2003
2432
  this._scriptList = new ListView(scriptList, (cls, key) => {
2004
2433
  if (this._tab === 'scripts') this._properties.setSubject(cls, this._scriptModel, key);
2005
2434
  this._updateStatus();
@@ -2148,6 +2577,7 @@ class Inspector {
2148
2577
  }
2149
2578
  if (typeof stored.assetSort === 'string') this._assetSort.value = stored.assetSort;
2150
2579
  if (typeof stored.copyDepth === 'number') this._setCopyDepth(stored.copyDepth);
2580
+ if (typeof stored.mcp === 'boolean') this._mcp = stored.mcp;
2151
2581
  if (typeof stored.filterBy === 'string') {
2152
2582
  this._filterBy.value = stored.filterBy;
2153
2583
  this._hierarchy.filterBy = /** @type {any} */ (this._filterBy.value);
@@ -2178,7 +2608,8 @@ class Inspector {
2178
2608
  physicsDraw: this._physicsDraw,
2179
2609
  physicsDrawOptions: this._physicsDrawOptions,
2180
2610
  hiddenBodies,
2181
- tab: this._tab,
2611
+ // treemap tabs do not outlive the page, so the tab their snapshots came from is kept
2612
+ tab: this._treemapTabs.get(this._tab)?.source ?? this._tab,
2182
2613
  width: this._width,
2183
2614
  gpuTimings: this._gpuToggle.checked,
2184
2615
  perfInspector: this._perfInspectorToggle.checked,
@@ -2193,7 +2624,8 @@ class Inspector {
2193
2624
  texturePreview: { enabled: this._texturePreviewToggle.checked, channels: this._textureChannels.value },
2194
2625
  assetSort: this._assetSort.value,
2195
2626
  filterBy: this._filterBy.value,
2196
- copyDepth: this._copyDepth
2627
+ copyDepth: this._copyDepth,
2628
+ mcp: this._mcp
2197
2629
  }));
2198
2630
  } catch (e) {
2199
2631
  // storage unavailable or full: settings simply do not persist
@@ -2780,6 +3212,116 @@ class Inspector {
2780
3212
  if (element.style.display !== display) element.style.display = display;
2781
3213
  }
2782
3214
 
3215
+ /**
3216
+ * Builds the snapshots section of a tab, over the snapshots the tab already has.
3217
+ *
3218
+ * @param {string} tab - The tab.
3219
+ * @param {string} title - Its name.
3220
+ * @param {() => SnapshotContent} measure - Measures what the tab shows, now.
3221
+ * @returns {HTMLElement} The section.
3222
+ * @private
3223
+ */
3224
+ _snapshotSection(tab, title, measure) {
3225
+ let list = this._snapshots.get(tab);
3226
+ if (!list) {
3227
+ list = createSnapshotList();
3228
+ this._snapshots.set(tab, list);
3229
+ }
3230
+ const panel = new SnapshotPanel(list, title, measure, data => this._showTreemap(tab, data));
3231
+ this._snapshotPanels[tab] = panel;
3232
+ return panel.el;
3233
+ }
3234
+
3235
+ /**
3236
+ * Shows a treemap of snapshots in a tab of its own, added at the end of the tab bar, or switches
3237
+ * to the tab already showing them. Several can be open at once.
3238
+ *
3239
+ * @param {string} source - The tab the snapshots were captured on.
3240
+ * @param {TreemapData} data - The snapshots.
3241
+ * @returns {string} The id of the treemap's tab.
3242
+ * @private
3243
+ */
3244
+ _showTreemap(source, data) {
3245
+ const key = `${source}:${data.from?.number ?? ''}:${data.to.number}`;
3246
+ for (const [id, tab] of this._treemapTabs) {
3247
+ if (tab.key === key) {
3248
+ this._setTab(/** @type {any} */ (id));
3249
+ return id;
3250
+ }
3251
+ }
3252
+ const id = `treemap${this._nextTreemap++}`;
3253
+ const tab = { source, key, data, view: null };
3254
+ this._treemapTabs.set(id, tab);
3255
+ this._addTreemapTab(id, tab);
3256
+ this._setTab(/** @type {any} */ (id));
3257
+ return id;
3258
+ }
3259
+
3260
+ /**
3261
+ * Builds the button and the panel of a treemap tab. The button's cross closes the tab, as does
3262
+ * a middle click on it.
3263
+ *
3264
+ * @param {string} id - The tab's id.
3265
+ * @param {{ data: TreemapData, view: TreemapView|null }} tab - The tab.
3266
+ * @private
3267
+ */
3268
+ _addTreemapTab(id, tab) {
3269
+ // a box shows what it measured in the tab listing it; when that tab no longer lists it,
3270
+ // the treemap stays, to say so
3271
+ const view = new TreemapView(tab.data, {
3272
+ label: (target) => {
3273
+ const where = this._tabOf(target);
3274
+ return where ? `the ${this._tabButtons[where].textContent} tab` : null;
3275
+ },
3276
+ open: (target) => {
3277
+ if (this._selectAny(target)) return true;
3278
+ this._setTab(/** @type {any} */ (id));
3279
+ return false;
3280
+ }
3281
+ });
3282
+ tab.view = view;
3283
+ view.el.style.display = 'none';
3284
+ this._hierarchyEl.appendChild(view.el);
3285
+ this._panels[id] = view.el;
3286
+
3287
+ const button = el('button', 'pci-tab pci-tab-closable', view.title);
3288
+ setTip(button, `A treemap of ${tab.data.from ? 'two snapshots' : 'a snapshot'} of the ${tab.data.tab} tab. A middle click closes it`);
3289
+ const close = el('span', 'pci-tab-close', '×');
3290
+ setTip(close, 'Close this tab');
3291
+ close.addEventListener('click', (e) => {
3292
+ e.stopPropagation();
3293
+ this._closeTreemap(id);
3294
+ });
3295
+ button.appendChild(close);
3296
+ button.addEventListener('click', () => this._setTab(/** @type {any} */ (id)));
3297
+ // a middle press would start the browser's scrolling
3298
+ button.addEventListener('mousedown', (e) => {
3299
+ if (e.button === 1) e.preventDefault();
3300
+ });
3301
+ button.addEventListener('auxclick', (e) => {
3302
+ if (e.button === 1) this._closeTreemap(id);
3303
+ });
3304
+ this._tabsEl.appendChild(button);
3305
+ this._tabButtons[id] = button;
3306
+ }
3307
+
3308
+ /**
3309
+ * Closes a treemap tab, going back to the tab its snapshots came from when it was shown.
3310
+ *
3311
+ * @param {string} id - The tab's id.
3312
+ * @private
3313
+ */
3314
+ _closeTreemap(id) {
3315
+ const tab = this._treemapTabs.get(id);
3316
+ if (!tab) return;
3317
+ this._treemapTabs.delete(id);
3318
+ tab.view?.el.remove();
3319
+ this._tabButtons[id]?.remove();
3320
+ delete this._tabButtons[id];
3321
+ delete this._panels[id];
3322
+ if (this._tab === id) this._setTab(/** @type {any} */ (tab.source));
3323
+ }
3324
+
2783
3325
  /**
2784
3326
  * @param {HTMLElement} parent - The bar to add the toggle to.
2785
3327
  * @param {string} label - The label.
@@ -2860,6 +3402,9 @@ class Inspector {
2860
3402
  * @private
2861
3403
  */
2862
3404
  _setRecording(on) {
3405
+ // a capture started other than by the tools is the user's, which the tools do not clear
3406
+ // unasked; the tools mark their own once started
3407
+ if (on && !this._perf.recording) this._mcpHost.perf.byAgent = false;
2863
3408
  if (on) this._perf.start();
2864
3409
  else this._perf.stop();
2865
3410
  this._perfCharts.invalidate();
@@ -2936,15 +3481,18 @@ class Inspector {
2936
3481
  /**
2937
3482
  * Switches the list tab and points the property view at that tab's selection.
2938
3483
  *
2939
- * @param {'hierarchy'|'cameras'|'assets'|'passes'|'perf'|'targets'|'textures'|'meshes'|'materials'|'scripts'|'memory'|'shaders'|'physics'} tab - The tab.
3484
+ * @param {'hierarchy'|'cameras'|'layers'|'assets'|'passes'|'perf'|'targets'|'textures'|'meshes'|'materials'|'scripts'|'memory'|'shaders'|'physics'|`treemap${number}`} tab - The tab.
2940
3485
  * @private
2941
3486
  */
2942
3487
  _setTab(tab) {
2943
3488
  this._tab = tab;
2944
3489
  this._menu?.hide();
3490
+ const treemap = this._treemapTabs.get(tab);
2945
3491
  this._filterBy.style.display = tab === 'hierarchy' ? '' : 'none';
2946
- // the Performance tab has no list to filter
2947
- this._filterEl.style.display = tab === 'perf' ? 'none' : '';
3492
+ // the Performance and treemap tabs have no list to filter
3493
+ this._filterEl.style.display = tab === 'perf' || treemap ? 'none' : '';
3494
+ // a treemap has the whole height, the properties put away while it shows
3495
+ this._bodyEl.classList.toggle('pci-full', !!treemap);
2948
3496
  this._hierarchyEl.classList.toggle('pci-tall', tab === 'perf');
2949
3497
  if (tab === 'perf') this._perfCharts.invalidate();
2950
3498
  this._updateFilterHint();
@@ -2954,6 +3502,8 @@ class Inspector {
2954
3502
  for (const [id, panel] of Object.entries(this._panels)) {
2955
3503
  panel.style.display = id === tab ? '' : 'none';
2956
3504
  }
3505
+ // drawn once shown, when it has a size
3506
+ treemap?.view?.render();
2957
3507
  // measured with the tab's panel shown
2958
3508
  if (tab === 'perf') this._fitTop();
2959
3509
  this._refreshLists(false);
@@ -2975,6 +3525,14 @@ class Inspector {
2975
3525
  _refreshLists(capture) {
2976
3526
  const device = this._app.graphicsDevice;
2977
3527
 
3528
+ const treemap = this._treemapTabs.get(this._tab);
3529
+ if (treemap) {
3530
+ // a treemap holds still: it is drawn again only when its tab changes size
3531
+ treemap.view?.fit();
3532
+ this._updateStatus();
3533
+ return;
3534
+ }
3535
+
2978
3536
  if (this._tab === 'hierarchy') {
2979
3537
  this._hierarchy.refresh();
2980
3538
  } else if (this._tab === 'physics') {
@@ -3025,6 +3583,13 @@ class Inspector {
3025
3583
  if (camera !== this._properties.subject) {
3026
3584
  this._properties.setSubject(camera, this._cameraModel, this._cameraList.selectedKey);
3027
3585
  }
3586
+ } else if (this._tab === 'layers') {
3587
+ this._pruneHiddenLayers();
3588
+ this._layerList.setRows(layerRows(this._app, layer => this._hiddenLayers.has(layer)));
3589
+ const layer = this._layerList.selected;
3590
+ if (layer !== this._properties.subject) {
3591
+ this._properties.setSubject(layer, this._layerModel, this._layerList.selectedKey);
3592
+ }
3028
3593
  } else if (this._tab === 'scripts') {
3029
3594
  this._scriptList.setRows(scriptListRows(surveyScripts(this._app)));
3030
3595
  const cls = this._scriptList.selected;
@@ -3095,6 +3660,7 @@ class Inspector {
3095
3660
  this._materialList.filter = names;
3096
3661
  this._scriptList.filter = names;
3097
3662
  this._cameraList.filter = names;
3663
+ this._layerList.filter = names;
3098
3664
  this._bodyList.filter = names;
3099
3665
  this._refreshLists(false);
3100
3666
  // the instances listed under a forward pass narrow with the filter too
@@ -3115,6 +3681,7 @@ class Inspector {
3115
3681
  materials: this._materialList,
3116
3682
  scripts: this._scriptList,
3117
3683
  cameras: this._cameraList,
3684
+ layers: this._layerList,
3118
3685
  memory: this._bufferList,
3119
3686
  assets: this._assetList,
3120
3687
  physics: this._bodyList
@@ -3340,11 +3907,8 @@ class Inspector {
3340
3907
  const frames = charts.range ? `, ${capture.rangeLabel(from, to).toLowerCase()}` : '';
3341
3908
  const figures = json => ({ json, objects: 0, truncated: false });
3342
3909
  switch (what.kind) {
3343
- case 'capture': {
3344
- const device = this._app.graphicsDevice;
3345
- const info = { type: device.deviceType, width: device.width, height: device.height, maxPixelRatio: device.maxPixelRatio };
3346
- return { title: `Performance${frames}`, plain: true, copy: () => figures(captureJson(capture, from, to, info)) };
3347
- }
3910
+ case 'capture':
3911
+ return { title: `Performance${frames}`, plain: true, copy: () => figures(captureJson(capture, from, to, this._deviceInfo())) };
3348
3912
  case 'series': {
3349
3913
  const name = PERF_SERIES_NAMES[what.key] ?? what.key;
3350
3914
  return {
@@ -3366,6 +3930,15 @@ class Inspector {
3366
3930
  return null;
3367
3931
  }
3368
3932
 
3933
+ /**
3934
+ * @returns {object} What a copy of a capture says about the device: its type and size.
3935
+ * @private
3936
+ */
3937
+ _deviceInfo() {
3938
+ const device = this._app.graphicsDevice;
3939
+ return { type: device.deviceType, width: device.width, height: device.height, maxPixelRatio: device.maxPixelRatio };
3940
+ }
3941
+
3369
3942
  /**
3370
3943
  * @returns {Set<object>} The app's own objects, which a copy never follows, as through them it
3371
3944
  * would reach everything else.
@@ -3403,6 +3976,7 @@ class Inspector {
3403
3976
  if (obj instanceof Shader) return buildShaderModel(obj);
3404
3977
  if (obj instanceof Asset) return buildAssetModel(obj, ctx);
3405
3978
  if (isScriptClass(obj)) return buildScriptModel(/** @type {Function} */ (obj), ctx);
3979
+ if (obj instanceof Layer) return this._layerModel(obj);
3406
3980
  if (obj instanceof Material) return buildMaterialModel(obj, ctx);
3407
3981
  if (obj instanceof Mesh) return buildMeshModel(obj, ctx);
3408
3982
  if (bufferKind(obj)) return buildBufferModel(obj, ctx);
@@ -3425,45 +3999,45 @@ class Inspector {
3425
3999
  if (entry) this._passList.selectItem(entry.pass);
3426
4000
  }
3427
4001
 
4002
+ /**
4003
+ * @param {*} target - An object.
4004
+ * @returns {'hierarchy'|'targets'|'passes'|'textures'|'shaders'|'assets'|'scripts'|'layers'|'materials'|'meshes'|'memory'|null}
4005
+ * The tab that lists objects of its kind, or null when none does.
4006
+ * @private
4007
+ */
4008
+ _tabOf(target) {
4009
+ if (target instanceof GraphNode) return 'hierarchy';
4010
+ if (target instanceof RenderTarget) return 'targets';
4011
+ if (target instanceof FramePass) return 'passes';
4012
+ if (target instanceof Texture) return 'textures';
4013
+ if (target instanceof Shader) return 'shaders';
4014
+ if (target instanceof Asset) return 'assets';
4015
+ if (isScriptClass(target)) return 'scripts';
4016
+ if (target instanceof Layer) return 'layers';
4017
+ if (target instanceof Material) return 'materials';
4018
+ if (target instanceof Mesh) return 'meshes';
4019
+ if (bufferKind(target)) return 'memory';
4020
+ return null;
4021
+ }
4022
+
3428
4023
  /**
3429
4024
  * Reveals a linked object in the tab that lists it: nodes in the hierarchy, passes in the frame
3430
4025
  * graph, render targets in their list.
3431
4026
  *
3432
4027
  * @param {*} target - The object.
4028
+ * @returns {boolean} Whether the tab lists it, as one listing what is on the device does not
4029
+ * once the object is destroyed.
3433
4030
  * @private
3434
4031
  */
3435
4032
  _selectAny(target) {
3436
- if (target instanceof GraphNode) {
3437
- this._setTab('hierarchy');
4033
+ const tab = this._tabOf(target);
4034
+ if (!tab) return false;
4035
+ this._setTab(tab);
4036
+ if (tab === 'hierarchy') {
3438
4037
  this._hierarchy.select(target);
3439
- } else if (target instanceof RenderTarget) {
3440
- this._setTab('targets');
3441
- this._targetList.selectItem(target);
3442
- } else if (target instanceof FramePass) {
3443
- this._setTab('passes');
3444
- this._passList.selectItem(target);
3445
- } else if (target instanceof Texture) {
3446
- this._setTab('textures');
3447
- this._textureList.selectItem(target);
3448
- } else if (target instanceof Shader) {
3449
- this._setTab('shaders');
3450
- this._shaderList.selectItem(target);
3451
- } else if (target instanceof Asset) {
3452
- this._setTab('assets');
3453
- this._assetList.selectItem(target);
3454
- } else if (isScriptClass(target)) {
3455
- this._setTab('scripts');
3456
- this._scriptList.selectItem(target);
3457
- } else if (target instanceof Material) {
3458
- this._setTab('materials');
3459
- this._materialList.selectItem(target);
3460
- } else if (target instanceof Mesh) {
3461
- this._setTab('meshes');
3462
- this._meshList.selectItem(target);
3463
- } else if (bufferKind(target)) {
3464
- this._setTab('memory');
3465
- this._bufferList.selectItem(target);
4038
+ return true;
3466
4039
  }
4040
+ return this._tabLists()[tab].selectItem(target);
3467
4041
  }
3468
4042
 
3469
4043
  /**
@@ -3602,7 +4176,10 @@ class Inspector {
3602
4176
  let counts = '';
3603
4177
  let selected = '';
3604
4178
 
3605
- switch (this._tab) {
4179
+ switch (this._treemapTabs.has(this._tab) ? 'treemap' : this._tab) {
4180
+ case 'treemap':
4181
+ counts = this._treemapTabs.get(this._tab).data.measure;
4182
+ break;
3606
4183
  case 'passes': {
3607
4184
  const gpu = this._frame?.frameTime;
3608
4185
  // WebGL times the frame with a single query; only WebGPU timestamps each pass
@@ -3667,6 +4244,15 @@ class Inspector {
3667
4244
  selected = this._cameraList.selected?.entity.name ?? '';
3668
4245
  break;
3669
4246
  }
4247
+ case 'layers': {
4248
+ const subLayers = collectSubLayers(this._app.scene?.layers);
4249
+ const layers = new Set(subLayers.map(sub => sub.layer));
4250
+ const rendering = subLayers.filter(sub => sub.enabled && sub.layer.cameras.length > 0).length;
4251
+ counts = `${layers.size} layers · ${subLayers.length} in the composition · ${rendering} rendering`;
4252
+ if (this._hiddenLayers.size) counts += ` · ${this._hiddenLayers.size} hidden`;
4253
+ selected = this._layerList.selected?.name ?? '';
4254
+ break;
4255
+ }
3670
4256
  case 'scripts': {
3671
4257
  const survey = surveyScripts(this._app);
3672
4258
  const instances = [...survey.values()].reduce((sum, script) => sum + script.instances.length, 0);
@@ -3932,9 +4518,66 @@ class Inspector {
3932
4518
  this._stopFly();
3933
4519
  this._setTransformMode(null);
3934
4520
  this._resetRenderOverrides();
4521
+ this._showHiddenLayers();
3935
4522
  this._modeEl.textContent = '';
3936
4523
  }
3937
4524
 
4525
+ /**
4526
+ * Hides a layer from the view by turning it off, or turns a layer hidden here back on. Only a
4527
+ * layer the app has on can be hidden, so showing it again restores what the app had.
4528
+ *
4529
+ * @param {Layer} layer - The layer.
4530
+ * @param {boolean} hidden - Whether to hide it.
4531
+ * @private
4532
+ */
4533
+ _hideLayer(layer, hidden) {
4534
+ if (hidden) {
4535
+ if (!layer.enabled || this._hiddenLayers.has(layer)) return;
4536
+ this._hiddenLayers.add(layer);
4537
+ layer.enabled = false;
4538
+ } else {
4539
+ if (!this._hiddenLayers.delete(layer)) return;
4540
+ layer.enabled = true;
4541
+ }
4542
+ this._afterLayersChanged();
4543
+ }
4544
+
4545
+ /**
4546
+ * Turns every layer hidden here back on.
4547
+ *
4548
+ * @private
4549
+ */
4550
+ _showHiddenLayers() {
4551
+ if (this._hiddenLayers.size === 0) return;
4552
+ for (const layer of this._hiddenLayers) layer.enabled = true;
4553
+ this._hiddenLayers.clear();
4554
+ this._afterLayersChanged();
4555
+ }
4556
+
4557
+ /**
4558
+ * Forgets the hidden layers the app has turned back on itself, or taken out of the composition,
4559
+ * so the panel never turns on a layer it no longer hides.
4560
+ *
4561
+ * @private
4562
+ */
4563
+ _pruneHiddenLayers() {
4564
+ const composition = this._app.scene?.layers;
4565
+ for (const layer of this._hiddenLayers) {
4566
+ if (layer.enabled || !composition?.layerList.includes(layer)) this._hiddenLayers.delete(layer);
4567
+ }
4568
+ if (this._showLayersBtn) this._showLayersBtn.disabled = this._hiddenLayers.size === 0;
4569
+ }
4570
+
4571
+ /**
4572
+ * @private
4573
+ */
4574
+ _afterLayersChanged() {
4575
+ if (this._showLayersBtn) this._showLayersBtn.disabled = this._hiddenLayers.size === 0;
4576
+ this._refreshLists(false);
4577
+ this._properties.refresh();
4578
+ this._updateStatus();
4579
+ }
4580
+
3938
4581
  /**
3939
4582
  * Puts back the shader pass each camera had before the panel changed it, and turns wireframe
3940
4583
  * off.