@playcanvas/inspector 0.3.0 → 0.4.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
@@ -10,7 +10,7 @@ import { ASSET_SORTS, assetRows, buildAssetModel, collectAssets } from './asset-
10
10
  import { buildCameraModel, cameraRows, collectCameras } from './camera-view.js';
11
11
  import { ContextMenu } from './context-menu.js';
12
12
  import { copyGroup, copyList, copyListRow, copySubject, stringifyCopy } from './copy-json.js';
13
- import { INSTANCES_PER_PAGE, LayerStepSelection, buildPassModel, buildStepModel, captureFrameGraph, passRows } from './frame-graph-view.js';
13
+ import { INSTANCES_PER_PAGE, LayerStepSelection, buildPassModel, buildStepModel, captureFrameGraph, passRows, profilerName } from './frame-graph-view.js';
14
14
  import { bufferKind, bufferOwners, buildBufferModel, KIND_NAMES, memoryRows, videoMemory } from './memory-view.js';
15
15
  import { HierarchyView, filterSuggestions } from './hierarchy-view.js';
16
16
  import { ListView } from './list-view.js';
@@ -21,6 +21,10 @@ import {
21
21
  import { buildMeshModel, meshBytes, meshListRows, meshNote, surveyMeshes } from './mesh-view.js';
22
22
  import { formatBytes, formatName, passDisplayName } from './model.js';
23
23
  import { buildComponentModel, buildNodeModel, meshInstanceRows } from './node-model.js';
24
+ import { PerfCapture } from './perf-capture.js';
25
+ import { PerfCharts } from './perf-chart.js';
26
+ import { captureJson, frameJson, rangeJson, seriesRows, toCsv } from './perf-copy.js';
27
+ import { buildPerfModel, captureNorms, formatMs, isHitch } from './perf-view.js';
24
28
  import { AmmoDebugDraw, DEBUG_DRAW } from './physics-debug.js';
25
29
  import { bodyRows, drawCollisionShape, drawJoint, jointRows, physicsStats } from './physics-view.js';
26
30
  import { PropertyView } from './property-view.js';
@@ -59,13 +63,19 @@ import { TRANSFORM_POINTER_EVENTS, TransformTool } from './transform-tool.js';
59
63
  * @property {GraphNode|null} [lockedNode] - A node whose enabled checkbox, and those of its
60
64
  * ancestors, are withheld. A script hosting the inspector passes its own entity so the panel
61
65
  * cannot switch itself off. Defaults to null.
66
+ * @property {boolean} [record] - Whether to start recording frames for the Performance tab right
67
+ * away, as if Record were pressed, so the capture begins with the first frame the app runs after
68
+ * the inspector is created. Defaults to false. See {@link Inspector#recording}.
62
69
  * @property {(visible: boolean) => void} [onVisibleChange] - Called with the new visibility
63
70
  * whenever the panel is shown or hidden, whether through {@link Inspector#visible}, the toggle key
64
71
  * or the panel's own close button.
65
72
  * @property {string|null} [storageKey] - The local storage key the panel's settings are kept
66
73
  * under, so they survive a reload or a restart of the app: the physics drawing switch and options,
67
- * the bodies excluded from it (by entity path), the active tab, the panel width and the GPU
68
- * timings switch. Stored settings take precedence over the defaults given here. Defaults to
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
76
+ * includes the inspector's time, the charts collapsed and lines hidden, and the script types the
77
+ * Scripts chart shows. Stored settings take
78
+ * precedence over the defaults given here. Defaults to
69
79
  * 'pc-inspector'; null keeps nothing.
70
80
  */
71
81
 
@@ -104,12 +114,36 @@ const PHYSICS_FLAGS = {
104
114
  const LIST_INTERVAL = 0.5;
105
115
  const PROPERTY_INTERVAL = 0.1;
106
116
 
117
+ // seconds between refreshes of the Performance tab's frame details, which it redraws with its
118
+ // charts at the same pace
119
+ const PERF_PROPERTY_INTERVAL = 0.25;
120
+
121
+ // the least height of the part above the splitter, and of the Performance tab's charts in it,
122
+ // which scroll below that; the styles hold the same
123
+ const MIN_TOP_HEIGHT = 60;
124
+ const MIN_PERF_CHARTS_HEIGHT = 60;
125
+
126
+ // the names a copy of each series of the Performance tab goes by
127
+ const PERF_SERIES_NAMES = {
128
+ frame: 'Frame',
129
+ cpu: 'CPU',
130
+ gpu: 'GPU',
131
+ draws: 'Draw calls',
132
+ scripts: 'Scripts',
133
+ counters: 'Counters',
134
+ loading: 'Loading',
135
+ memory: 'Memory',
136
+ resources: 'Resources',
137
+ events: 'Events'
138
+ };
139
+
107
140
  // the tooltips of the tabs
108
141
  const TAB_TIPS = {
109
142
  hierarchy: 'The entity tree, and the components and properties of the selected entity',
110
143
  cameras: 'The cameras of the scene in render order, with where they draw, their render mode and a way to fly each',
111
144
  assets: 'The assets of the registry, and what uses each',
112
145
  passes: 'The passes that rendered the last frame, with the layers, draws and targets of each',
146
+ 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',
113
147
  targets: 'The render targets on the device, with a live preview of their textures',
114
148
  textures: 'The textures on the device, largest first, with a live preview',
115
149
  meshes: 'The meshes of the app, found through the components, layers and assets using them, largest first',
@@ -180,7 +214,7 @@ function isTextTarget(e) {
180
214
  }
181
215
 
182
216
  /**
183
- * An in-page inspector for a running application. It docks a panel over the canvas with twelve
217
+ * An in-page inspector for a running application. It docks a panel over the canvas with thirteen
184
218
  * tabs above a live property view of whatever is selected:
185
219
  *
186
220
  * - Hierarchy: the entity tree. The property view shows the node's transform, every component it
@@ -195,6 +229,12 @@ function isTextTarget(e) {
195
229
  * prints them, with the layer steps of forward passes, the light of shadow passes and optional
196
230
  * GPU timings. Render target cells link to the next tab. With the debug engine, the debug frame
197
231
  * draws a forward pass only up to a chosen draw, stepped one draw at a time with the arrow keys.
232
+ * - Performance: frames recorded while Record is on, up to the last 1000, charted over
233
+ * the whole capture: the frame interval, the CPU time on the main thread by phase, the GPU time,
234
+ * the draw calls and video memory, and the events of each frame, such as shaders compiled and
235
+ * the main thread blocked. Clicking a frame shows it on a timeline of its own and everything
236
+ * recorded for it in the property view; dragging selects frames to compare their figures. The
237
+ * inspector's own time is told apart from the app's.
198
238
  * - Render targets: every render target on the device including the backbuffer, with its
199
239
  * attachments and the passes that rendered into it this frame, linking back to the frame graph.
200
240
  * The selected target's attachment can be previewed live in a corner of the viewport.
@@ -419,11 +459,104 @@ class Inspector {
419
459
  _nextPropertyRefresh = 0;
420
460
 
421
461
  /**
422
- * @type {'hierarchy'|'cameras'|'assets'|'passes'|'targets'|'textures'|'meshes'|'materials'|'scripts'|'memory'|'shaders'|'physics'}
462
+ * @type {'hierarchy'|'cameras'|'assets'|'passes'|'perf'|'targets'|'textures'|'meshes'|'materials'|'scripts'|'memory'|'shaders'|'physics'}
423
463
  * @private
424
464
  */
425
465
  _tab = 'hierarchy';
426
466
 
467
+ /**
468
+ * The frames recorded for the Performance tab. Hooked into the app only while recording.
469
+ *
470
+ * @type {PerfCapture}
471
+ * @private
472
+ */
473
+ _perf;
474
+
475
+ /**
476
+ * The charts of the Performance tab, and the frame they show.
477
+ *
478
+ * @type {PerfCharts}
479
+ * @private
480
+ */
481
+ _perfCharts;
482
+
483
+ /**
484
+ * @type {HTMLButtonElement}
485
+ * @private
486
+ */
487
+ _perfRecordBtn;
488
+
489
+ /**
490
+ * Shows the newest frame, and keeps following it as frames are recorded.
491
+ *
492
+ * @type {HTMLButtonElement}
493
+ * @private
494
+ */
495
+ _perfLastBtn;
496
+
497
+ /**
498
+ * The GPU timings switch of the Performance tab, kept in step with the Frame graph's.
499
+ *
500
+ * @type {HTMLInputElement}
501
+ * @private
502
+ */
503
+ _perfGpuToggle;
504
+
505
+ /**
506
+ * Whether the CPU chart includes the inspector's own time.
507
+ *
508
+ * @type {HTMLInputElement}
509
+ * @private
510
+ */
511
+ _perfInspectorToggle;
512
+
513
+ /**
514
+ * Whether to time each script type while recording.
515
+ *
516
+ * @type {HTMLInputElement}
517
+ * @private
518
+ */
519
+ _perfScriptsToggle;
520
+
521
+ /**
522
+ * @type {HTMLElement}
523
+ * @private
524
+ */
525
+ _perfNote;
526
+
527
+ /**
528
+ * The filter bar, which the Performance tab has no list for.
529
+ *
530
+ * @type {HTMLElement}
531
+ * @private
532
+ */
533
+ _filterEl;
534
+
535
+ /**
536
+ * Model builder for the property view on the Performance tab: the frames the charts show.
537
+ *
538
+ * @param {PerfCharts} charts - The charts.
539
+ * @returns {PropertySection[]} The sections.
540
+ * @private
541
+ */
542
+ _perfModel = charts => buildPerfModel({
543
+ capture: this._perf,
544
+ seq: charts.shown,
545
+ range: charts.range,
546
+ gpu: {
547
+ supported: !!this._app.graphicsDevice.gpuProfiler,
548
+ enabled: !!this._app.graphicsDevice.gpuProfiler?.enabled,
549
+ enable: () => this._setGpuTimings(true)
550
+ },
551
+ scripts: {
552
+ enabled: this._perf.timeScripts,
553
+ enable: () => this._setScriptTiming(true),
554
+ rows: charts.scriptRows,
555
+ pinned: charts.pinned,
556
+ pin: name => charts.togglePin(name)
557
+ }
558
+ });
559
+
427
560
  /**
428
561
  * @type {FrameSnapshot|null}
429
562
  * @private
@@ -1029,6 +1162,7 @@ class Inspector {
1029
1162
 
1030
1163
  this._wire = new WireRenderer(app);
1031
1164
  this._textures = new TextureRenderer(app);
1165
+ this._perf = new PerfCapture(app);
1032
1166
  this._buildDom();
1033
1167
  this._hierarchy.setRoot(app.root);
1034
1168
  this._gpuWasEnabled = !!app.graphicsDevice.gpuProfiler?.enabled;
@@ -1042,6 +1176,7 @@ class Inspector {
1042
1176
  this._applyVisibility();
1043
1177
  this._applyPauseState();
1044
1178
  this._refresh();
1179
+ if (options.record) this._setRecording(true);
1045
1180
  this._restoring = false;
1046
1181
 
1047
1182
  window.addEventListener('keydown', this._onKeyDown);
@@ -1073,6 +1208,8 @@ class Inspector {
1073
1208
  this._picker = null;
1074
1209
 
1075
1210
  this.paused = false;
1211
+ this._perf.destroy();
1212
+ this._perfCharts.destroy();
1076
1213
  const profiler = app.graphicsDevice?.gpuProfiler;
1077
1214
  if (profiler) profiler.enabled = this._gpuWasEnabled;
1078
1215
  this._pruneHiddenBodies();
@@ -1142,6 +1279,27 @@ class Inspector {
1142
1279
  return this._paused;
1143
1280
  }
1144
1281
 
1282
+ /**
1283
+ * Whether frames are being recorded for the Performance tab, as its Record button shows. Set it
1284
+ * to start or stop a capture from code, such as around a part of the app to profile. Starting
1285
+ * adds to the frames kept, up to the last 1000; the tab's Clear button forgets them.
1286
+ *
1287
+ * @type {boolean}
1288
+ * @example
1289
+ * inspector.recording = true;
1290
+ * await loadLevel();
1291
+ * inspector.recording = false;
1292
+ */
1293
+ set recording(value) {
1294
+ value = !!value;
1295
+ if (this._destroyed || value === this._perf.recording) return;
1296
+ this._setRecording(value);
1297
+ }
1298
+
1299
+ get recording() {
1300
+ return this._perf.recording;
1301
+ }
1302
+
1145
1303
  /**
1146
1304
  * Whether the physics world is drawn over the scene while the panel is shown: the Draw checkbox
1147
1305
  * of the Physics tab. Hiding the panel suspends the drawing; showing it again resumes it.
@@ -1272,6 +1430,7 @@ class Inspector {
1272
1430
  // the document that held the panel is gone, so the panel is too: build it anew
1273
1431
  const selected = this._selected;
1274
1432
  this._host.remove?.();
1433
+ this._perfCharts.destroy();
1275
1434
  this._buildDom();
1276
1435
  this._hierarchy.setRoot(this._app.root);
1277
1436
  if (selected) this._hierarchy.select(selected);
@@ -1284,10 +1443,23 @@ class Inspector {
1284
1443
  }
1285
1444
 
1286
1445
  /**
1446
+ * Runs the panel's work for the frame, timed so a capture can tell it apart from the app's own:
1447
+ * it runs inside the app's update.
1448
+ *
1287
1449
  * @param {number} dt - The frame delta, scaled by the app time scale.
1288
1450
  * @private
1289
1451
  */
1290
1452
  _onUpdate(dt) {
1453
+ const start = performance.now();
1454
+ this._updatePanel(dt);
1455
+ this._perf.addOverhead(start, performance.now() - start);
1456
+ }
1457
+
1458
+ /**
1459
+ * @param {number} dt - The frame delta, scaled by the app time scale.
1460
+ * @private
1461
+ */
1462
+ _updatePanel(dt) {
1291
1463
  this._drawPhysics();
1292
1464
 
1293
1465
  // the user closed the pop-out window: bring the panel home
@@ -1297,7 +1469,12 @@ class Inspector {
1297
1469
 
1298
1470
  // wall clock, as the frame delta is zero while paused
1299
1471
  const now = performance.now();
1300
- if (now >= this._nextListRefresh) {
1472
+
1473
+ // the charts of the Performance tab redraw on their own pace; the list and property
1474
+ // refreshes wait for a frame without a redraw, so no one frame takes the cost of all three
1475
+ const perfDrew = this._tab === 'perf' && this._perfCharts.update(now);
1476
+
1477
+ if (now >= this._nextListRefresh && !perfDrew) {
1301
1478
  this._nextListRefresh = now + LIST_INTERVAL * 1000;
1302
1479
  this._refreshLists(true);
1303
1480
  // mesh instances the app added since are drawn in wireframe too
@@ -1309,8 +1486,8 @@ class Inspector {
1309
1486
  this._drawHighlight(this._cameraList.selected.entity);
1310
1487
  }
1311
1488
  this._updateModeStatus();
1312
- if (now >= this._nextPropertyRefresh) {
1313
- this._nextPropertyRefresh = now + PROPERTY_INTERVAL * 1000;
1489
+ if (now >= this._nextPropertyRefresh && !perfDrew) {
1490
+ this._nextPropertyRefresh = now + (this._tab === 'perf' ? PERF_PROPERTY_INTERVAL : PROPERTY_INTERVAL) * 1000;
1314
1491
  this._properties.refresh();
1315
1492
  }
1316
1493
 
@@ -1440,7 +1617,7 @@ class Inspector {
1440
1617
  const tabs = el('div', 'pci-tabs');
1441
1618
  this._tabButtons = {};
1442
1619
  const tabList = [
1443
- ['hierarchy', 'Hierarchy'], ['cameras', 'Cameras'], ['assets', 'Assets'], ['passes', 'Frame graph'],
1620
+ ['hierarchy', 'Hierarchy'], ['cameras', 'Cameras'], ['assets', 'Assets'], ['passes', 'Frame graph'], ['perf', 'Performance'],
1444
1621
  ['targets', 'Render targets'], ['textures', 'Textures'], ['meshes', 'Meshes'], ['materials', 'Materials'], ['scripts', 'Scripts'], ['memory', 'Memory'],
1445
1622
  ['shaders', 'Shaders'], ['physics', 'Physics']
1446
1623
  ];
@@ -1453,6 +1630,7 @@ class Inspector {
1453
1630
  }
1454
1631
 
1455
1632
  const filter = el('div', 'pci-filter');
1633
+ this._filterEl = filter;
1456
1634
  // what the hierarchy filter matches, shown on that tab only: the lists match names
1457
1635
  this._filterBy = /** @type {HTMLSelectElement} */ (document.createElement('select'));
1458
1636
  this._filterBy.className = 'pci-select';
@@ -1490,6 +1668,68 @@ class Inspector {
1490
1668
  const passList = el('div', 'pci-list');
1491
1669
  passPanel.append(passBar, this._passNote, passList);
1492
1670
 
1671
+ // performance: recording controls, the charts of the capture and the timeline of a frame
1672
+ const perfPanel = el('div', 'pci-listpanel');
1673
+ const perfBar = el('div', 'pci-subbar pci-wrap');
1674
+ const button = (parent, text, tip, run) => {
1675
+ const b = /** @type {HTMLButtonElement} */ (el('button', 'pci-btn', text));
1676
+ setTip(b, tip);
1677
+ b.addEventListener('click', run);
1678
+ parent.appendChild(b);
1679
+ return b;
1680
+ };
1681
+ const recordGroup = el('span', 'pci-group');
1682
+ this._perfRecordBtn = iconButton('record', 'Record');
1683
+ this._perfRecordBtn.classList.add('pci-small', 'pci-record');
1684
+ this._perfRecordBtn.addEventListener('click', () => this._setRecording(!this._perf.recording));
1685
+ const clearBtn = iconButton('clear', 'Clear');
1686
+ clearBtn.classList.add('pci-small');
1687
+ setTip(clearBtn, 'Clear: forget every frame recorded');
1688
+ clearBtn.addEventListener('click', () => {
1689
+ this._perf.clear();
1690
+ this._perfCharts.reset();
1691
+ });
1692
+ recordGroup.append(this._perfRecordBtn, clearBtn);
1693
+ const frameGroup = el('span', 'pci-group');
1694
+ button(frameGroup, '«', 'Show the first frame kept. The Home key does the same while the panel has focus', () => this._perfCharts.pick(this._perf.first));
1695
+ button(frameGroup, '‹', 'Show the frame before. The left arrow key does the same while the panel has focus; with Shift, ten frames', () => this._perfCharts.step(-1));
1696
+ button(frameGroup, '›', 'Show the frame after. The right arrow key does the same while the panel has focus; with Shift, ten frames', () => this._perfCharts.step(1));
1697
+ this._perfLastBtn = button(frameGroup, '»', 'Show the newest frame, and keep showing it as frames are recorded. The End key does the same while the panel has focus', () => this._perfCharts.follow());
1698
+ perfBar.append(recordGroup, frameGroup);
1699
+ this._perfGpuToggle = this._makeToggle(perfBar, 'GPU timings',
1700
+ 'Enable the GPU profiler and record the time each frame and each pass take on the GPU. Measuring adds a little overhead');
1701
+ this._perfInspectorToggle = this._makeToggle(perfBar, 'Inspector time',
1702
+ 'Include the inspector\'s own time in the CPU chart. It runs inside the app\'s update; leave it out to scale the chart\nto the app\'s own time. The frame details list it either way');
1703
+ this._perfInspectorToggle.checked = true;
1704
+ this._perfScriptsToggle = this._makeToggle(perfBar, 'Script timing',
1705
+ 'Time each script type\'s update, post-update and initialize while recording. Timing a call costs the app about half a\nmicrosecond, counted as the inspector\'s time. Time spent in event handlers, timers and promises is not counted');
1706
+ this._perfScriptsToggle.addEventListener('change', () => this._setScriptTiming(this._perfScriptsToggle.checked));
1707
+ if (!this._perf.supports.scripts) {
1708
+ this._perfScriptsToggle.disabled = true;
1709
+ setTip(this._perfScriptsToggle.parentElement, 'This app has no script system');
1710
+ }
1711
+ this._perfNote = el('div', 'pci-note pci-note-info');
1712
+ this._perfNote.style.display = 'none';
1713
+ perfPanel.append(perfBar, this._perfNote);
1714
+ this._perfCharts = new PerfCharts(perfPanel, this._perf);
1715
+ setTip(this._perfCharts.timelineElement, 'The frame shown, along its own time. The GPU passes are drawn back to back,\nas the GPU says how long each took but not when it ran');
1716
+ this._perfCharts.onChange = () => this._onPerfChange();
1717
+ this._perfCharts.onSelectScript = (id) => {
1718
+ const cls = this._perf.scriptClasses[id];
1719
+ if (cls) this._selectAny(cls);
1720
+ };
1721
+ this._perfCharts.onSelectPass = pass => this._showPass(pass);
1722
+ this._perfCharts.onSelectAsset = (id) => {
1723
+ const asset = this._app.assets.get(id);
1724
+ if (asset) this._selectAny(asset);
1725
+ };
1726
+ this._perfCharts.onCollapse = () => this._saveSettings();
1727
+ this._perfInspectorToggle.addEventListener('change', () => {
1728
+ this._perfCharts.showInspector = this._perfInspectorToggle.checked;
1729
+ this._perfCharts.invalidate();
1730
+ this._saveSettings();
1731
+ });
1732
+
1493
1733
  // render targets: a live preview of the selected target, drawn over the canvas
1494
1734
  const targetPanel = el('div', 'pci-listpanel');
1495
1735
  const targetBar = el('div', 'pci-subbar');
@@ -1630,6 +1870,7 @@ class Inspector {
1630
1870
  hierarchy: tree,
1631
1871
  assets: assetPanel,
1632
1872
  passes: passPanel,
1873
+ perf: perfPanel,
1633
1874
  targets: targetPanel,
1634
1875
  textures: texturePanel,
1635
1876
  meshes: meshPanel,
@@ -1640,17 +1881,18 @@ class Inspector {
1640
1881
  shaders: shaderPanel,
1641
1882
  physics: physicsPanel
1642
1883
  };
1643
- this._hierarchyEl.append(tabs, filter, tree, cameraPanel, assetPanel, passPanel, targetPanel, texturePanel, meshPanel, materialPanel, scriptPanel, memoryPanel, shaderPanel, physicsPanel);
1884
+ this._hierarchyEl.append(tabs, filter, tree, cameraPanel, assetPanel, passPanel, perfPanel, targetPanel, texturePanel, meshPanel, materialPanel, scriptPanel, memoryPanel, shaderPanel, physicsPanel);
1644
1885
 
1645
1886
  const splitter = el('div', 'pci-splitter');
1646
1887
  const properties = el('div', 'pci-properties');
1647
1888
  body.append(this._hierarchyEl, splitter, properties);
1648
1889
 
1649
- this._gpuToggle.addEventListener('change', () => {
1650
- const profiler = this._app.graphicsDevice.gpuProfiler;
1651
- if (profiler) profiler.enabled = this._gpuToggle.checked;
1652
- this._saveSettings();
1653
- });
1890
+ this._gpuToggle.addEventListener('change', () => this._setGpuTimings(this._gpuToggle.checked));
1891
+ this._perfGpuToggle.addEventListener('change', () => this._setGpuTimings(this._perfGpuToggle.checked));
1892
+ if (!this._app.graphicsDevice.gpuProfiler) {
1893
+ this._perfGpuToggle.disabled = true;
1894
+ setTip(this._perfGpuToggle.parentElement, 'This device has no GPU profiler');
1895
+ }
1654
1896
  this._passPreviewToggle.addEventListener('change', () => this._saveSettings());
1655
1897
  this._debugFrameToggle.addEventListener('change', () => this._setDebugFrame(this._debugFrameToggle.checked));
1656
1898
  this._freezeToggle.addEventListener('change', () => {
@@ -1676,7 +1918,7 @@ class Inspector {
1676
1918
 
1677
1919
  this._makeDraggable(splitter, (e) => {
1678
1920
  const rect = body.getBoundingClientRect();
1679
- const height = Math.max(60, Math.min(rect.height - 60, e.clientY - rect.top));
1921
+ const height = Math.max(this._topMinHeight(), Math.min(rect.height - 60, e.clientY - rect.top));
1680
1922
  this._hierarchyEl.style.flexBasis = `${height}px`;
1681
1923
  });
1682
1924
 
@@ -1708,7 +1950,12 @@ class Inspector {
1708
1950
  for (const type of SWALLOWED_EVENTS) {
1709
1951
  host.addEventListener(type, (e) => {
1710
1952
  e.stopPropagation();
1711
- if (type === 'keydown' && !isTextTarget(e)) this._onKeyDown(/** @type {KeyboardEvent} */ (e));
1953
+ if (type === 'keydown' && !isTextTarget(e)) {
1954
+ // the Performance tab steps through frames only while the panel has focus, so
1955
+ // the arrow keys stay the app's otherwise
1956
+ const key = /** @type {KeyboardEvent} */ (e);
1957
+ if (!this._onPerfKey(key)) this._onKeyDown(key);
1958
+ }
1712
1959
  });
1713
1960
  }
1714
1961
 
@@ -1878,10 +2125,22 @@ class Inspector {
1878
2125
  }
1879
2126
  if (typeof stored.width === 'number') this._setWidth(stored.width);
1880
2127
  if (typeof stored.passPreview === 'boolean') this._passPreviewToggle.checked = stored.passPreview;
1881
- if (typeof stored.gpuTimings === 'boolean') {
1882
- this._gpuToggle.checked = stored.gpuTimings;
1883
- const profiler = this._app.graphicsDevice.gpuProfiler;
1884
- if (profiler) profiler.enabled = stored.gpuTimings;
2128
+ if (typeof stored.gpuTimings === 'boolean') this._setGpuTimings(stored.gpuTimings);
2129
+ if (Array.isArray(stored.perfCollapsed)) {
2130
+ this._perfCharts.collapsed = new Set(stored.perfCollapsed.filter(key => typeof key === 'string'));
2131
+ }
2132
+ if (Array.isArray(stored.perfHidden)) {
2133
+ this._perfCharts.hidden = new Set(stored.perfHidden.filter(key => typeof key === 'string'));
2134
+ }
2135
+ if (typeof stored.perfInspector === 'boolean') {
2136
+ this._perfInspectorToggle.checked = stored.perfInspector;
2137
+ this._perfCharts.showInspector = stored.perfInspector;
2138
+ }
2139
+ if (typeof stored.perfScripts === 'boolean') this._setScriptTiming(stored.perfScripts);
2140
+ if (Number.isInteger(stored.perfScriptRows) && stored.perfScriptRows > 0) this._perfCharts.scriptRows = stored.perfScriptRows;
2141
+ if (Number.isFinite(stored.perfGutter)) this._perfCharts.gutter = stored.perfGutter;
2142
+ if (Array.isArray(stored.perfPinned)) {
2143
+ this._perfCharts.pinned = new Set(stored.perfPinned.filter(name => typeof name === 'string'));
1885
2144
  }
1886
2145
  if (stored.targetPreview && typeof stored.targetPreview === 'object') {
1887
2146
  if (typeof stored.targetPreview.enabled === 'boolean') this._previewToggle.checked = stored.targetPreview.enabled;
@@ -1922,6 +2181,13 @@ class Inspector {
1922
2181
  tab: this._tab,
1923
2182
  width: this._width,
1924
2183
  gpuTimings: this._gpuToggle.checked,
2184
+ perfInspector: this._perfInspectorToggle.checked,
2185
+ perfScripts: this._perfScriptsToggle.checked,
2186
+ perfScriptRows: this._perfCharts.scriptRows,
2187
+ perfGutter: this._perfCharts.gutter,
2188
+ perfPinned: [...this._perfCharts.pinned],
2189
+ perfCollapsed: [...this._perfCharts.collapsed],
2190
+ perfHidden: [...this._perfCharts.hidden],
1925
2191
  passPreview: this._passPreviewToggle.checked,
1926
2192
  targetPreview: { enabled: this._previewToggle.checked, channels: this._previewChannels.value },
1927
2193
  texturePreview: { enabled: this._texturePreviewToggle.checked, channels: this._textureChannels.value },
@@ -2531,16 +2797,156 @@ class Inspector {
2531
2797
  return input;
2532
2798
  }
2533
2799
 
2800
+ /**
2801
+ * @returns {number} The least height of the part above the splitter. The Performance tab keeps
2802
+ * room for what does not shrink, its controls and its timeline, and a little of its charts,
2803
+ * which scroll; less would spill over the splitter.
2804
+ * @private
2805
+ */
2806
+ _topMinHeight() {
2807
+ if (this._tab !== 'perf') return MIN_TOP_HEIGHT;
2808
+ // the content as laid out, spilling or not, less what the charts take beyond their least
2809
+ const charts = this._perfCharts.chartsElement;
2810
+ return Math.max(MIN_TOP_HEIGHT, Math.ceil(this._hierarchyEl.scrollHeight - charts.offsetHeight + MIN_PERF_CHARTS_HEIGHT));
2811
+ }
2812
+
2813
+ /**
2814
+ * Raises the part above the splitter to the least height of the tab now shown, where it was
2815
+ * dragged lower on another tab.
2816
+ *
2817
+ * @private
2818
+ */
2819
+ _fitTop() {
2820
+ const basis = parseFloat(this._hierarchyEl.style.flexBasis);
2821
+ if (!(basis > 0)) return;
2822
+ const least = this._topMinHeight();
2823
+ if (basis < least) this._hierarchyEl.style.flexBasis = `${least}px`;
2824
+ }
2825
+
2826
+ /**
2827
+ * Turns the GPU profiler on or off, from either of the switches, which follow each other.
2828
+ *
2829
+ * @param {boolean} on - Whether to time the GPU.
2830
+ * @private
2831
+ */
2832
+ _setGpuTimings(on) {
2833
+ const profiler = this._app.graphicsDevice.gpuProfiler;
2834
+ if (profiler) profiler.enabled = on;
2835
+ this._gpuToggle.checked = on;
2836
+ this._perfGpuToggle.checked = on;
2837
+ this._saveSettings();
2838
+ if (this._tab === 'perf') this._refreshLists(false);
2839
+ }
2840
+
2841
+ /**
2842
+ * Turns the timing of scripts on or off, which takes effect right away while recording.
2843
+ *
2844
+ * @param {boolean} on - Whether to time each script type.
2845
+ * @private
2846
+ */
2847
+ _setScriptTiming(on) {
2848
+ on &&= this._perf.supports.scripts;
2849
+ this._perf.timeScripts = on;
2850
+ this._perfScriptsToggle.checked = on;
2851
+ this._perfCharts.invalidate();
2852
+ this._saveSettings();
2853
+ if (this._tab === 'perf') this._refreshLists(false);
2854
+ }
2855
+
2856
+ /**
2857
+ * Starts or stops recording frames for the Performance tab.
2858
+ *
2859
+ * @param {boolean} on - Whether to record.
2860
+ * @private
2861
+ */
2862
+ _setRecording(on) {
2863
+ if (on) this._perf.start();
2864
+ else this._perf.stop();
2865
+ this._perfCharts.invalidate();
2866
+ // the Record button shows it on whichever tab is open, as code can start a capture too
2867
+ this._updatePerfBar();
2868
+ this._refreshLists(false);
2869
+ }
2870
+
2871
+ /**
2872
+ * The frame shown or the frames selected on the Performance tab changed.
2873
+ *
2874
+ * @private
2875
+ */
2876
+ _onPerfChange() {
2877
+ if (this._tab !== 'perf') return;
2878
+ this._properties.refresh();
2879
+ this._updatePerfBar();
2880
+ this._updateStatus();
2881
+ }
2882
+
2883
+ /**
2884
+ * Brings the recording controls of the Performance tab and its note up to date.
2885
+ *
2886
+ * @private
2887
+ */
2888
+ _updatePerfBar() {
2889
+ const capture = this._perf;
2890
+ const recording = capture.recording;
2891
+ const record = this._perfRecordBtn;
2892
+ record.classList.toggle('pci-active', recording);
2893
+ record.setAttribute('aria-label', recording ? 'Stop' : 'Record');
2894
+ setTip(record, recording ? 'Stop recording, keeping the frames recorded' :
2895
+ 'Record every frame, adding to the capture, which keeps the last 1000');
2896
+ this._perfLastBtn.classList.toggle('pci-active', this._perfCharts.following);
2897
+ const profiler = this._app.graphicsDevice.gpuProfiler;
2898
+ this._perfGpuToggle.checked = !!profiler?.enabled;
2899
+
2900
+ const notes = [];
2901
+ if (!capture.detailed) notes.push('This engine build times the update and the render as a whole: the phases of the render and the breakdown of the draw calls need the profiler or debug engine.');
2902
+ // the frames recorded keep the late timings after recording stops
2903
+ if (profiler?.enabled && (recording || capture.count) && !capture.gpuExact) {
2904
+ notes.push('This engine does not say which frame GPU timings belong to, so they land a few frames late.');
2905
+ }
2906
+ Inspector._setNote(this._perfNote, notes.join(' '));
2907
+ }
2908
+
2909
+ /**
2910
+ * Steps through the frames of the Performance tab with the arrow keys, Shift taking ten at a
2911
+ * time; Home shows the first frame, End follows the newest and Escape unselects the frames
2912
+ * selected together.
2913
+ *
2914
+ * @param {KeyboardEvent} e - A key pressed while the panel has focus.
2915
+ * @returns {boolean} Whether the key was used.
2916
+ * @private
2917
+ */
2918
+ _onPerfKey(e) {
2919
+ if (this._tab !== 'perf' || this._debugFrame) return false;
2920
+ const charts = this._perfCharts;
2921
+ if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
2922
+ charts.step((e.key === 'ArrowLeft' ? -1 : 1) * (e.shiftKey ? 10 : 1));
2923
+ } else if (e.key === 'Home') {
2924
+ charts.pick(this._perf.first);
2925
+ } else if (e.key === 'End') {
2926
+ charts.follow();
2927
+ } else if (e.key === 'Escape' && charts.range) {
2928
+ charts.clearRange();
2929
+ } else {
2930
+ return false;
2931
+ }
2932
+ e.preventDefault();
2933
+ return true;
2934
+ }
2935
+
2534
2936
  /**
2535
2937
  * Switches the list tab and points the property view at that tab's selection.
2536
2938
  *
2537
- * @param {'hierarchy'|'cameras'|'assets'|'passes'|'targets'|'textures'|'meshes'|'materials'|'scripts'|'memory'|'shaders'|'physics'} tab - The tab.
2939
+ * @param {'hierarchy'|'cameras'|'assets'|'passes'|'perf'|'targets'|'textures'|'meshes'|'materials'|'scripts'|'memory'|'shaders'|'physics'} tab - The tab.
2538
2940
  * @private
2539
2941
  */
2540
2942
  _setTab(tab) {
2541
2943
  this._tab = tab;
2542
2944
  this._menu?.hide();
2543
2945
  this._filterBy.style.display = tab === 'hierarchy' ? '' : 'none';
2946
+ // the Performance tab has no list to filter
2947
+ this._filterEl.style.display = tab === 'perf' ? 'none' : '';
2948
+ this._hierarchyEl.classList.toggle('pci-tall', tab === 'perf');
2949
+ if (tab === 'perf') this._perfCharts.invalidate();
2544
2950
  this._updateFilterHint();
2545
2951
  for (const [id, button] of Object.entries(this._tabButtons)) {
2546
2952
  button.classList.toggle('pci-active', id === tab);
@@ -2548,6 +2954,8 @@ class Inspector {
2548
2954
  for (const [id, panel] of Object.entries(this._panels)) {
2549
2955
  panel.style.display = id === tab ? '' : 'none';
2550
2956
  }
2957
+ // measured with the tab's panel shown
2958
+ if (tab === 'perf') this._fitTop();
2551
2959
  this._refreshLists(false);
2552
2960
  if (tab === 'hierarchy') {
2553
2961
  this._properties.setSubject(this._hierarchy.selected, buildNodeModel);
@@ -2641,6 +3049,12 @@ class Inspector {
2641
3049
  if (shader !== this._properties.subject) {
2642
3050
  this._properties.setSubject(shader, this._shaderModel, this._shaderList.selectedKey);
2643
3051
  }
3052
+ } else if (this._tab === 'perf') {
3053
+ // the charts are the subject, so the view follows the frame they show
3054
+ if (this._properties.subject !== this._perfCharts) {
3055
+ this._properties.setSubject(this._perfCharts, this._perfModel, 'perf');
3056
+ }
3057
+ this._updatePerfBar();
2644
3058
  } else {
2645
3059
  if ((capture && !this._frozen) || !this._frame) {
2646
3060
  this._frame = captureFrameGraph(this._app);
@@ -2724,7 +3138,7 @@ class Inspector {
2724
3138
  */
2725
3139
  _onContextMenu = (e) => {
2726
3140
  if (isTextTarget(e)) return;
2727
- const copy = this._copyTargetAt(/** @type {Node} */ (e.composedPath()[0]));
3141
+ const copy = this._copyTargetAt(/** @type {Node} */ (e.composedPath()[0]), e);
2728
3142
  if (!copy) return;
2729
3143
  e.preventDefault();
2730
3144
  this._menu?.show(e.clientX, e.clientY, copy.title, this._copyItems(copy));
@@ -2738,14 +3152,19 @@ class Inspector {
2738
3152
  * everything it lists is copied.
2739
3153
  *
2740
3154
  * @param {Node} target - What was right-clicked.
3155
+ * @param {MouseEvent} [e] - The click, for where it was on the charts of the Performance tab.
2741
3156
  * @returns {CopyTarget|null} What to copy, or null for a part of the panel nothing is copied
2742
3157
  * from, such as the toolbar.
2743
3158
  * @private
2744
3159
  */
2745
- _copyTargetAt(target) {
3160
+ _copyTargetAt(target, e) {
2746
3161
  const property = this._properties.copyTargetAt(target);
2747
3162
  if (property) return property;
2748
3163
 
3164
+ // the charts and the timeline of the Performance tab copy what is under the pointer
3165
+ const perf = this._tab === 'perf' && e ? this._perfCharts.copyAt(target, e) : null;
3166
+ if (perf) return this._perfCopy(perf);
3167
+
2749
3168
  const node = this._hierarchy.nodeAt(target);
2750
3169
  if (node) {
2751
3170
  this._hierarchy.select(node);
@@ -2776,6 +3195,7 @@ class Inspector {
2776
3195
  */
2777
3196
  _tabCopyTarget(tab) {
2778
3197
  const title = this._tabButtons[tab].textContent ?? tab;
3198
+ if (tab === 'perf') return this._perf.count ? this._perfCopy({ kind: 'capture' }) : null;
2779
3199
  if (tab === 'hierarchy') {
2780
3200
  const root = this._app.root;
2781
3201
  return { title, copy: options => copySubject(root, buildNodeModel(root), options) };
@@ -2791,6 +3211,16 @@ class Inspector {
2791
3211
  * @private
2792
3212
  */
2793
3213
  _copyItems(copy) {
3214
+ // figures have no links to follow, so they are copied as they are, or as CSV
3215
+ if (copy.plain) {
3216
+ /** @type {MenuItem[]} */
3217
+ const items = [{ text: () => 'Copy as JSON', title: 'Copy it with numbers at full precision', run: () => this._copy(copy, 0) }];
3218
+ const csv = copy.csv;
3219
+ if (csv) {
3220
+ items.push({ text: () => 'Copy as CSV', title: 'Copy it a row per frame, to paste into a spreadsheet', run: () => this._copyText(csv, 'CSV') });
3221
+ }
3222
+ return items;
3223
+ }
2794
3224
  const levels = n => `${n} level${n === 1 ? '' : 's'}`;
2795
3225
  return [{
2796
3226
  text: () => 'Copy as JSON',
@@ -2855,6 +3285,33 @@ class Inspector {
2855
3285
  const size = formatBytes(text.length);
2856
3286
  const note = `Copied ${result.objects ? `${result.objects} object${result.objects === 1 ? '' : 's'}, ` : ''}${size}` +
2857
3287
  `${result.truncated ? ', stopped at the object limit' : ''}`;
3288
+ this._writeClipboard(text, note);
3289
+ }
3290
+
3291
+ /**
3292
+ * Copies text made on demand, such as CSV.
3293
+ *
3294
+ * @param {() => string} make - Makes the text.
3295
+ * @param {string} what - What it is, for the note saying it was copied.
3296
+ * @private
3297
+ */
3298
+ _copyText(make, what) {
3299
+ let text;
3300
+ try {
3301
+ text = make();
3302
+ } catch (e) {
3303
+ this._menu?.note(`Could not copy: ${e?.message ?? e}`);
3304
+ return;
3305
+ }
3306
+ this._writeClipboard(text, `Copied ${what}, ${formatBytes(text.length)}`);
3307
+ }
3308
+
3309
+ /**
3310
+ * @param {string} text - The text.
3311
+ * @param {string} note - What the menu says once it is copied.
3312
+ * @private
3313
+ */
3314
+ _writeClipboard(text, note) {
2858
3315
  // the clipboard of the window the panel is in, which is the one with focus once popped out
2859
3316
  const clipboard = (this._panel.ownerDocument.defaultView ?? window).navigator.clipboard;
2860
3317
  if (!clipboard) {
@@ -2867,6 +3324,48 @@ class Inspector {
2867
3324
  );
2868
3325
  }
2869
3326
 
3327
+ /**
3328
+ * What a right click on the Performance tab copies, as the charts tell it: the capture, a
3329
+ * series, a frame, the frames selected together, or the timeline. A capture and a series
3330
+ * cover the frames selected together, or every frame kept.
3331
+ *
3332
+ * @param {{ kind: string, key?: string, seq?: number }} what - What to copy.
3333
+ * @returns {CopyTarget|null} The copy, or null for nothing.
3334
+ * @private
3335
+ */
3336
+ _perfCopy(what) {
3337
+ const capture = this._perf;
3338
+ const charts = this._perfCharts;
3339
+ const { from, to } = charts.copyRange;
3340
+ const frames = charts.range ? `, ${capture.rangeLabel(from, to).toLowerCase()}` : '';
3341
+ const figures = json => ({ json, objects: 0, truncated: false });
3342
+ 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
+ }
3348
+ case 'series': {
3349
+ const name = PERF_SERIES_NAMES[what.key] ?? what.key;
3350
+ return {
3351
+ title: `${name}${frames}`,
3352
+ plain: true,
3353
+ copy: () => figures({ series: name, range: { from: capture.frameNumber(from), to: capture.frameNumber(to), frames: to - from + 1 }, rows: seriesRows(capture, what.key, from, to) }),
3354
+ csv: () => toCsv(seriesRows(capture, what.key, from, to))
3355
+ };
3356
+ }
3357
+ case 'frame':
3358
+ return { title: capture.label(what.seq), plain: true, copy: () => figures(frameJson(capture, what.seq)) };
3359
+ case 'range':
3360
+ return { title: capture.rangeLabel(from, to), plain: true, copy: () => figures(rangeJson(capture, from, to)) };
3361
+ case 'timeline': {
3362
+ const json = charts.timelineJson();
3363
+ return json ? { title: `${json.title}, timeline`, plain: true, copy: () => figures(json) } : null;
3364
+ }
3365
+ }
3366
+ return null;
3367
+ }
3368
+
2870
3369
  /**
2871
3370
  * @returns {Set<object>} The app's own objects, which a copy never follows, as through them it
2872
3371
  * would reach everything else.
@@ -2910,6 +3409,22 @@ class Inspector {
2910
3409
  return null;
2911
3410
  }
2912
3411
 
3412
+ /**
3413
+ * Shows a GPU pass of the Performance tab on the Frame graph tab: the pass of the frame graph
3414
+ * with its name it was matched to, in the frame graph as it is now, unless that is frozen.
3415
+ *
3416
+ * @param {{ name: string, occurrence: number }} pass - The pass, by its profiler name and which
3417
+ * of the passes with that name it is.
3418
+ * @private
3419
+ */
3420
+ _showPass({ name, occurrence }) {
3421
+ if (!this._frozen) this._frame = captureFrameGraph(this._app);
3422
+ this._setTab('passes');
3423
+ const entries = this._frame?.entries.filter(entry => profilerName(entry.pass) === name) ?? [];
3424
+ const entry = entries[occurrence] ?? entries[0];
3425
+ if (entry) this._passList.selectItem(entry.pass);
3426
+ }
3427
+
2913
3428
  /**
2914
3429
  * Reveals a linked object in the tab that lists it: nodes in the hierarchy, passes in the frame
2915
3430
  * graph, render targets in their list.
@@ -3100,6 +3615,22 @@ class Inspector {
3100
3615
  item ? passDisplayName(item) : '';
3101
3616
  break;
3102
3617
  }
3618
+ case 'perf': {
3619
+ const capture = this._perf;
3620
+ const charts = this._perfCharts;
3621
+ counts = `${capture.recording ? 'Recording' : 'Stopped'} · ${capture.count} frames`;
3622
+ if (capture.count) {
3623
+ const { median } = captureNorms(capture);
3624
+ let hitches = 0;
3625
+ for (let seq = capture.first; seq < capture.end; seq++) {
3626
+ if (isHitch(capture, seq, median)) hitches++;
3627
+ }
3628
+ counts += ` · median ${formatMs(median)} · ${hitches} hitch${hitches === 1 ? '' : 'es'}`;
3629
+ selected = charts.range ? capture.rangeLabel(charts.range.from, charts.range.to) :
3630
+ `${capture.label(charts.shown)}${charts.following ? ', the newest' : ''}`;
3631
+ }
3632
+ break;
3633
+ }
3103
3634
  case 'targets': {
3104
3635
  counts = `${this._targetList.rowCount} render targets · ${this._frame?.usage.size ?? 0} used this frame`;
3105
3636
  const rt = this._targetList.selected;