@playcanvas/inspector 0.2.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.
Files changed (49) hide show
  1. package/README.md +147 -5
  2. package/package.json +1 -1
  3. package/src/asset-view.js +24 -17
  4. package/src/camera-view.js +5 -3
  5. package/src/context-menu.js +231 -0
  6. package/src/copy-json.js +692 -0
  7. package/src/describe.js +20 -1
  8. package/src/entity-inspector-script.js +10 -0
  9. package/src/frame-graph-view.js +41 -9
  10. package/src/hierarchy-view.js +29 -3
  11. package/src/inspector.js +958 -80
  12. package/src/list-view.js +118 -12
  13. package/src/material-view.js +7 -6
  14. package/src/memory-view.js +224 -66
  15. package/src/mesh-view.js +6 -5
  16. package/src/model.js +24 -2
  17. package/src/node-model.js +81 -11
  18. package/src/perf-capture.js +2034 -0
  19. package/src/perf-chart.js +3989 -0
  20. package/src/perf-copy.js +367 -0
  21. package/src/perf-view.js +1224 -0
  22. package/src/property-view.js +162 -5
  23. package/src/render-target-view.js +3 -3
  24. package/src/script-view.js +21 -12
  25. package/src/styles.js +374 -2
  26. package/src/texture-view.js +4 -4
  27. package/src/transform-tool.js +185 -0
  28. package/types/asset-view.d.ts +3 -1
  29. package/types/camera-view.d.ts +4 -0
  30. package/types/context-menu.d.ts +90 -0
  31. package/types/copy-json.d.ts +69 -0
  32. package/types/describe.d.ts +1 -1
  33. package/types/entity-inspector-script.d.ts +8 -0
  34. package/types/frame-graph-view.d.ts +7 -0
  35. package/types/hierarchy-view.d.ts +13 -0
  36. package/types/inspector.d.ts +339 -25
  37. package/types/list-view.d.ts +44 -3
  38. package/types/material-view.d.ts +3 -1
  39. package/types/memory-view.d.ts +24 -25
  40. package/types/mesh-view.d.ts +3 -1
  41. package/types/model.d.ts +16 -1
  42. package/types/node-model.d.ts +17 -1
  43. package/types/perf-capture.d.ts +871 -0
  44. package/types/perf-chart.d.ts +1407 -0
  45. package/types/perf-copy.d.ts +61 -0
  46. package/types/perf-view.d.ts +231 -0
  47. package/types/property-view.d.ts +41 -0
  48. package/types/script-view.d.ts +3 -1
  49. package/types/transform-tool.d.ts +92 -0
package/src/inspector.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import {
2
- Asset, Color, Entity, FramePass, GraphNode, LAYERID_UI, Material, Mesh, RenderPassForward, RenderTarget, Shader, Texture
2
+ Asset, Color, Component, Entity, FramePass, GraphNode, LAYERID_UI, Material, Mesh, MeshInstance, RenderPassForward, RenderTarget, Shader, Texture
3
3
  } from 'playcanvas';
4
4
 
5
5
  import { TextureRenderer } from './renderers/texture-renderer.js';
@@ -8,8 +8,10 @@ import { WireRenderer } from './renderers/wire-renderer.js';
8
8
  import { pushResourceUsage } from './asset-usage.js';
9
9
  import { ASSET_SORTS, assetRows, buildAssetModel, collectAssets } from './asset-view.js';
10
10
  import { buildCameraModel, cameraRows, collectCameras } from './camera-view.js';
11
- import { INSTANCES_PER_PAGE, LayerStepSelection, buildPassModel, buildStepModel, captureFrameGraph, passRows } from './frame-graph-view.js';
12
- import { BUFFER_KINDS, bufferBytes, bufferKind, bufferOwners, bufferRows, buildBufferModel, collectBuffers, idOf, memorySummary } from './memory-view.js';
11
+ import { ContextMenu } from './context-menu.js';
12
+ import { copyGroup, copyList, copyListRow, copySubject, stringifyCopy } from './copy-json.js';
13
+ 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';
13
15
  import { HierarchyView, filterSuggestions } from './hierarchy-view.js';
14
16
  import { ListView } from './list-view.js';
15
17
  import {
@@ -18,7 +20,11 @@ import {
18
20
  } from './material-view.js';
19
21
  import { buildMeshModel, meshBytes, meshListRows, meshNote, surveyMeshes } from './mesh-view.js';
20
22
  import { formatBytes, formatName, passDisplayName } from './model.js';
21
- import { buildNodeModel } from './node-model.js';
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';
22
28
  import { AmmoDebugDraw, DEBUG_DRAW } from './physics-debug.js';
23
29
  import { bodyRows, drawCollisionShape, drawJoint, jointRows, physicsStats } from './physics-view.js';
24
30
  import { PropertyView } from './property-view.js';
@@ -29,12 +35,16 @@ import { styles } from './styles.js';
29
35
  import { installTooltip, setTip } from './tooltip.js';
30
36
  import { CameraFly, CameraOrbit, CanvasCapture, RENDER_MODES, ViewportPicker, WireframeMode, isScreenCamera, screenCameraAt } from './viewport-tools.js';
31
37
  import { buildTextureModel, collectTextures, textureRows } from './texture-view.js';
38
+ import { TRANSFORM_POINTER_EVENTS, TransformTool } from './transform-tool.js';
32
39
 
33
40
  /** @import { AppBase } from 'playcanvas' */
34
41
  /** @import { GraphicsDevice } from 'playcanvas' */
35
42
  /** @import { FrameSnapshot, PassModelContext } from './frame-graph-view.js' */
36
- /** @import { MeshInstance } from 'playcanvas' */
37
- /** @import { PropertySection } from './model.js' */
43
+ /** @import { PropertyRow, PropertySection } from './model.js' */
44
+ /** @import { MenuItem } from './context-menu.js' */
45
+ /** @import { CopyOptions } from './copy-json.js' */
46
+ /** @import { CopyTarget } from './property-view.js' */
47
+ /** @import { TransformMode } from './transform-tool.js' */
38
48
 
39
49
  /**
40
50
  * Options for {@link Inspector}.
@@ -53,13 +63,19 @@ import { buildTextureModel, collectTextures, textureRows } from './texture-view.
53
63
  * @property {GraphNode|null} [lockedNode] - A node whose enabled checkbox, and those of its
54
64
  * ancestors, are withheld. A script hosting the inspector passes its own entity so the panel
55
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}.
56
69
  * @property {(visible: boolean) => void} [onVisibleChange] - Called with the new visibility
57
70
  * whenever the panel is shown or hidden, whether through {@link Inspector#visible}, the toggle key
58
71
  * or the panel's own close button.
59
72
  * @property {string|null} [storageKey] - The local storage key the panel's settings are kept
60
73
  * under, so they survive a reload or a restart of the app: the physics drawing switch and options,
61
- * the bodies excluded from it (by entity path), the active tab, the panel width and the GPU
62
- * 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
63
79
  * 'pc-inspector'; null keeps nothing.
64
80
  */
65
81
 
@@ -98,24 +114,52 @@ const PHYSICS_FLAGS = {
98
114
  const LIST_INTERVAL = 0.5;
99
115
  const PROPERTY_INTERVAL = 0.1;
100
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
+
101
140
  // the tooltips of the tabs
102
141
  const TAB_TIPS = {
103
142
  hierarchy: 'The entity tree, and the components and properties of the selected entity',
104
143
  cameras: 'The cameras of the scene in render order, with where they draw, their render mode and a way to fly each',
105
144
  assets: 'The assets of the registry, and what uses each',
106
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',
107
147
  targets: 'The render targets on the device, with a live preview of their textures',
108
148
  textures: 'The textures on the device, largest first, with a live preview',
109
149
  meshes: 'The meshes of the app, found through the components, layers and assets using them, largest first',
110
150
  materials: 'The materials of the app, found through the mesh instances and assets using them, most used first',
111
151
  scripts: 'The script classes of the app, registered or found on its entities, with the entities using each and its source',
112
- memory: 'The vertex, index, uniform and storage buffers on the device, and what uses each',
152
+ memory: 'Video memory by kind of resource, and every buffer on the device with what uses it',
113
153
  shaders: 'The compiled shaders, with their sources',
114
154
  physics: 'The rigid bodies and joints of the physics world, and its debug drawing'
115
155
  };
116
156
 
117
157
  const CHANNELS_TIP = 'Which channels of the texture to show. A single channel shows as grayscale';
118
158
 
159
+ // how many links the deep copy follows until changed, and at most
160
+ const COPY_DEPTH = 3;
161
+ const MAX_COPY_DEPTH = 20;
162
+
119
163
  // events the panel swallows so that they never reach the input handlers of the app underneath
120
164
  const SWALLOWED_EVENTS = ['keydown', 'keyup', 'keypress', 'pointerdown', 'mousedown', 'wheel', 'touchstart', 'contextmenu'];
121
165
 
@@ -170,7 +214,7 @@ function isTextTarget(e) {
170
214
  }
171
215
 
172
216
  /**
173
- * An in-page inspector for a running application. It docks a panel over the canvas with four
217
+ * An in-page inspector for a running application. It docks a panel over the canvas with thirteen
174
218
  * tabs above a live property view of whatever is selected:
175
219
  *
176
220
  * - Hierarchy: the entity tree. The property view shows the node's transform, every component it
@@ -179,9 +223,18 @@ function isTextTarget(e) {
179
223
  * - Cameras: every camera in render order, with its target, viewport, layers and render mode. The
180
224
  * render mode of a camera can be switched to a debug view of the material inputs, the whole scene
181
225
  * drawn in wireframe, and any camera flown.
226
+ * - Assets: every asset in the registry with its file, load state and the components using it.
227
+ * Asset references on a component link here, and a texture names the asset it came from.
182
228
  * - Frame graph: the render passes of the last frame in execution order, as the render pass trace
183
229
  * prints them, with the layer steps of forward passes, the light of shadow passes and optional
184
- * GPU timings. Render target cells link to the next tab.
230
+ * GPU timings. Render target cells link to the next tab. With the debug engine, the debug frame
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.
185
238
  * - Render targets: every render target on the device including the backbuffer, with its
186
239
  * attachments and the passes that rendered into it this frame, linking back to the frame graph.
187
240
  * The selected target's attachment can be previewed live in a corner of the viewport.
@@ -196,20 +249,21 @@ function isTextTarget(e) {
196
249
  * - Scripts: every script class the script registry holds or an entity uses, with the entities using
197
250
  * it, its declared attributes and its source as the browser keeps it. The script sections of an
198
251
  * entity link here.
199
- * - Memory: video memory by kind of resource, and every buffer on the device, largest first, named
200
- * after the mesh, material or asset it was found to belong to. Buffer values elsewhere link here.
252
+ * - Memory: video memory by kind of resource, each kind a group headed by its count and size that
253
+ * opens to list its buffers largest first, named after the mesh, material or asset each was found
254
+ * to belong to. Buffer values elsewhere link here.
201
255
  * - Shaders: every shader on the device with its language, state and vertex attributes. The
202
256
  * compiled variants listed on a material link here.
203
- * - Assets: every asset in the registry with its file, load state and the components using it.
204
- * Asset references on a component link here, and a texture names the asset it came from.
205
257
  * - Physics: the rigid bodies and joints of the scene, with the physics world drawn over the scene
206
258
  * through the engine's debug drawer when Ammo is loaded.
207
259
  *
208
260
  * The app can be paused and stepped a frame at a time, and the panel can be popped out into its own
209
- * window to leave the canvas unobscured.
261
+ * window to leave the canvas unobscured. In the view, an entity can be picked to select it, and the
262
+ * camera flown, or orbited around the selected entity, without moving the app's own camera.
210
263
  *
211
- * The view is read-only, with one exception: the checkbox on each hierarchy row flips the node's
212
- * enabled flag.
264
+ * The inspector is read-only, apart from the checkbox on each hierarchy row, which flips the node's
265
+ * enabled flag, pausing and stepping the app, and view-only overrides: render modes, wireframe and
266
+ * a flown or orbited camera, which it removes when it closes.
213
267
  *
214
268
  * ```javascript
215
269
  * const inspector = new Inspector(app, { dock: 'left' });
@@ -405,11 +459,104 @@ class Inspector {
405
459
  _nextPropertyRefresh = 0;
406
460
 
407
461
  /**
408
- * @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'}
409
463
  * @private
410
464
  */
411
465
  _tab = 'hierarchy';
412
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
+
413
560
  /**
414
561
  * @type {FrameSnapshot|null}
415
562
  * @private
@@ -452,6 +599,38 @@ class Inspector {
452
599
  */
453
600
  _bodyList;
454
601
 
602
+ /**
603
+ * The gizmo that moves, rotates or scales the selected entity, while one of its buttons is on.
604
+ *
605
+ * @type {TransformTool|null}
606
+ * @private
607
+ */
608
+ _transformTool = null;
609
+
610
+ /**
611
+ * The buttons of the gizmos, by what each does.
612
+ *
613
+ * @type {Record<TransformMode, HTMLButtonElement>}
614
+ * @private
615
+ */
616
+ _transformBtns;
617
+
618
+ /**
619
+ * The menu opened with a right click, which copies what it was opened on.
620
+ *
621
+ * @type {ContextMenu|null}
622
+ * @private
623
+ */
624
+ _menu = null;
625
+
626
+ /**
627
+ * How many links the menu's deep copy follows.
628
+ *
629
+ * @type {number}
630
+ * @private
631
+ */
632
+ _copyDepth = COPY_DEPTH;
633
+
455
634
  /**
456
635
  * Draws the selected render target's texture over the canvas, straight from the GPU.
457
636
  *
@@ -721,18 +900,6 @@ class Inspector {
721
900
  */
722
901
  _instancePages = new Map();
723
902
 
724
- /**
725
- * @type {HTMLSelectElement}
726
- * @private
727
- */
728
- _bufferKind;
729
-
730
- /**
731
- * @type {HTMLElement}
732
- * @private
733
- */
734
- _memoryNote;
735
-
736
903
  /**
737
904
  * Model builder for the property view when a buffer is selected.
738
905
  *
@@ -769,7 +936,11 @@ class Inspector {
769
936
  */
770
937
  _cameraModel = camera => buildCameraModel(camera, {
771
938
  app: this._app,
772
- cameraActions: { fly: target => this._startFly(target), flying: this._fly?.camera ?? null }
939
+ cameraActions: {
940
+ fly: target => this._startFly(target),
941
+ flying: this._fly?.camera ?? null,
942
+ unavailable: this._transformTool ? 'Turn the gizmo off to fly a camera' : null
943
+ }
773
944
  });
774
945
 
775
946
  /**
@@ -991,6 +1162,7 @@ class Inspector {
991
1162
 
992
1163
  this._wire = new WireRenderer(app);
993
1164
  this._textures = new TextureRenderer(app);
1165
+ this._perf = new PerfCapture(app);
994
1166
  this._buildDom();
995
1167
  this._hierarchy.setRoot(app.root);
996
1168
  this._gpuWasEnabled = !!app.graphicsDevice.gpuProfiler?.enabled;
@@ -1004,9 +1176,13 @@ class Inspector {
1004
1176
  this._applyVisibility();
1005
1177
  this._applyPauseState();
1006
1178
  this._refresh();
1179
+ if (options.record) this._setRecording(true);
1007
1180
  this._restoring = false;
1008
1181
 
1009
1182
  window.addEventListener('keydown', this._onKeyDown);
1183
+ // ahead of every listener of the app and of the panel's own modes added later, so a gizmo
1184
+ // being dragged keeps the pointer to itself
1185
+ for (const type of TRANSFORM_POINTER_EVENTS) window.addEventListener(type, this._onTransformPointer, { capture: true, passive: false });
1010
1186
  // the app fires 'update' after every component system has updated, so the physics step of
1011
1187
  // the frame is done by the time the world is drawn
1012
1188
  app.on('update', this._onUpdate, this);
@@ -1025,12 +1201,15 @@ class Inspector {
1025
1201
  app.off('update', this._onUpdate, this);
1026
1202
  app.off('destroy', this.destroy, this);
1027
1203
  window.removeEventListener('keydown', this._onKeyDown);
1204
+ for (const type of TRANSFORM_POINTER_EVENTS) window.removeEventListener(type, this._onTransformPointer, { capture: true });
1028
1205
  this._setDebugFrame(false);
1029
1206
  this._endViewportModes();
1030
1207
  this._picker?.destroy();
1031
1208
  this._picker = null;
1032
1209
 
1033
1210
  this.paused = false;
1211
+ this._perf.destroy();
1212
+ this._perfCharts.destroy();
1034
1213
  const profiler = app.graphicsDevice?.gpuProfiler;
1035
1214
  if (profiler) profiler.enabled = this._gpuWasEnabled;
1036
1215
  this._pruneHiddenBodies();
@@ -1039,6 +1218,8 @@ class Inspector {
1039
1218
  this._hiddenBodies.clear();
1040
1219
 
1041
1220
  if (this._popup) this._dockBack();
1221
+ this._menu?.destroy();
1222
+ this._menu = null;
1042
1223
  this._textures.destroy();
1043
1224
  this._host?.remove();
1044
1225
  this._host = null;
@@ -1098,6 +1279,27 @@ class Inspector {
1098
1279
  return this._paused;
1099
1280
  }
1100
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
+
1101
1303
  /**
1102
1304
  * Whether the physics world is drawn over the scene while the panel is shown: the Draw checkbox
1103
1305
  * of the Physics tab. Hiding the panel suspends the drawing; showing it again resumes it.
@@ -1183,6 +1385,7 @@ class Inspector {
1183
1385
  this._popup.focus();
1184
1386
  return;
1185
1387
  }
1388
+ this._menu?.hide();
1186
1389
 
1187
1390
  const height = Math.max(480, Math.round(window.innerHeight * 0.9));
1188
1391
  const popup = window.open('', 'pc-inspector', `popup=yes,width=${this._width},height=${height}`);
@@ -1216,6 +1419,7 @@ class Inspector {
1216
1419
  const popup = this._popup;
1217
1420
  if (!popup) return;
1218
1421
  this._popup = null;
1422
+ this._menu?.hide();
1219
1423
 
1220
1424
  popup.removeEventListener('pagehide', this._onPopupHide);
1221
1425
  popup.removeEventListener('keydown', this._onKeyDown);
@@ -1226,6 +1430,7 @@ class Inspector {
1226
1430
  // the document that held the panel is gone, so the panel is too: build it anew
1227
1431
  const selected = this._selected;
1228
1432
  this._host.remove?.();
1433
+ this._perfCharts.destroy();
1229
1434
  this._buildDom();
1230
1435
  this._hierarchy.setRoot(this._app.root);
1231
1436
  if (selected) this._hierarchy.select(selected);
@@ -1238,10 +1443,23 @@ class Inspector {
1238
1443
  }
1239
1444
 
1240
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
+ *
1241
1449
  * @param {number} dt - The frame delta, scaled by the app time scale.
1242
1450
  * @private
1243
1451
  */
1244
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) {
1245
1463
  this._drawPhysics();
1246
1464
 
1247
1465
  // the user closed the pop-out window: bring the panel home
@@ -1251,7 +1469,12 @@ class Inspector {
1251
1469
 
1252
1470
  // wall clock, as the frame delta is zero while paused
1253
1471
  const now = performance.now();
1254
- 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) {
1255
1478
  this._nextListRefresh = now + LIST_INTERVAL * 1000;
1256
1479
  this._refreshLists(true);
1257
1480
  // mesh instances the app added since are drawn in wireframe too
@@ -1263,8 +1486,8 @@ class Inspector {
1263
1486
  this._drawHighlight(this._cameraList.selected.entity);
1264
1487
  }
1265
1488
  this._updateModeStatus();
1266
- if (now >= this._nextPropertyRefresh) {
1267
- 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;
1268
1491
  this._properties.refresh();
1269
1492
  }
1270
1493
 
@@ -1346,6 +1569,19 @@ class Inspector {
1346
1569
  setTip(this._pickBtn, 'Pick an entity in the view: hover to see it outlined, click to select it. Esc stops');
1347
1570
  setTip(this._flyBtn, 'Fly the camera of the view with the mouse and WASD, without moving the app\'s own camera. Esc stops');
1348
1571
  setTip(this._orbitBtn, 'Orbit the camera of the view around the selected entity: drag to orbit, right-drag to pan, the wheel to zoom, without moving the app\'s own camera. Esc stops');
1572
+ this._transformBtns = {
1573
+ translate: iconButton('translate', 'Move'),
1574
+ rotate: iconButton('rotate', 'Rotate'),
1575
+ scale: iconButton('scale', 'Scale')
1576
+ };
1577
+ const transformTips = { translate: 'Move', rotate: 'Rotate', scale: 'Scale' };
1578
+ for (const [mode, button] of Object.entries(this._transformBtns)) {
1579
+ setTip(button, TransformTool.supported ?
1580
+ `${transformTips[mode]} the selected entity with a gizmo in the view: drag its handles. Away from them the app has the view as usual; Pick, Fly and Orbit are off meanwhile. Click again or press Esc to stop` :
1581
+ 'The gizmos of this engine cannot be driven by the inspector');
1582
+ button.disabled = !TransformTool.supported;
1583
+ button.addEventListener('click', () => this._setTransformMode(this._transformTool?.mode === mode ? null : /** @type {TransformMode} */ (mode)));
1584
+ }
1349
1585
  this._popBtn = iconButton('popout', 'Pop out');
1350
1586
  const closeBtn = iconButton('close', 'Hide');
1351
1587
  const toggleLabel = Inspector._keyLabel(this._toggleKey);
@@ -1353,7 +1589,8 @@ class Inspector {
1353
1589
  toolbar.append(
1354
1590
  title,
1355
1591
  this._pauseBtn, this._stepBtn, el('span', 'pci-sep'),
1356
- this._pickBtn, this._flyBtn, this._orbitBtn,
1592
+ this._pickBtn, this._flyBtn, this._orbitBtn, el('span', 'pci-sep'),
1593
+ this._transformBtns.translate, this._transformBtns.rotate, this._transformBtns.scale,
1357
1594
  el('span', 'pci-spacer'),
1358
1595
  this._popBtn, closeBtn
1359
1596
  );
@@ -1380,7 +1617,7 @@ class Inspector {
1380
1617
  const tabs = el('div', 'pci-tabs');
1381
1618
  this._tabButtons = {};
1382
1619
  const tabList = [
1383
- ['hierarchy', 'Hierarchy'], ['cameras', 'Cameras'], ['assets', 'Assets'], ['passes', 'Frame graph'],
1620
+ ['hierarchy', 'Hierarchy'], ['cameras', 'Cameras'], ['assets', 'Assets'], ['passes', 'Frame graph'], ['perf', 'Performance'],
1384
1621
  ['targets', 'Render targets'], ['textures', 'Textures'], ['meshes', 'Meshes'], ['materials', 'Materials'], ['scripts', 'Scripts'], ['memory', 'Memory'],
1385
1622
  ['shaders', 'Shaders'], ['physics', 'Physics']
1386
1623
  ];
@@ -1393,6 +1630,7 @@ class Inspector {
1393
1630
  }
1394
1631
 
1395
1632
  const filter = el('div', 'pci-filter');
1633
+ this._filterEl = filter;
1396
1634
  // what the hierarchy filter matches, shown on that tab only: the lists match names
1397
1635
  this._filterBy = /** @type {HTMLSelectElement} */ (document.createElement('select'));
1398
1636
  this._filterBy.className = 'pci-select';
@@ -1430,6 +1668,68 @@ class Inspector {
1430
1668
  const passList = el('div', 'pci-list');
1431
1669
  passPanel.append(passBar, this._passNote, passList);
1432
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
+
1433
1733
  // render targets: a live preview of the selected target, drawn over the canvas
1434
1734
  const targetPanel = el('div', 'pci-listpanel');
1435
1735
  const targetBar = el('div', 'pci-subbar');
@@ -1507,21 +1807,17 @@ class Inspector {
1507
1807
  const scriptList = el('div', 'pci-list');
1508
1808
  scriptPanel.append(scriptList);
1509
1809
 
1510
- // memory: the totals over the buffers, which can be narrowed to one kind
1810
+ // memory: a group per kind of resource, each opening to its buffers
1511
1811
  const memoryPanel = el('div', 'pci-listpanel');
1512
- const memoryBar = el('div', 'pci-subbar');
1513
- this._bufferKind = this._makeSelect(memoryBar, 'Show', BUFFER_KINDS, 'List and total only the buffers of this kind');
1514
- this._memoryNote = el('div', 'pci-note pci-note-info');
1515
- this._memoryNote.style.whiteSpace = 'pre-line';
1516
1812
  const bufferList = el('div', 'pci-list');
1517
- memoryPanel.append(memoryBar, this._memoryNote, bufferList);
1813
+ memoryPanel.append(bufferList);
1518
1814
 
1519
1815
  // shaders: a plain list
1520
1816
  const shaderPanel = el('div', 'pci-listpanel');
1521
1817
  const shaderList = el('div', 'pci-list');
1522
1818
  shaderPanel.append(shaderList);
1523
1819
 
1524
- for (const input of [this._previewToggle, this._previewAttachment, this._previewChannels, this._texturePreviewToggle, this._textureChannels, this._assetSort, this._bufferKind]) {
1820
+ for (const input of [this._previewToggle, this._previewAttachment, this._previewChannels, this._texturePreviewToggle, this._textureChannels, this._assetSort]) {
1525
1821
  input.addEventListener('change', () => this._saveSettings());
1526
1822
  }
1527
1823
 
@@ -1574,6 +1870,7 @@ class Inspector {
1574
1870
  hierarchy: tree,
1575
1871
  assets: assetPanel,
1576
1872
  passes: passPanel,
1873
+ perf: perfPanel,
1577
1874
  targets: targetPanel,
1578
1875
  textures: texturePanel,
1579
1876
  meshes: meshPanel,
@@ -1584,17 +1881,18 @@ class Inspector {
1584
1881
  shaders: shaderPanel,
1585
1882
  physics: physicsPanel
1586
1883
  };
1587
- 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);
1588
1885
 
1589
1886
  const splitter = el('div', 'pci-splitter');
1590
1887
  const properties = el('div', 'pci-properties');
1591
1888
  body.append(this._hierarchyEl, splitter, properties);
1592
1889
 
1593
- this._gpuToggle.addEventListener('change', () => {
1594
- const profiler = this._app.graphicsDevice.gpuProfiler;
1595
- if (profiler) profiler.enabled = this._gpuToggle.checked;
1596
- this._saveSettings();
1597
- });
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
+ }
1598
1896
  this._passPreviewToggle.addEventListener('change', () => this._saveSettings());
1599
1897
  this._debugFrameToggle.addEventListener('change', () => this._setDebugFrame(this._debugFrameToggle.checked));
1600
1898
  this._freezeToggle.addEventListener('change', () => {
@@ -1620,7 +1918,7 @@ class Inspector {
1620
1918
 
1621
1919
  this._makeDraggable(splitter, (e) => {
1622
1920
  const rect = body.getBoundingClientRect();
1623
- 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));
1624
1922
  this._hierarchyEl.style.flexBasis = `${height}px`;
1625
1923
  });
1626
1924
 
@@ -1644,11 +1942,20 @@ class Inspector {
1644
1942
  installTooltip(panel);
1645
1943
  shadow.append(style, panel);
1646
1944
 
1945
+ this._menu?.destroy();
1946
+ this._menu = new ContextMenu(panel);
1947
+ panel.addEventListener('contextmenu', this._onContextMenu);
1948
+
1647
1949
  // keep the app's input handlers from seeing interaction with the panel
1648
1950
  for (const type of SWALLOWED_EVENTS) {
1649
1951
  host.addEventListener(type, (e) => {
1650
1952
  e.stopPropagation();
1651
- 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
+ }
1652
1959
  });
1653
1960
  }
1654
1961
 
@@ -1661,10 +1968,12 @@ class Inspector {
1661
1968
  this._selected = node;
1662
1969
  if (this._tab === 'hierarchy') this._properties.setSubject(node, buildNodeModel);
1663
1970
  if (node && this._fly instanceof CameraOrbit) this._fly.setTarget(node);
1664
- this._applyOrbitState();
1971
+ this._transformTool?.attach(node);
1972
+ this._applyViewToolState();
1665
1973
  this._updateStatus();
1666
1974
  });
1667
1975
  this._hierarchy.isLocked = node => this._isLocked(node);
1976
+ this._hierarchy.isHidden = node => node === this._transformTool?.root;
1668
1977
  this._hierarchy.onToggle = () => this._properties.refresh();
1669
1978
  this._passList = new ListView(passList, (item, key) => {
1670
1979
  if (this._tab === 'passes') this._properties.setSubject(item, this._passListModel(item), key);
@@ -1717,11 +2026,7 @@ class Inspector {
1717
2026
  const onHover = (el, target) => {
1718
2027
  this._hoverLink = el && target ? { el, target } : null;
1719
2028
  };
1720
- const views = [
1721
- this._properties, this._passList, this._targetList, this._textureList, this._shaderList, this._meshList,
1722
- this._materialList, this._scriptList, this._cameraList, this._bufferList, this._assetList, this._bodyList
1723
- ];
1724
- for (const view of views) view.onHover = onHover;
2029
+ for (const view of [this._properties, ...this._lists()]) view.onHover = onHover;
1725
2030
  }
1726
2031
 
1727
2032
  /**
@@ -1820,17 +2125,29 @@ class Inspector {
1820
2125
  }
1821
2126
  if (typeof stored.width === 'number') this._setWidth(stored.width);
1822
2127
  if (typeof stored.passPreview === 'boolean') this._passPreviewToggle.checked = stored.passPreview;
1823
- if (typeof stored.gpuTimings === 'boolean') {
1824
- this._gpuToggle.checked = stored.gpuTimings;
1825
- const profiler = this._app.graphicsDevice.gpuProfiler;
1826
- 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'));
1827
2144
  }
1828
2145
  if (stored.targetPreview && typeof stored.targetPreview === 'object') {
1829
2146
  if (typeof stored.targetPreview.enabled === 'boolean') this._previewToggle.checked = stored.targetPreview.enabled;
1830
2147
  if (typeof stored.targetPreview.channels === 'string') this._previewChannels.value = stored.targetPreview.channels;
1831
2148
  }
1832
2149
  if (typeof stored.assetSort === 'string') this._assetSort.value = stored.assetSort;
1833
- if (typeof stored.bufferKind === 'string') this._bufferKind.value = stored.bufferKind;
2150
+ if (typeof stored.copyDepth === 'number') this._setCopyDepth(stored.copyDepth);
1834
2151
  if (typeof stored.filterBy === 'string') {
1835
2152
  this._filterBy.value = stored.filterBy;
1836
2153
  this._hierarchy.filterBy = /** @type {any} */ (this._filterBy.value);
@@ -1864,12 +2181,19 @@ class Inspector {
1864
2181
  tab: this._tab,
1865
2182
  width: this._width,
1866
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],
1867
2191
  passPreview: this._passPreviewToggle.checked,
1868
2192
  targetPreview: { enabled: this._previewToggle.checked, channels: this._previewChannels.value },
1869
2193
  texturePreview: { enabled: this._texturePreviewToggle.checked, channels: this._textureChannels.value },
1870
2194
  assetSort: this._assetSort.value,
1871
- bufferKind: this._bufferKind.value,
1872
- filterBy: this._filterBy.value
2195
+ filterBy: this._filterBy.value,
2196
+ copyDepth: this._copyDepth
1873
2197
  }));
1874
2198
  } catch (e) {
1875
2199
  // storage unavailable or full: settings simply do not persist
@@ -2473,15 +2797,156 @@ class Inspector {
2473
2797
  return input;
2474
2798
  }
2475
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
+
2476
2936
  /**
2477
2937
  * Switches the list tab and points the property view at that tab's selection.
2478
2938
  *
2479
- * @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.
2480
2940
  * @private
2481
2941
  */
2482
2942
  _setTab(tab) {
2483
2943
  this._tab = tab;
2944
+ this._menu?.hide();
2484
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();
2485
2950
  this._updateFilterHint();
2486
2951
  for (const [id, button] of Object.entries(this._tabButtons)) {
2487
2952
  button.classList.toggle('pci-active', id === tab);
@@ -2489,6 +2954,8 @@ class Inspector {
2489
2954
  for (const [id, panel] of Object.entries(this._panels)) {
2490
2955
  panel.style.display = id === tab ? '' : 'none';
2491
2956
  }
2957
+ // measured with the tab's panel shown
2958
+ if (tab === 'perf') this._fitTop();
2492
2959
  this._refreshLists(false);
2493
2960
  if (tab === 'hierarchy') {
2494
2961
  this._properties.setSubject(this._hierarchy.selected, buildNodeModel);
@@ -2565,8 +3032,7 @@ class Inspector {
2565
3032
  this._properties.setSubject(cls, this._scriptModel, this._scriptList.selectedKey);
2566
3033
  }
2567
3034
  } else if (this._tab === 'memory') {
2568
- Inspector._setNote(this._memoryNote, memorySummary(device));
2569
- this._bufferList.setRows(bufferRows(device, bufferOwners(this._app), this._bufferKind.value));
3035
+ this._bufferList.setRows(memoryRows(device, bufferOwners(this._app)));
2570
3036
  const buffer = this._bufferList.selected;
2571
3037
  if (buffer !== this._properties.subject) {
2572
3038
  this._properties.setSubject(buffer, this._bufferModel, this._bufferList.selectedKey);
@@ -2583,6 +3049,12 @@ class Inspector {
2583
3049
  if (shader !== this._properties.subject) {
2584
3050
  this._properties.setSubject(shader, this._shaderModel, this._shaderList.selectedKey);
2585
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();
2586
3058
  } else {
2587
3059
  if ((capture && !this._frozen) || !this._frame) {
2588
3060
  this._frame = captureFrameGraph(this._app);
@@ -2629,6 +3101,330 @@ class Inspector {
2629
3101
  this._properties.refresh();
2630
3102
  }
2631
3103
 
3104
+ /**
3105
+ * @returns {Record<string, ListView>} The list of each tab, all but the hierarchy, by tab.
3106
+ * @private
3107
+ */
3108
+ _tabLists() {
3109
+ return {
3110
+ passes: this._passList,
3111
+ targets: this._targetList,
3112
+ textures: this._textureList,
3113
+ shaders: this._shaderList,
3114
+ meshes: this._meshList,
3115
+ materials: this._materialList,
3116
+ scripts: this._scriptList,
3117
+ cameras: this._cameraList,
3118
+ memory: this._bufferList,
3119
+ assets: this._assetList,
3120
+ physics: this._bodyList
3121
+ };
3122
+ }
3123
+
3124
+ /**
3125
+ * @returns {ListView[]} The lists of the tabs, all but the hierarchy.
3126
+ * @private
3127
+ */
3128
+ _lists() {
3129
+ return Object.values(this._tabLists());
3130
+ }
3131
+
3132
+ /**
3133
+ * Opens the copy menu on what was right-clicked. Text fields keep the browser's own menu, to
3134
+ * paste into them.
3135
+ *
3136
+ * @param {MouseEvent} e - The event.
3137
+ * @private
3138
+ */
3139
+ _onContextMenu = (e) => {
3140
+ if (isTextTarget(e)) return;
3141
+ const copy = this._copyTargetAt(/** @type {Node} */ (e.composedPath()[0]), e);
3142
+ if (!copy) return;
3143
+ e.preventDefault();
3144
+ this._menu?.show(e.clientX, e.clientY, copy.title, this._copyItems(copy));
3145
+ };
3146
+
3147
+ /**
3148
+ * What a right click copies: a row or section of the property view, or anywhere else in it
3149
+ * the subject. A row of a list or of the hierarchy is selected first, the way a click selects
3150
+ * it, and the subject it shows is copied; the header of a group copies the group, and a row
3151
+ * that selects nothing its figures. A tab is opened first, the way a click opens it, and
3152
+ * everything it lists is copied.
3153
+ *
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.
3156
+ * @returns {CopyTarget|null} What to copy, or null for a part of the panel nothing is copied
3157
+ * from, such as the toolbar.
3158
+ * @private
3159
+ */
3160
+ _copyTargetAt(target, e) {
3161
+ const property = this._properties.copyTargetAt(target);
3162
+ if (property) return property;
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
+
3168
+ const node = this._hierarchy.nodeAt(target);
3169
+ if (node) {
3170
+ this._hierarchy.select(node);
3171
+ return this._properties.subjectCopyTarget();
3172
+ }
3173
+ for (const list of this._lists()) {
3174
+ const row = list.rowAt(target);
3175
+ if (!row) continue;
3176
+ if (row.header) return { title: row.name, copy: options => copyGroup(list.rows, row.key, options) };
3177
+ if (row.inert) return { title: row.name, copy: () => copyListRow(row) };
3178
+ list.select(row.key);
3179
+ return this._properties.subjectCopyTarget();
3180
+ }
3181
+
3182
+ const tab = Object.keys(this._tabButtons).find(id => this._tabButtons[id].contains(target));
3183
+ if (tab) {
3184
+ this._setTab(/** @type {any} */ (tab));
3185
+ return this._tabCopyTarget(tab);
3186
+ }
3187
+ return null;
3188
+ }
3189
+
3190
+ /**
3191
+ * @param {string} tab - A tab.
3192
+ * @returns {CopyTarget|null} A copy of everything the tab lists: the hierarchy from its root,
3193
+ * or every row of the tab's list, whatever its filter shows.
3194
+ * @private
3195
+ */
3196
+ _tabCopyTarget(tab) {
3197
+ const title = this._tabButtons[tab].textContent ?? tab;
3198
+ if (tab === 'perf') return this._perf.count ? this._perfCopy({ kind: 'capture' }) : null;
3199
+ if (tab === 'hierarchy') {
3200
+ const root = this._app.root;
3201
+ return { title, copy: options => copySubject(root, buildNodeModel(root), options) };
3202
+ }
3203
+ const list = this._tabLists()[tab];
3204
+ return list ? { title, copy: options => copyList(title, list.rows, options) } : null;
3205
+ }
3206
+
3207
+ /**
3208
+ * @param {CopyTarget} copy - What the menu copies.
3209
+ * @returns {MenuItem[]} The entries of the menu: on its own, a
3210
+ * number of links deep, and every link there is.
3211
+ * @private
3212
+ */
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
+ }
3224
+ const levels = n => `${n} level${n === 1 ? '' : 's'}`;
3225
+ return [{
3226
+ text: () => 'Copy as JSON',
3227
+ title: 'Copy it on its own: what it links to is named, not copied',
3228
+ run: () => this._copy(copy, 0)
3229
+ }, {
3230
+ text: () => `Copy ${levels(this._copyDepth)} deep`,
3231
+ title: 'Copy it with what it links to, up to this many links away: children, mesh instances, materials, textures',
3232
+ run: () => this._copy(copy, this._copyDepth),
3233
+ buttons: [{
3234
+ text: '−',
3235
+ title: 'One level less',
3236
+ disabled: () => this._copyDepth <= 1,
3237
+ run: () => this._setCopyDepth(this._copyDepth - 1)
3238
+ }, {
3239
+ text: '+',
3240
+ title: 'One level more',
3241
+ disabled: () => this._copyDepth >= MAX_COPY_DEPTH,
3242
+ run: () => this._setCopyDepth(this._copyDepth + 1)
3243
+ }]
3244
+ }, {
3245
+ text: () => 'Copy all levels',
3246
+ title: 'Copy it with everything it links to, however far, such as the whole hierarchy below a node',
3247
+ run: () => this._copy(copy, Infinity)
3248
+ }];
3249
+ }
3250
+
3251
+ /**
3252
+ * @param {number} depth - How many links the deep copy follows.
3253
+ * @private
3254
+ */
3255
+ _setCopyDepth(depth) {
3256
+ this._copyDepth = Math.max(1, Math.min(MAX_COPY_DEPTH, Math.round(depth)));
3257
+ this._saveSettings();
3258
+ }
3259
+
3260
+ /**
3261
+ * Copies to the clipboard as JSON, and notes how much was copied.
3262
+ *
3263
+ * @param {CopyTarget} copy - What to copy.
3264
+ * @param {number} depth - How many links to follow, see {@link CopyOptions#depth}.
3265
+ * @private
3266
+ */
3267
+ _copy(copy, depth) {
3268
+ const ctx = { ...this._context(), backlinks: false };
3269
+ const opaque = this._opaqueObjects();
3270
+ let result;
3271
+ let text;
3272
+ try {
3273
+ result = copy.copy({
3274
+ depth,
3275
+ modelFor: obj => this._copyModel(obj, ctx),
3276
+ opaque: obj => opaque.has(obj),
3277
+ exclude: obj => obj === this._transformTool?.root
3278
+ });
3279
+ text = stringifyCopy(result.json);
3280
+ } catch (e) {
3281
+ this._menu?.note(`Could not copy: ${e?.message ?? e}`);
3282
+ return;
3283
+ }
3284
+
3285
+ const size = formatBytes(text.length);
3286
+ const note = `Copied ${result.objects ? `${result.objects} object${result.objects === 1 ? '' : 's'}, ` : ''}${size}` +
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) {
3315
+ // the clipboard of the window the panel is in, which is the one with focus once popped out
3316
+ const clipboard = (this._panel.ownerDocument.defaultView ?? window).navigator.clipboard;
3317
+ if (!clipboard) {
3318
+ this._menu?.note('The page has no access to the clipboard');
3319
+ return;
3320
+ }
3321
+ clipboard.writeText(text).then(
3322
+ () => this._menu?.note(note),
3323
+ e => this._menu?.note(`Could not copy: ${e?.message ?? e}`)
3324
+ );
3325
+ }
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
+
3369
+ /**
3370
+ * @returns {Set<object>} The app's own objects, which a copy never follows, as through them it
3371
+ * would reach everything else.
3372
+ * @private
3373
+ */
3374
+ _opaqueObjects() {
3375
+ const app = /** @type {any} */ (this._app);
3376
+ const objects = new Set([app, app.scene?.layers]);
3377
+ for (const value of Object.values(app)) {
3378
+ if (value && typeof value === 'object') objects.add(value);
3379
+ }
3380
+ for (const system of app.systems?.list ?? []) objects.add(system);
3381
+ for (const layer of app.scene?.layers?.layerList ?? []) objects.add(layer);
3382
+ return objects;
3383
+ }
3384
+
3385
+ /**
3386
+ * The model a copy follows a link into: what the tab the link opens on shows, see
3387
+ * {@link Inspector#_selectAny}, without the lists of what uses the object.
3388
+ *
3389
+ * @param {object} obj - An object reached through a link.
3390
+ * @param {PassModelContext & { app: AppBase, backlinks: boolean }} ctx - What the model
3391
+ * builders need besides their subject.
3392
+ * @returns {PropertySection[]|PropertyRow[]|null} The model, or null for an object no tab shows.
3393
+ * @private
3394
+ */
3395
+ _copyModel(obj, ctx) {
3396
+ if (obj instanceof GraphNode) return buildNodeModel(obj);
3397
+ if (obj instanceof Component) return buildComponentModel(obj);
3398
+ if (obj instanceof MeshInstance) return meshInstanceRows(obj);
3399
+ if (obj instanceof RenderTarget) return buildRenderTargetModel(obj, ctx);
3400
+ if (obj instanceof FramePass) return buildPassModel(obj, ctx);
3401
+ if (obj instanceof LayerStepSelection) return buildStepModel(obj, ctx);
3402
+ if (obj instanceof Texture) return buildTextureModel(obj, ctx);
3403
+ if (obj instanceof Shader) return buildShaderModel(obj);
3404
+ if (obj instanceof Asset) return buildAssetModel(obj, ctx);
3405
+ if (isScriptClass(obj)) return buildScriptModel(/** @type {Function} */ (obj), ctx);
3406
+ if (obj instanceof Material) return buildMaterialModel(obj, ctx);
3407
+ if (obj instanceof Mesh) return buildMeshModel(obj, ctx);
3408
+ if (bufferKind(obj)) return buildBufferModel(obj, ctx);
3409
+ return null;
3410
+ }
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
+
2632
3428
  /**
2633
3429
  * Reveals a linked object in the tab that lists it: nodes in the hierarchy, passes in the frame
2634
3430
  * graph, render targets in their list.
@@ -2665,8 +3461,6 @@ class Inspector {
2665
3461
  this._setTab('meshes');
2666
3462
  this._meshList.selectItem(target);
2667
3463
  } else if (bufferKind(target)) {
2668
- // a filter hiding the buffer's kind would leave nothing to select
2669
- if (this._bufferKind.value !== 'all' && this._bufferKind.value !== bufferKind(target)) this._bufferKind.value = 'all';
2670
3464
  this._setTab('memory');
2671
3465
  this._bufferList.selectItem(target);
2672
3466
  }
@@ -2731,6 +3525,7 @@ class Inspector {
2731
3525
  */
2732
3526
  _applyVisibility() {
2733
3527
  if (!this._host) return;
3528
+ if (!this._visible) this._menu?.hide();
2734
3529
  this._host.style.display = this._visible ? '' : 'none';
2735
3530
  }
2736
3531
 
@@ -2820,6 +3615,22 @@ class Inspector {
2820
3615
  item ? passDisplayName(item) : '';
2821
3616
  break;
2822
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
+ }
2823
3634
  case 'targets': {
2824
3635
  counts = `${this._targetList.rowCount} render targets · ${this._frame?.usage.size ?? 0} used this frame`;
2825
3636
  const rt = this._targetList.selected;
@@ -2864,11 +3675,10 @@ class Inspector {
2864
3675
  break;
2865
3676
  }
2866
3677
  case 'memory': {
2867
- const buffers = collectBuffers(device, this._bufferKind.value);
2868
- const bytes = buffers.reduce((sum, buffer) => sum + bufferBytes(buffer), 0);
2869
- counts = `${buffers.length} buffers · ${formatBytes(bytes)}`;
2870
- const buffer = this._bufferList.selected;
2871
- selected = buffer ? `${buffer.constructor.name} #${idOf(buffer)}` : '';
3678
+ counts = `${formatBytes(videoMemory(device))} of video memory`;
3679
+ // a buffer whose owner was not found is dimmed, and its name says only that
3680
+ const row = this._bufferList.selectedRow;
3681
+ selected = row ? `${KIND_NAMES[bufferKind(row.item)]}${row.dim ? '' : ` of ${row.name}`}` : '';
2872
3682
  break;
2873
3683
  }
2874
3684
  case 'assets': {
@@ -2918,7 +3728,7 @@ class Inspector {
2918
3728
  * @private
2919
3729
  */
2920
3730
  _setPicking(on) {
2921
- if (on === (this._canvasMode === 'pick')) return;
3731
+ if (on === (this._canvasMode === 'pick') || (on && this._transformTool)) return;
2922
3732
  this._releaseCanvas();
2923
3733
  if (on) {
2924
3734
  this._stopFly();
@@ -3010,6 +3820,7 @@ class Inspector {
3010
3820
  * @private
3011
3821
  */
3012
3822
  _startDrive(kind, camera) {
3823
+ if (this._transformTool) return;
3013
3824
  this._stopFly();
3014
3825
  this._setPicking(false);
3015
3826
  const target = this._selected;
@@ -3054,16 +3865,22 @@ class Inspector {
3054
3865
  }
3055
3866
  this._flyBtn?.classList.remove('pci-active');
3056
3867
  this._orbitBtn?.classList.remove('pci-active');
3057
- this._applyOrbitState();
3868
+ this._applyViewToolState();
3058
3869
  }
3059
3870
 
3060
3871
  /**
3061
- * Orbit needs a node to orbit around, so its button is off until one is selected.
3872
+ * Pick, Fly and Orbit take the view from the app, which a gizmo needs to be used in, so their
3873
+ * buttons are off while one is on. Orbit also needs a node to orbit around, so its button is off
3874
+ * until one is selected.
3062
3875
  *
3063
3876
  * @private
3064
3877
  */
3065
- _applyOrbitState() {
3066
- if (this._orbitBtn) this._orbitBtn.disabled = !this._selected && !(this._fly instanceof CameraOrbit);
3878
+ _applyViewToolState() {
3879
+ if (!this._orbitBtn) return;
3880
+ const gizmo = !!this._transformTool;
3881
+ this._pickBtn.disabled = gizmo;
3882
+ this._flyBtn.disabled = gizmo;
3883
+ this._orbitBtn.disabled = gizmo || (!this._selected && !(this._fly instanceof CameraOrbit));
3067
3884
  }
3068
3885
 
3069
3886
  /**
@@ -3113,6 +3930,7 @@ class Inspector {
3113
3930
  if (!this._pickBtn) return;
3114
3931
  this._setPicking(false);
3115
3932
  this._stopFly();
3933
+ this._setTransformMode(null);
3116
3934
  this._resetRenderOverrides();
3117
3935
  this._modeEl.textContent = '';
3118
3936
  }
@@ -3200,10 +4018,70 @@ class Inspector {
3200
4018
  } else if (this._fly) {
3201
4019
  const keys = this._fly.zooms ? 'W S zoom, A D Q E pan' : 'WASD QE move';
3202
4020
  text = `FLY · "${this._fly.camera.entity.name}" · ${keys}, drag to look, wheel speed ${this._fly.speed.toFixed(1)}, Shift faster · Esc stops`;
4021
+ } else if (this._transformTool) {
4022
+ const selected = this._selected;
4023
+ text = `${this._transformTool.mode.toUpperCase()} · ${selected ? `drag the gizmo on "${selected.name}"` : 'select an entity'} · Esc stops`;
3203
4024
  }
3204
4025
  if (this._modeEl.textContent !== text && (text || !this._modeEl.textContent.includes(' · no camera'))) this._modeEl.textContent = text;
3205
4026
  }
3206
4027
 
4028
+ /**
4029
+ * Turns a gizmo on, in place of the one that is on, or turns it off. The gizmo is drawn and
4030
+ * used in the view of the first camera drawing to the screen, which Pick, Fly and Orbit would
4031
+ * take from the app, so they stop and stay off while it is on.
4032
+ *
4033
+ * @param {TransformMode|null} mode - What the gizmo does, or null to turn it off.
4034
+ * @private
4035
+ */
4036
+ _setTransformMode(mode) {
4037
+ window.removeEventListener('keydown', this._onTransformKey, true);
4038
+ this._transformTool?.destroy();
4039
+ this._transformTool = null;
4040
+ if (mode) {
4041
+ this._setPicking(false);
4042
+ this._stopFly();
4043
+ const camera = collectCameras(this._app).find(isScreenCamera) ?? null;
4044
+ if (camera) {
4045
+ this._transformTool = new TransformTool(this._app, mode, camera);
4046
+ this._transformTool.attach(this._selected);
4047
+ // Esc turns it off, as it ends Pick, Fly and Orbit
4048
+ window.addEventListener('keydown', this._onTransformKey, true);
4049
+ } else {
4050
+ this._modeEl.textContent = `${mode.toUpperCase()} · no camera draws to the screen`;
4051
+ }
4052
+ }
4053
+ for (const [id, button] of Object.entries(this._transformBtns ?? {})) {
4054
+ button.classList.toggle('pci-active', this._transformTool?.mode === id);
4055
+ }
4056
+ this._applyViewToolState();
4057
+ this._hierarchy?.refresh();
4058
+ // the Cameras tab offers to fly only while no gizmo is on
4059
+ this._properties?.refresh();
4060
+ }
4061
+
4062
+ /**
4063
+ * @param {KeyboardEvent} e - A key pressed while a gizmo is on.
4064
+ * @private
4065
+ */
4066
+ _onTransformKey = (e) => {
4067
+ // Escape in a text field, such as a value being edited, is the field's own
4068
+ if (e.key !== 'Escape' || isTextTarget(e)) return;
4069
+ e.stopImmediatePropagation();
4070
+ this._setTransformMode(null);
4071
+ };
4072
+
4073
+ /**
4074
+ * Hands the pointer to the gizmo first, and keeps from everything else what it keeps.
4075
+ *
4076
+ * @param {Event} e - A pointer event anywhere in the window.
4077
+ * @private
4078
+ */
4079
+ _onTransformPointer = (e) => {
4080
+ if (!this._transformTool?.handle(e)) return;
4081
+ e.stopImmediatePropagation();
4082
+ if (e.cancelable) e.preventDefault();
4083
+ };
4084
+
3207
4085
  /**
3208
4086
  * Outlines a node in the viewport for the current frame.
3209
4087
  *