@playcanvas/inspector 0.1.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 (77) hide show
  1. package/LICENSE +19 -0
  2. package/README.md +110 -0
  3. package/package.json +62 -0
  4. package/src/asset-usage.js +108 -0
  5. package/src/asset-view.js +370 -0
  6. package/src/camera-view.js +128 -0
  7. package/src/debug.js +31 -0
  8. package/src/describe.js +302 -0
  9. package/src/entity-inspector-script.js +130 -0
  10. package/src/frame-graph-view.js +767 -0
  11. package/src/hierarchy-view.js +475 -0
  12. package/src/index.js +4 -0
  13. package/src/input/fly-controller.js +116 -0
  14. package/src/input/input.js +299 -0
  15. package/src/input/math.js +8 -0
  16. package/src/input/orbit-controller.js +158 -0
  17. package/src/input/pose.js +207 -0
  18. package/src/inspector.js +3293 -0
  19. package/src/instance-survey.js +50 -0
  20. package/src/list-view.js +410 -0
  21. package/src/material-view.js +197 -0
  22. package/src/memory-view.js +344 -0
  23. package/src/mesh-view.js +235 -0
  24. package/src/model.js +170 -0
  25. package/src/node-model.js +404 -0
  26. package/src/physics-debug.js +527 -0
  27. package/src/physics-view.js +314 -0
  28. package/src/picker/picker.js +545 -0
  29. package/src/picker/render-pass-picker.js +206 -0
  30. package/src/property-view.js +628 -0
  31. package/src/render-target-view.js +288 -0
  32. package/src/renderers/texture-renderer-shaders.js +139 -0
  33. package/src/renderers/texture-renderer.js +430 -0
  34. package/src/renderers/wire-renderer.js +954 -0
  35. package/src/script-view.js +288 -0
  36. package/src/shader-view.js +287 -0
  37. package/src/styles.js +918 -0
  38. package/src/texture-view.js +186 -0
  39. package/src/tooltip.js +72 -0
  40. package/src/viewport-tools.js +695 -0
  41. package/types/asset-usage.d.ts +23 -0
  42. package/types/asset-view.d.ts +94 -0
  43. package/types/camera-view.d.ts +45 -0
  44. package/types/debug.d.ts +14 -0
  45. package/types/describe.d.ts +43 -0
  46. package/types/entity-inspector-script.d.ts +87 -0
  47. package/types/frame-graph-view.d.ts +155 -0
  48. package/types/hierarchy-view.d.ts +172 -0
  49. package/types/index.d.ts +3 -0
  50. package/types/input/fly-controller.d.ts +42 -0
  51. package/types/input/input.d.ts +192 -0
  52. package/types/input/math.d.ts +1 -0
  53. package/types/input/orbit-controller.d.ts +63 -0
  54. package/types/input/pose.d.ts +126 -0
  55. package/types/inspector.d.ts +1304 -0
  56. package/types/instance-survey.d.ts +35 -0
  57. package/types/list-view.d.ts +151 -0
  58. package/types/material-view.d.ts +63 -0
  59. package/types/memory-view.d.ts +95 -0
  60. package/types/mesh-view.d.ts +89 -0
  61. package/types/model.d.ts +104 -0
  62. package/types/node-model.d.ts +54 -0
  63. package/types/physics-debug.d.ts +254 -0
  64. package/types/physics-view.d.ts +81 -0
  65. package/types/picker/picker.d.ts +255 -0
  66. package/types/picker/render-pass-picker.d.ts +47 -0
  67. package/types/property-view.d.ts +189 -0
  68. package/types/render-target-view.d.ts +98 -0
  69. package/types/renderers/texture-renderer-shaders.d.ts +9 -0
  70. package/types/renderers/texture-renderer.d.ts +231 -0
  71. package/types/renderers/wire-renderer.d.ts +347 -0
  72. package/types/script-view.d.ts +56 -0
  73. package/types/shader-view.d.ts +46 -0
  74. package/types/styles.d.ts +22 -0
  75. package/types/texture-view.d.ts +30 -0
  76. package/types/tooltip.d.ts +17 -0
  77. package/types/viewport-tools.d.ts +237 -0
@@ -0,0 +1,3293 @@
1
+ import {
2
+ Asset, Color, Entity, FramePass, GraphNode, LAYERID_UI, Material, Mesh, RenderPassForward, RenderTarget, Shader, Texture
3
+ } from 'playcanvas';
4
+
5
+ import { TextureRenderer } from './renderers/texture-renderer.js';
6
+ import { WireRenderer } from './renderers/wire-renderer.js';
7
+
8
+ import { pushResourceUsage } from './asset-usage.js';
9
+ import { ASSET_SORTS, assetRows, buildAssetModel, collectAssets } from './asset-view.js';
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';
13
+ import { HierarchyView, filterSuggestions } from './hierarchy-view.js';
14
+ import { ListView } from './list-view.js';
15
+ import {
16
+ buildMaterialModel, materialListRows, materialsUsingShader, materialsUsingTexture, surveyMaterials,
17
+ usedByMaterialsSection
18
+ } from './material-view.js';
19
+ import { buildMeshModel, meshBytes, meshListRows, meshNote, surveyMeshes } from './mesh-view.js';
20
+ import { formatBytes, formatName, passDisplayName } from './model.js';
21
+ import { buildNodeModel } from './node-model.js';
22
+ import { AmmoDebugDraw, DEBUG_DRAW } from './physics-debug.js';
23
+ import { bodyRows, drawCollisionShape, drawJoint, jointRows, physicsStats } from './physics-view.js';
24
+ import { PropertyView } from './property-view.js';
25
+ import { buildScriptModel, isScriptClass, scriptListRows, surveyScripts } from './script-view.js';
26
+ import { buildRenderTargetModel, formatChannels, isDepthFormat, previewAttachments, previewSupport, renderTargetRows, storedBottomUp } from './render-target-view.js';
27
+ import { buildShaderModel, collectShaders, shaderRows, stateName } from './shader-view.js';
28
+ import { styles } from './styles.js';
29
+ import { installTooltip, setTip } from './tooltip.js';
30
+ import { CameraFly, CameraOrbit, CanvasCapture, RENDER_MODES, ViewportPicker, WireframeMode, isScreenCamera, screenCameraAt } from './viewport-tools.js';
31
+ import { buildTextureModel, collectTextures, textureRows } from './texture-view.js';
32
+
33
+ /** @import { AppBase } from 'playcanvas' */
34
+ /** @import { GraphicsDevice } from 'playcanvas' */
35
+ /** @import { FrameSnapshot, PassModelContext } from './frame-graph-view.js' */
36
+ /** @import { MeshInstance } from 'playcanvas' */
37
+ /** @import { PropertySection } from './model.js' */
38
+
39
+ /**
40
+ * Options for {@link Inspector}.
41
+ *
42
+ * @typedef {object} InspectorOptions
43
+ * @property {boolean} [visible] - Whether the panel starts shown. Defaults to true.
44
+ * @property {'left'|'right'} [dock] - The side of the viewport the panel docks to. Defaults to
45
+ * 'right'.
46
+ * @property {number} [width] - The width of the docked panel in CSS pixels. Defaults to 420.
47
+ * @property {number} [top] - A gap left above the panel in CSS pixels, to keep it clear of other
48
+ * overlays. Defaults to 0.
49
+ * @property {string} [toggleKey] - The `KeyboardEvent.code` or `key` that shows and hides the
50
+ * panel. Defaults to 'Backquote'. Empty disables the key.
51
+ * @property {string} [pauseKey] - The key that pauses and resumes the app. Defaults to 'F9'.
52
+ * @property {string} [stepKey] - The key that advances one frame while paused. Defaults to 'F10'.
53
+ * @property {GraphNode|null} [lockedNode] - A node whose enabled checkbox, and those of its
54
+ * ancestors, are withheld. A script hosting the inspector passes its own entity so the panel
55
+ * cannot switch itself off. Defaults to null.
56
+ * @property {(visible: boolean) => void} [onVisibleChange] - Called with the new visibility
57
+ * whenever the panel is shown or hidden, whether through {@link Inspector#visible}, the toggle key
58
+ * or the panel's own close button.
59
+ * @property {string|null} [storageKey] - The local storage key the panel's settings are kept
60
+ * 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
63
+ * 'pc-inspector'; null keeps nothing.
64
+ */
65
+
66
+ /**
67
+ * Which parts of the physics world the Physics tab draws. Each option is a checkbox on the tab.
68
+ *
69
+ * @typedef {object} InspectorPhysicsDrawOptions
70
+ * @property {boolean} [wireframe] - Collision shapes, colored by activation state. Defaults to
71
+ * true.
72
+ * @property {boolean} [aabb] - Axis-aligned bounds of each body.
73
+ * @property {boolean} [contacts] - Contact points and normals from the last step.
74
+ * @property {boolean} [constraints] - Joint frames.
75
+ * @property {boolean} [limits] - Joint limits.
76
+ * @property {boolean} [normals] - Face normals of mesh shapes.
77
+ * @property {boolean} [frames] - Local axes of each body.
78
+ * @property {boolean} [keepAwake] - Stop bodies from falling asleep while drawing.
79
+ * @property {boolean} [depthTest] - Hide lines behind geometry.
80
+ * @property {number} [range] - Only draw lines within this distance of the camera, in meters. Zero
81
+ * draws everything.
82
+ * @ignore
83
+ */
84
+
85
+ // the Bullet debug flag behind each boolean option
86
+ const PHYSICS_FLAGS = {
87
+ wireframe: DEBUG_DRAW.WIREFRAME,
88
+ aabb: DEBUG_DRAW.AABB,
89
+ contacts: DEBUG_DRAW.CONTACT_POINTS,
90
+ constraints: DEBUG_DRAW.CONSTRAINTS,
91
+ limits: DEBUG_DRAW.CONSTRAINT_LIMITS,
92
+ normals: DEBUG_DRAW.NORMALS,
93
+ frames: DEBUG_DRAW.FRAMES,
94
+ keepAwake: DEBUG_DRAW.NO_DEACTIVATION
95
+ };
96
+
97
+ // seconds between refreshes of the active list, and of the selected item's properties
98
+ const LIST_INTERVAL = 0.5;
99
+ const PROPERTY_INTERVAL = 0.1;
100
+
101
+ // the tooltips of the tabs
102
+ const TAB_TIPS = {
103
+ hierarchy: 'The entity tree, and the components and properties of the selected entity',
104
+ cameras: 'The cameras of the scene in render order, with where they draw, their render mode and a way to fly each',
105
+ assets: 'The assets of the registry, and what uses each',
106
+ passes: 'The passes that rendered the last frame, with the layers, draws and targets of each',
107
+ targets: 'The render targets on the device, with a live preview of their textures',
108
+ textures: 'The textures on the device, largest first, with a live preview',
109
+ meshes: 'The meshes of the app, found through the components, layers and assets using them, largest first',
110
+ materials: 'The materials of the app, found through the mesh instances and assets using them, most used first',
111
+ 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',
113
+ shaders: 'The compiled shaders, with their sources',
114
+ physics: 'The rigid bodies and joints of the physics world, and its debug drawing'
115
+ };
116
+
117
+ const CHANNELS_TIP = 'Which channels of the texture to show. A single channel shows as grayscale';
118
+
119
+ // events the panel swallows so that they never reach the input handlers of the app underneath
120
+ const SWALLOWED_EVENTS = ['keydown', 'keyup', 'keypress', 'pointerdown', 'mousedown', 'wheel', 'touchstart', 'contextmenu'];
121
+
122
+ /**
123
+ * @param {string} tag - The element tag.
124
+ * @param {string} className - The class name.
125
+ * @param {string} [text] - The text content.
126
+ * @returns {HTMLElement} The element.
127
+ */
128
+ function el(tag, className, text) {
129
+ const element = document.createElement(tag);
130
+ element.className = className;
131
+ if (text !== undefined) element.textContent = text;
132
+ return element;
133
+ }
134
+
135
+ /**
136
+ * A toolbar button showing one of the icons of the stylesheet. The label names it for screen
137
+ * readers, as the tooltip only shows on hover.
138
+ *
139
+ * @param {string} icon - The icon name, one of `ICONS` in the stylesheet.
140
+ * @param {string} label - The accessible name of the button.
141
+ * @returns {HTMLButtonElement} The button.
142
+ */
143
+ function iconButton(icon, label) {
144
+ const button = /** @type {HTMLButtonElement} */ (el('button', `pci-btn pci-icon-btn pci-i-${icon}`));
145
+ button.setAttribute('aria-label', label);
146
+ return button;
147
+ }
148
+
149
+ /**
150
+ * @param {HTMLButtonElement} button - A button made by `iconButton`.
151
+ * @param {string} icon - The icon to show instead.
152
+ */
153
+ function setIcon(button, icon) {
154
+ button.className = button.className.replace(/\bpci-i-\S+/, `pci-i-${icon}`);
155
+ }
156
+
157
+ /**
158
+ * @param {Event} e - A keyboard event.
159
+ * @returns {boolean} Whether the key went to a text field.
160
+ */
161
+ function isTextTarget(e) {
162
+ const target = /** @type {HTMLInputElement|undefined} */ (e.composedPath()[0]);
163
+ if (!target) return false;
164
+ const tag = target.tagName;
165
+ if (tag === 'INPUT') {
166
+ // checkboxes and buttons take no text, so hotkeys stay live while one has focus
167
+ return !['checkbox', 'radio', 'button', 'range'].includes(target.type);
168
+ }
169
+ return tag === 'TEXTAREA' || tag === 'SELECT' || target.isContentEditable;
170
+ }
171
+
172
+ /**
173
+ * An in-page inspector for a running application. It docks a panel over the canvas with four
174
+ * tabs above a live property view of whatever is selected:
175
+ *
176
+ * - Hierarchy: the entity tree. The property view shows the node's transform, every component it
177
+ * carries and every script instance with its attributes. The selected node is outlined in the
178
+ * viewport.
179
+ * - Cameras: every camera in render order, with its target, viewport, layers and render mode. The
180
+ * render mode of a camera can be switched to a debug view of the material inputs, the whole scene
181
+ * drawn in wireframe, and any camera flown.
182
+ * - Frame graph: the render passes of the last frame in execution order, as the render pass trace
183
+ * 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.
185
+ * - Render targets: every render target on the device including the backbuffer, with its
186
+ * attachments and the passes that rendered into it this frame, linking back to the frame graph.
187
+ * The selected target's attachment can be previewed live in a corner of the viewport.
188
+ * - Textures: every texture on the device, largest GPU footprint first, with the same live preview.
189
+ * Texture values elsewhere, such as the maps of a material, link here.
190
+ * - Meshes: every mesh found through the components, layers and assets using it, largest first,
191
+ * with its geometry and users. Nothing keeps a list of meshes, so a note counts the vertex buffers
192
+ * on the device that belong to no mesh found. Mesh values elsewhere link here.
193
+ * - Materials: every material found through the mesh instances and assets using it, most used
194
+ * first, with its textures, compiled variants and users. Material values elsewhere link here, and
195
+ * the Textures and Shaders tabs list the materials using a texture or shader.
196
+ * - Scripts: every script class the script registry holds or an entity uses, with the entities using
197
+ * it, its declared attributes and its source as the browser keeps it. The script sections of an
198
+ * 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.
201
+ * - Shaders: every shader on the device with its language, state and vertex attributes. The
202
+ * 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
+ * - Physics: the rigid bodies and joints of the scene, with the physics world drawn over the scene
206
+ * through the engine's debug drawer when Ammo is loaded.
207
+ *
208
+ * 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.
210
+ *
211
+ * The view is read-only, with one exception: the checkbox on each hierarchy row flips the node's
212
+ * enabled flag.
213
+ *
214
+ * ```javascript
215
+ * const inspector = new Inspector(app, { dock: 'left' });
216
+ * inspector.visible = false; // show again with the backquote key
217
+ * ```
218
+ *
219
+ * Default keys: backquote toggles the panel, F9 pauses and resumes, F10 steps one frame while
220
+ * paused. Pausing sets {@link AppBase#timeScale} to zero and suspends the sound manager, so
221
+ * rendering continues while every time-driven system stands still. Scripts that read the wall
222
+ * clock rather than the frame delta keep moving.
223
+ *
224
+ * The property view is generic: it reflects on the public getters of each component and script,
225
+ * so components it has never heard of show up with all of their state.
226
+ *
227
+ * @category Debug
228
+ */
229
+ class Inspector {
230
+ /**
231
+ * Called with the new visibility whenever the panel is shown or hidden, whether through
232
+ * {@link visible}, the toggle key or the panel's own close button. Set from the
233
+ * {@link InspectorOptions#onVisibleChange} option, or assigned later.
234
+ *
235
+ * @type {((visible: boolean) => void)|null}
236
+ */
237
+ onVisibleChange = null;
238
+
239
+ /**
240
+ * @type {AppBase}
241
+ * @private
242
+ */
243
+ _app;
244
+
245
+ /** @private */
246
+ _toggleKey = 'Backquote';
247
+
248
+ /** @private */
249
+ _pauseKey = 'F9';
250
+
251
+ /** @private */
252
+ _stepKey = 'F10';
253
+
254
+ /**
255
+ * @type {Color}
256
+ * @private
257
+ */
258
+ _highlightColor = new Color(1, 0.55, 0.1);
259
+
260
+ /**
261
+ * @type {GraphNode|null}
262
+ * @private
263
+ */
264
+ _lockedNode = null;
265
+
266
+ /** @private */
267
+ _visible = true;
268
+
269
+ /** @private */
270
+ _dock = 'right';
271
+
272
+ /** @private */
273
+ _width = 420;
274
+
275
+ /** @private */
276
+ _top = 0;
277
+
278
+ /** @private */
279
+ _paused = false;
280
+
281
+ /** @private */
282
+ _savedTimeScale = 1;
283
+
284
+ /** @private */
285
+ _destroyed = false;
286
+
287
+ /**
288
+ * @type {Window|null}
289
+ * @private
290
+ */
291
+ _popup = null;
292
+
293
+ /**
294
+ * @type {GraphNode|null}
295
+ * @private
296
+ */
297
+ _selected = null;
298
+
299
+ /**
300
+ * @type {HTMLElement|null}
301
+ * @private
302
+ */
303
+ _host = null;
304
+
305
+ /**
306
+ * @type {HTMLElement}
307
+ * @private
308
+ */
309
+ _panel;
310
+
311
+ /**
312
+ * @type {HTMLElement}
313
+ * @private
314
+ */
315
+ _hierarchyEl;
316
+
317
+ /**
318
+ * @type {HTMLInputElement}
319
+ * @private
320
+ */
321
+ _filterInput;
322
+
323
+ /**
324
+ * What the hierarchy filter matches: entity names, component types or script names.
325
+ *
326
+ * @type {HTMLSelectElement}
327
+ * @private
328
+ */
329
+ _filterBy;
330
+
331
+ /**
332
+ * The values offered while filtering the hierarchy by component or script.
333
+ *
334
+ * @type {HTMLDataListElement}
335
+ * @private
336
+ */
337
+ _filterSuggestions;
338
+
339
+ /**
340
+ * @type {HTMLButtonElement}
341
+ * @private
342
+ */
343
+ _pauseBtn;
344
+
345
+ /**
346
+ * @type {HTMLButtonElement}
347
+ * @private
348
+ */
349
+ _stepBtn;
350
+
351
+ /**
352
+ * @type {HTMLButtonElement}
353
+ * @private
354
+ */
355
+ _popBtn;
356
+
357
+ /**
358
+ * @type {HTMLElement}
359
+ * @private
360
+ */
361
+ _countsEl;
362
+
363
+ /**
364
+ * @type {HTMLElement}
365
+ * @private
366
+ */
367
+ _pausedEl;
368
+
369
+ /**
370
+ * @type {HTMLElement}
371
+ * @private
372
+ */
373
+ _pathEl;
374
+
375
+ /**
376
+ * What the view is doing while it is picked, flown or orbited.
377
+ *
378
+ * @type {HTMLElement}
379
+ * @private
380
+ */
381
+ _modeEl;
382
+
383
+ /**
384
+ * @type {HierarchyView}
385
+ * @private
386
+ */
387
+ _hierarchy;
388
+
389
+ /**
390
+ * @type {PropertyView}
391
+ * @private
392
+ */
393
+ _properties;
394
+
395
+ /**
396
+ * @type {WireRenderer}
397
+ * @private
398
+ */
399
+ _wire;
400
+
401
+ /** @private */
402
+ _nextListRefresh = 0;
403
+
404
+ /** @private */
405
+ _nextPropertyRefresh = 0;
406
+
407
+ /**
408
+ * @type {'hierarchy'|'cameras'|'assets'|'passes'|'targets'|'textures'|'meshes'|'materials'|'scripts'|'memory'|'shaders'|'physics'}
409
+ * @private
410
+ */
411
+ _tab = 'hierarchy';
412
+
413
+ /**
414
+ * @type {FrameSnapshot|null}
415
+ * @private
416
+ */
417
+ _frame = null;
418
+
419
+ /** @private */
420
+ _frozen = false;
421
+
422
+ /** @private */
423
+ _gpuWasEnabled = false;
424
+
425
+ /**
426
+ * @type {Record<string, HTMLElement>}
427
+ * @private
428
+ */
429
+ _tabButtons = {};
430
+
431
+ /**
432
+ * @type {Record<string, HTMLElement>}
433
+ * @private
434
+ */
435
+ _panels = {};
436
+
437
+ /**
438
+ * @type {ListView}
439
+ * @private
440
+ */
441
+ _passList;
442
+
443
+ /**
444
+ * @type {ListView}
445
+ * @private
446
+ */
447
+ _targetList;
448
+
449
+ /**
450
+ * @type {ListView}
451
+ * @private
452
+ */
453
+ _bodyList;
454
+
455
+ /**
456
+ * Draws the selected render target's texture over the canvas, straight from the GPU.
457
+ *
458
+ * @type {TextureRenderer}
459
+ * @private
460
+ */
461
+ _textures;
462
+
463
+ /**
464
+ * @type {HTMLInputElement}
465
+ * @private
466
+ */
467
+ _previewToggle;
468
+
469
+ /**
470
+ * @type {HTMLSelectElement}
471
+ * @private
472
+ */
473
+ _previewAttachment;
474
+
475
+ /**
476
+ * @type {HTMLSelectElement}
477
+ * @private
478
+ */
479
+ _previewChannels;
480
+
481
+ /**
482
+ * @type {HTMLElement}
483
+ * @private
484
+ */
485
+ _previewNote;
486
+
487
+ /**
488
+ * The attachment keys the selector currently offers, to rebuild it only when they change.
489
+ *
490
+ * @private
491
+ */
492
+ _previewKeys = '';
493
+
494
+ /**
495
+ * @type {ListView}
496
+ * @private
497
+ */
498
+ _textureList;
499
+
500
+ /**
501
+ * @type {ListView}
502
+ * @private
503
+ */
504
+ _shaderList;
505
+
506
+ /**
507
+ * @type {ListView}
508
+ * @private
509
+ */
510
+ _assetList;
511
+
512
+ /**
513
+ * @type {ListView}
514
+ * @private
515
+ */
516
+ _bufferList;
517
+
518
+ /**
519
+ * @type {ListView}
520
+ * @private
521
+ */
522
+ _meshList;
523
+
524
+ /**
525
+ * @type {HTMLElement}
526
+ * @private
527
+ */
528
+ _meshNote;
529
+
530
+ /**
531
+ * @type {ListView}
532
+ * @private
533
+ */
534
+ _materialList;
535
+
536
+ /**
537
+ * @type {ListView}
538
+ * @private
539
+ */
540
+ _scriptList;
541
+
542
+ /**
543
+ * @type {ListView}
544
+ * @private
545
+ */
546
+ _cameraList;
547
+
548
+ /**
549
+ * The render mode applied from the Cameras tab.
550
+ *
551
+ * @type {HTMLSelectElement}
552
+ * @private
553
+ */
554
+ _renderMode;
555
+
556
+ /**
557
+ * Whether the render mode applies to the selected camera or to all of them.
558
+ *
559
+ * @type {HTMLSelectElement}
560
+ * @private
561
+ */
562
+ _renderScope;
563
+
564
+ /**
565
+ * The cameras last listed in the render mode scope, to rebuild it only when they change.
566
+ *
567
+ * @type {string}
568
+ * @private
569
+ */
570
+ _scopeSignature = '';
571
+
572
+ /**
573
+ * @type {HTMLInputElement}
574
+ * @private
575
+ */
576
+ _wireframeToggle;
577
+
578
+ /**
579
+ * Ends the render mode changes and wireframe.
580
+ *
581
+ * @type {HTMLButtonElement}
582
+ * @private
583
+ */
584
+ _resetViewBtn;
585
+
586
+ /**
587
+ * The shader pass each camera the panel changed had before, to put back.
588
+ *
589
+ * @type {Map<CameraComponent, string|null>}
590
+ * @private
591
+ */
592
+ _changedPasses = new Map();
593
+
594
+ /** @private */
595
+ _wireframe = new WireframeMode();
596
+
597
+ /**
598
+ * @type {ViewportPicker|null}
599
+ * @private
600
+ */
601
+ _picker = null;
602
+
603
+ /**
604
+ * The pointer events taken while picking, or while waiting for a click choosing the camera to
605
+ * fly, null otherwise.
606
+ *
607
+ * @type {CanvasCapture|null}
608
+ * @private
609
+ */
610
+ _canvasCapture = null;
611
+
612
+ /**
613
+ * What the canvas capture is for.
614
+ *
615
+ * @type {'pick'|'choose'|null}
616
+ * @private
617
+ */
618
+ _canvasMode = null;
619
+
620
+ /**
621
+ * The entity under the pointer while picking.
622
+ *
623
+ * @type {Entity|null}
624
+ * @private
625
+ */
626
+ _hovered = null;
627
+
628
+ /**
629
+ * The camera driven by Fly or Orbit, while one is.
630
+ *
631
+ * @type {CameraFly|CameraOrbit|null}
632
+ * @private
633
+ */
634
+ _fly = null;
635
+
636
+ /**
637
+ * Which of Fly and Orbit waits for the view of a camera to be clicked, while one does.
638
+ *
639
+ * @type {'fly'|'orbit'}
640
+ * @private
641
+ */
642
+ _chooseKind = 'fly';
643
+
644
+ /**
645
+ * @type {HTMLButtonElement}
646
+ * @private
647
+ */
648
+ _pickBtn;
649
+
650
+ /**
651
+ * @type {HTMLButtonElement}
652
+ * @private
653
+ */
654
+ _flyBtn;
655
+
656
+ /**
657
+ * @type {HTMLButtonElement}
658
+ * @private
659
+ */
660
+ _orbitBtn;
661
+
662
+ /** @private */
663
+ _hoverColor = new Color(0.35, 0.8, 1);
664
+
665
+ /**
666
+ * The latest pointer position to pick under while hovering, null once it has been picked.
667
+ *
668
+ * @type {number[]|null}
669
+ * @private
670
+ */
671
+ _hoverPoint = null;
672
+
673
+ /**
674
+ * @type {HTMLInputElement}
675
+ * @private
676
+ */
677
+ _passPreviewToggle;
678
+
679
+ /**
680
+ * @type {HTMLInputElement}
681
+ * @private
682
+ */
683
+ _debugFrameToggle;
684
+
685
+ /**
686
+ * @type {HTMLElement}
687
+ * @private
688
+ */
689
+ _passNote;
690
+
691
+ /**
692
+ * @type {HTMLElement}
693
+ * @private
694
+ */
695
+ _debugEl;
696
+
697
+ /**
698
+ * The debug frame while it is on: the layer step it stops in, by its list key, the draw it stops
699
+ * at within that step's list, and the instance drawn last, which keeps the choice when the sort
700
+ * order shifts. Null while it is off.
701
+ *
702
+ * @type {{ stepKey: string|null, index: number, instance: MeshInstance|null, wasPaused: boolean }|null}
703
+ * @private
704
+ */
705
+ _debugFrame = null;
706
+
707
+ /**
708
+ * The link or row the pointer is over, with a function reading its current target, so a texture
709
+ * or render target can preview while hovered.
710
+ *
711
+ * @type {{ el: HTMLElement, target: () => * }|null}
712
+ * @private
713
+ */
714
+ _hoverLink = null;
715
+
716
+ /**
717
+ * The page each forward pass layer step shows, by pass row key and step, kept across refreshes.
718
+ *
719
+ * @type {Map<string, number>}
720
+ * @private
721
+ */
722
+ _instancePages = new Map();
723
+
724
+ /**
725
+ * @type {HTMLSelectElement}
726
+ * @private
727
+ */
728
+ _bufferKind;
729
+
730
+ /**
731
+ * @type {HTMLElement}
732
+ * @private
733
+ */
734
+ _memoryNote;
735
+
736
+ /**
737
+ * Model builder for the property view when a buffer is selected.
738
+ *
739
+ * @param {*} buffer - The buffer.
740
+ * @returns {PropertySection[]} The sections.
741
+ * @private
742
+ */
743
+ _bufferModel = buffer => buildBufferModel(buffer, this._context());
744
+
745
+ /**
746
+ * Model builder for the property view when a mesh is selected.
747
+ *
748
+ * @param {Mesh} mesh - The mesh.
749
+ * @returns {PropertySection[]} The sections.
750
+ * @private
751
+ */
752
+ _meshModel = mesh => buildMeshModel(mesh, this._context());
753
+
754
+ /**
755
+ * Model builder for the property view when a material is selected.
756
+ *
757
+ * @param {Material} material - The material.
758
+ * @returns {PropertySection[]} The sections.
759
+ * @private
760
+ */
761
+ _materialModel = material => buildMaterialModel(material, this._context());
762
+
763
+ /**
764
+ * Model builder for the property view when a camera is selected.
765
+ *
766
+ * @param {CameraComponent} camera - The camera.
767
+ * @returns {PropertySection[]} The sections.
768
+ * @private
769
+ */
770
+ _cameraModel = camera => buildCameraModel(camera, {
771
+ app: this._app,
772
+ cameraActions: { fly: target => this._startFly(target), flying: this._fly?.camera ?? null }
773
+ });
774
+
775
+ /**
776
+ * Model builder for the property view when a script class is selected.
777
+ *
778
+ * @param {Function} cls - The script class.
779
+ * @returns {PropertySection[]} The sections.
780
+ * @private
781
+ */
782
+ _scriptModel = cls => buildScriptModel(cls, this._context());
783
+
784
+ /**
785
+ * Model builder for the property view when a shader is selected, followed by the materials that
786
+ * compiled it.
787
+ *
788
+ * @param {Shader} shader - The shader.
789
+ * @returns {PropertySection[]} The sections.
790
+ * @private
791
+ */
792
+ _shaderModel = shader => [...buildShaderModel(shader), usedByMaterialsSection(materialsUsingShader(this._app, shader))];
793
+
794
+ /**
795
+ * @type {HTMLSelectElement}
796
+ * @private
797
+ */
798
+ _assetSort;
799
+
800
+ /**
801
+ * Model builder for the property view when an asset is selected, with what uses its resource
802
+ * directly added to the components referencing it.
803
+ *
804
+ * @param {Asset} asset - The asset.
805
+ * @returns {PropertySection[]} The sections.
806
+ * @private
807
+ */
808
+ _assetModel = (asset) => {
809
+ const sections = buildAssetModel(asset, this._context());
810
+ const users = sections.find(section => section.key === 'users');
811
+ if (users) pushResourceUsage(users, asset, this._app);
812
+ return sections;
813
+ };
814
+
815
+ /**
816
+ * @type {HTMLInputElement}
817
+ * @private
818
+ */
819
+ _texturePreviewToggle;
820
+
821
+ /**
822
+ * @type {HTMLSelectElement}
823
+ * @private
824
+ */
825
+ _textureChannels;
826
+
827
+ /**
828
+ * @type {HTMLElement}
829
+ * @private
830
+ */
831
+ _textureNote;
832
+
833
+ /**
834
+ * Model builder for the property view when a texture is selected, followed by the materials
835
+ * sampling it.
836
+ *
837
+ * @param {Texture} texture - The texture.
838
+ * @returns {PropertySection[]} The sections.
839
+ * @private
840
+ */
841
+ _textureModel = texture => [
842
+ ...buildTextureModel(texture, this._context()),
843
+ usedByMaterialsSection(materialsUsingTexture(this._app, texture))
844
+ ];
845
+
846
+ /**
847
+ * @type {HTMLInputElement}
848
+ * @private
849
+ */
850
+ _gpuToggle;
851
+
852
+ /**
853
+ * @type {HTMLInputElement}
854
+ * @private
855
+ */
856
+ _freezeToggle;
857
+
858
+ /**
859
+ * @type {AmmoDebugDraw|null}
860
+ * @private
861
+ */
862
+ _physics = null;
863
+
864
+ /**
865
+ * @type {HTMLInputElement}
866
+ * @private
867
+ */
868
+ _drawToggle;
869
+
870
+ /**
871
+ * @type {HTMLInputElement}
872
+ * @private
873
+ */
874
+ _depthToggle;
875
+
876
+ /**
877
+ * @type {HTMLInputElement}
878
+ * @private
879
+ */
880
+ _rangeInput;
881
+
882
+ /**
883
+ * The checkbox of each boolean physics draw option, by option name.
884
+ *
885
+ * @type {Record<string, HTMLInputElement>}
886
+ * @private
887
+ */
888
+ _physicsToggles = {};
889
+
890
+ /**
891
+ * @type {HTMLElement}
892
+ * @private
893
+ */
894
+ _physicsNote;
895
+
896
+ /**
897
+ * The bar holding the options governed by the Draw switch.
898
+ *
899
+ * @type {HTMLElement}
900
+ * @private
901
+ */
902
+ _physicsOptionsBar;
903
+
904
+ /**
905
+ * Bodies excluded from the physics drawing, with the native body the exclusion was applied to,
906
+ * or null while the entity has no native body yet.
907
+ *
908
+ * @type {Map<Entity, any>}
909
+ * @private
910
+ */
911
+ _hiddenBodies = new Map();
912
+
913
+ /**
914
+ * Entity paths of excluded bodies restored from storage, waiting for the entities to exist.
915
+ *
916
+ * @type {Set<string>}
917
+ * @private
918
+ */
919
+ _pendingHiddenPaths = new Set();
920
+
921
+ /**
922
+ * @type {string|null}
923
+ * @private
924
+ */
925
+ _storageKey = 'pc-inspector';
926
+
927
+ /**
928
+ * True while the panel is being built and restored, when nothing should be saved.
929
+ *
930
+ * @private
931
+ */
932
+ _restoring = true;
933
+
934
+ /**
935
+ * Model builder for the property view when a pass is selected.
936
+ *
937
+ * @param {FramePass} pass - The pass.
938
+ * @returns {PropertySection[]} The sections.
939
+ * @private
940
+ */
941
+ _passModel = pass => buildPassModel(pass, this._context());
942
+
943
+ /**
944
+ * Model builder for the property view when a layer step of a forward pass is selected.
945
+ *
946
+ * @param {LayerStepSelection} selection - The step and its pass.
947
+ * @returns {PropertySection[]} The sections.
948
+ * @private
949
+ */
950
+ _stepModel = selection => buildStepModel(selection, this._context());
951
+
952
+ /**
953
+ * @param {*} item - What a row of the pass list selects: a pass, or one of its layer steps.
954
+ * @returns {(subject: *) => PropertySection[]} The model builder that shows it.
955
+ * @private
956
+ */
957
+ _passListModel(item) {
958
+ return item instanceof LayerStepSelection ? this._stepModel : this._passModel;
959
+ }
960
+
961
+ /**
962
+ * Model builder for the property view when a render target is selected.
963
+ *
964
+ * @param {RenderTarget} rt - The render target.
965
+ * @returns {PropertySection[]} The sections.
966
+ * @private
967
+ */
968
+ _targetModel = rt => buildRenderTargetModel(rt, this._context());
969
+
970
+ /**
971
+ * Creates the inspector and shows its panel. The panel is appended to the document body and
972
+ * follows the app until {@link destroy} is called, or the app is destroyed.
973
+ *
974
+ * @param {AppBase} app - The app to inspect.
975
+ * @param {InspectorOptions} [options] - The options.
976
+ * @example
977
+ * const inspector = new Inspector(app, { dock: 'left', width: 480 });
978
+ */
979
+ constructor(app, options = {}) {
980
+ this._app = app;
981
+
982
+ if (options.toggleKey !== undefined) this._toggleKey = options.toggleKey;
983
+ if (options.pauseKey !== undefined) this._pauseKey = options.pauseKey;
984
+ if (options.stepKey !== undefined) this._stepKey = options.stepKey;
985
+ this._lockedNode = options.lockedNode ?? null;
986
+ this.onVisibleChange = options.onVisibleChange ?? null;
987
+ this._visible = options.visible ?? true;
988
+ this._dock = options.dock === 'left' ? 'left' : 'right';
989
+ this._width = Math.max(240, Math.min(1600, options.width ?? 420));
990
+ this._top = Math.max(0, options.top ?? 0);
991
+
992
+ this._wire = new WireRenderer(app);
993
+ this._textures = new TextureRenderer(app);
994
+ this._buildDom();
995
+ this._hierarchy.setRoot(app.root);
996
+ this._gpuWasEnabled = !!app.graphicsDevice.gpuProfiler?.enabled;
997
+ this._physics = new AmmoDebugDraw(app);
998
+ this._physicsDrawOptions = { wireframe: true };
999
+ this._physicsDraw = false;
1000
+ this._setTab('hierarchy');
1001
+ this._storageKey = options.storageKey === undefined ? 'pc-inspector' : options.storageKey;
1002
+ this._loadSettings();
1003
+ this._applyLayout();
1004
+ this._applyVisibility();
1005
+ this._applyPauseState();
1006
+ this._refresh();
1007
+ this._restoring = false;
1008
+
1009
+ window.addEventListener('keydown', this._onKeyDown);
1010
+ // the app fires 'update' after every component system has updated, so the physics step of
1011
+ // the frame is done by the time the world is drawn
1012
+ app.on('update', this._onUpdate, this);
1013
+ app.on('destroy', this.destroy, this);
1014
+ }
1015
+
1016
+ /**
1017
+ * Removes the panel, releases every hook into the app and restores anything the inspector
1018
+ * changed: the time scale while paused, the GPU profiler, the physics debug drawer.
1019
+ */
1020
+ destroy() {
1021
+ if (this._destroyed) return;
1022
+ this._destroyed = true;
1023
+
1024
+ const app = this._app;
1025
+ app.off('update', this._onUpdate, this);
1026
+ app.off('destroy', this.destroy, this);
1027
+ window.removeEventListener('keydown', this._onKeyDown);
1028
+ this._setDebugFrame(false);
1029
+ this._endViewportModes();
1030
+ this._picker?.destroy();
1031
+ this._picker = null;
1032
+
1033
+ this.paused = false;
1034
+ const profiler = app.graphicsDevice?.gpuProfiler;
1035
+ if (profiler) profiler.enabled = this._gpuWasEnabled;
1036
+ this._pruneHiddenBodies();
1037
+ this._physics?.detach();
1038
+ this._physics = null;
1039
+ this._hiddenBodies.clear();
1040
+
1041
+ if (this._popup) this._dockBack();
1042
+ this._textures.destroy();
1043
+ this._host?.remove();
1044
+ this._host = null;
1045
+ }
1046
+
1047
+ /**
1048
+ * Whether the panel is shown. Toggled by the toggle key.
1049
+ *
1050
+ * @type {boolean}
1051
+ */
1052
+ set visible(value) {
1053
+ value = !!value;
1054
+ // a hidden panel leaves nothing on screen saying the frame is cut short
1055
+ if (!value && this._debugFrame) this._setDebugFrame(false);
1056
+ // nor that the view is being picked, flown, or drawn differently
1057
+ if (!value) this._endViewportModes();
1058
+ const changed = value !== this._visible;
1059
+ this._visible = value;
1060
+ if (this._host) {
1061
+ if (!value && this._popup) this._dockBack();
1062
+ this._applyVisibility();
1063
+ if (value) this._refresh();
1064
+ }
1065
+ if (changed) this.onVisibleChange?.(value);
1066
+ }
1067
+
1068
+ get visible() {
1069
+ return this._visible;
1070
+ }
1071
+
1072
+ /**
1073
+ * Whether the app is paused. Pausing sets {@link AppBase#timeScale} to zero and suspends the
1074
+ * sound manager; resuming restores the time scale that was in effect.
1075
+ *
1076
+ * @type {boolean}
1077
+ */
1078
+ set paused(value) {
1079
+ value = !!value;
1080
+ if (value === this._paused) return;
1081
+ this._paused = value;
1082
+
1083
+ const app = this._app;
1084
+ if (value) {
1085
+ this._savedTimeScale = app.timeScale;
1086
+ app.timeScale = 0;
1087
+ app.soundManager?.suspend();
1088
+ } else {
1089
+ app.timeScale = this._savedTimeScale;
1090
+ app.soundManager?.resume();
1091
+ }
1092
+
1093
+ this._applyPauseState();
1094
+ if (value) this._refresh();
1095
+ }
1096
+
1097
+ get paused() {
1098
+ return this._paused;
1099
+ }
1100
+
1101
+ /**
1102
+ * Whether the physics world is drawn over the scene while the panel is shown: the Draw checkbox
1103
+ * of the Physics tab. Hiding the panel suspends the drawing; showing it again resumes it.
1104
+ *
1105
+ * @type {boolean}
1106
+ * @private
1107
+ */
1108
+ set _physicsDraw(value) {
1109
+ this._drawToggle.checked = !!value;
1110
+ this._applyPhysicsSettings();
1111
+ }
1112
+
1113
+ /**
1114
+ * @returns {boolean} Whether the physics world is drawn.
1115
+ * @private
1116
+ */
1117
+ get _physicsDraw() {
1118
+ return this._drawToggle.checked;
1119
+ }
1120
+
1121
+ /**
1122
+ * Which parts of the physics world are drawn, mirroring the checkboxes of the Physics tab.
1123
+ * Assigning a partial object changes only the options it names.
1124
+ *
1125
+ * @type {InspectorPhysicsDrawOptions}
1126
+ * @private
1127
+ */
1128
+ set _physicsDrawOptions(value) {
1129
+ for (const key of Object.keys(PHYSICS_FLAGS)) {
1130
+ if (value[key] !== undefined) this._physicsToggles[key].checked = !!value[key];
1131
+ }
1132
+ if (value.depthTest !== undefined) this._depthToggle.checked = !!value.depthTest;
1133
+ if (value.range !== undefined) this._rangeInput.value = String(Math.max(0, value.range || 0));
1134
+ this._applyPhysicsSettings();
1135
+ }
1136
+
1137
+ /**
1138
+ * @returns {InspectorPhysicsDrawOptions} Which parts of the physics world are drawn.
1139
+ * @private
1140
+ */
1141
+ get _physicsDrawOptions() {
1142
+ /** @type {InspectorPhysicsDrawOptions} */
1143
+ const options = {};
1144
+ for (const key of Object.keys(PHYSICS_FLAGS)) {
1145
+ options[key] = this._physicsToggles[key].checked;
1146
+ }
1147
+ options.depthTest = this._depthToggle.checked;
1148
+ options.range = Math.max(0, parseFloat(this._rangeInput.value) || 0);
1149
+ return options;
1150
+ }
1151
+
1152
+ /**
1153
+ * Advances the app by one frame. Only meaningful while paused.
1154
+ */
1155
+ step() {
1156
+ if (!this._paused) return;
1157
+ const app = this._app;
1158
+ app.timeScale = this._savedTimeScale;
1159
+ app.once('frameend', () => {
1160
+ if (this._paused) app.timeScale = 0;
1161
+ });
1162
+ }
1163
+
1164
+ /**
1165
+ * Refreshes the active list and the property view immediately.
1166
+ *
1167
+ * @private
1168
+ */
1169
+ _refresh() {
1170
+ if (!this._host) return;
1171
+ this._refreshLists(true);
1172
+ this._properties.refresh();
1173
+ }
1174
+
1175
+ /**
1176
+ * Moves the panel into its own browser window, leaving the canvas unobscured. Must be called
1177
+ * from a user gesture, or the browser blocks the window.
1178
+ *
1179
+ * @private
1180
+ */
1181
+ _popOut() {
1182
+ if (this._popup) {
1183
+ this._popup.focus();
1184
+ return;
1185
+ }
1186
+
1187
+ const height = Math.max(480, Math.round(window.innerHeight * 0.9));
1188
+ const popup = window.open('', 'pc-inspector', `popup=yes,width=${this._width},height=${height}`);
1189
+ if (!popup) {
1190
+ // blocked by the browser: say so on the button rather than silently doing nothing
1191
+ this._popBtn.classList.add('pci-warn');
1192
+ setTip(this._popBtn, 'The browser blocked the window. Allow pop-ups for this page to pop the panel out');
1193
+ setTimeout(() => this._applyLayout(), 4000);
1194
+ return;
1195
+ }
1196
+
1197
+ const doc = popup.document;
1198
+ doc.title = 'Inspector';
1199
+ doc.documentElement.style.height = '100%';
1200
+ doc.body.style.cssText = 'margin: 0; height: 100%; background: #182022; overflow: hidden;';
1201
+ doc.body.appendChild(doc.adoptNode(this._host));
1202
+
1203
+ popup.addEventListener('pagehide', this._onPopupHide);
1204
+ popup.addEventListener('keydown', this._onKeyDown);
1205
+
1206
+ this._popup = popup;
1207
+ this._applyLayout();
1208
+ }
1209
+
1210
+ /**
1211
+ * Brings a popped-out panel back into the page and closes its window.
1212
+ *
1213
+ * @private
1214
+ */
1215
+ _dockBack() {
1216
+ const popup = this._popup;
1217
+ if (!popup) return;
1218
+ this._popup = null;
1219
+
1220
+ popup.removeEventListener('pagehide', this._onPopupHide);
1221
+ popup.removeEventListener('keydown', this._onKeyDown);
1222
+
1223
+ try {
1224
+ document.body.appendChild(document.adoptNode(this._host));
1225
+ } catch {
1226
+ // the document that held the panel is gone, so the panel is too: build it anew
1227
+ const selected = this._selected;
1228
+ this._host.remove?.();
1229
+ this._buildDom();
1230
+ this._hierarchy.setRoot(this._app.root);
1231
+ if (selected) this._hierarchy.select(selected);
1232
+ this._applyPauseState();
1233
+ }
1234
+
1235
+ if (!popup.closed) popup.close();
1236
+ this._applyLayout();
1237
+ this._applyVisibility();
1238
+ }
1239
+
1240
+ /**
1241
+ * @param {number} dt - The frame delta, scaled by the app time scale.
1242
+ * @private
1243
+ */
1244
+ _onUpdate(dt) {
1245
+ this._drawPhysics();
1246
+
1247
+ // the user closed the pop-out window: bring the panel home
1248
+ if (this._popup?.closed) this._dockBack();
1249
+
1250
+ if (!this._visible) return;
1251
+
1252
+ // wall clock, as the frame delta is zero while paused
1253
+ const now = performance.now();
1254
+ if (now >= this._nextListRefresh) {
1255
+ this._nextListRefresh = now + LIST_INTERVAL * 1000;
1256
+ this._refreshLists(true);
1257
+ // mesh instances the app added since are drawn in wireframe too
1258
+ if (this._wireframeToggle.checked) this._wireframe.apply(this._app);
1259
+ }
1260
+
1261
+ if (this._canvasMode === 'pick' && this._hovered) this._drawHighlight(this._hovered, this._hoverColor);
1262
+ if (this._tab === 'cameras' && this._cameraList.selected && this._cameraList.selected !== this._fly?.camera) {
1263
+ this._drawHighlight(this._cameraList.selected.entity);
1264
+ }
1265
+ this._updateModeStatus();
1266
+ if (now >= this._nextPropertyRefresh) {
1267
+ this._nextPropertyRefresh = now + PROPERTY_INTERVAL * 1000;
1268
+ this._properties.refresh();
1269
+ }
1270
+
1271
+ if (this._tab === 'hierarchy' && this._selected) {
1272
+ this._drawHighlight(this._selected);
1273
+ } else if (this._tab === 'physics') {
1274
+ const entity = this._bodyList.selected;
1275
+ if (entity) {
1276
+ this._wire.color.copy(this._highlightColor);
1277
+ this._wire.depthTest = false;
1278
+ const jointDrawn = drawJoint(this._wire, entity, this._highlightSize(entity));
1279
+ const shapeDrawn = drawCollisionShape(this._wire, entity);
1280
+ if (!jointDrawn && !shapeDrawn) this._drawHighlight(entity);
1281
+ }
1282
+ }
1283
+
1284
+ // a hovered texture or render target takes the place of the tab's own preview for as long as
1285
+ // it is hovered
1286
+ const hovered = this._hoveredPreview();
1287
+ if (hovered) {
1288
+ this._drawPreviewQuad(hovered.texture, hovered.label, hovered.depth, hovered.channels, 'corner', hovered.renderTarget);
1289
+ } else if (this._tab === 'targets') {
1290
+ this._drawTargetPreview();
1291
+ } else if (this._tab === 'textures') {
1292
+ this._drawTexturePreview();
1293
+ } else if (this._tab === 'passes') {
1294
+ this._drawPassPreview();
1295
+ }
1296
+
1297
+ // written every frame, as the forward passes it matches are rebuilt every frame
1298
+ if (this._debugFrame) this._applyDebugFrame();
1299
+ }
1300
+
1301
+ /**
1302
+ * Draws the physics world for this frame. Runs from the app's update event, which fires after
1303
+ * the rigid body system has stepped, so the drawn world matches the frame being rendered.
1304
+ *
1305
+ * @private
1306
+ */
1307
+ _drawPhysics() {
1308
+ const physics = this._physics;
1309
+ if (!physics) return;
1310
+
1311
+ // hiding the panel switches the drawing off with it; while disabled the drawer also stops
1312
+ // Bullet from reporting contacts, so nothing accumulates unseen
1313
+ physics.enabled = this._visible && this._drawToggle.checked;
1314
+
1315
+ if (physics.range > 0) {
1316
+ const camera = this._app.systems.camera?.cameras[0];
1317
+ physics.center = camera ? camera.entity.getPosition() : null;
1318
+ }
1319
+ this._pruneHiddenBodies();
1320
+ physics.update();
1321
+ }
1322
+
1323
+ /**
1324
+ * Builds the panel inside a shadow root on a host element appended to the document body.
1325
+ *
1326
+ * @private
1327
+ */
1328
+ _buildDom() {
1329
+ const host = el('div', 'pc-inspector');
1330
+ const shadow = host.attachShadow({ mode: 'open' });
1331
+
1332
+ const style = document.createElement('style');
1333
+ style.textContent = styles;
1334
+
1335
+ const panel = el('div', 'pci-panel');
1336
+
1337
+ // toolbar
1338
+ const toolbar = el('div', 'pci-toolbar');
1339
+ const title = el('span', 'pci-title', 'Inspector');
1340
+ this._pauseBtn = iconButton('pause', 'Pause');
1341
+ this._stepBtn = iconButton('step', 'Step');
1342
+ this._pickBtn = iconButton('pick', 'Pick');
1343
+ this._flyBtn = iconButton('fly', 'Fly');
1344
+ this._orbitBtn = iconButton('orbit', 'Orbit');
1345
+ this._orbitBtn.disabled = true;
1346
+ setTip(this._pickBtn, 'Pick an entity in the view: hover to see it outlined, click to select it. Esc stops');
1347
+ setTip(this._flyBtn, 'Fly the camera of the view with the mouse and WASD, without moving the app\'s own camera. Esc stops');
1348
+ 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');
1349
+ this._popBtn = iconButton('popout', 'Pop out');
1350
+ const closeBtn = iconButton('close', 'Hide');
1351
+ const toggleLabel = Inspector._keyLabel(this._toggleKey);
1352
+ setTip(closeBtn, `Hide the panel${toggleLabel ? `. Press ${toggleLabel} to show it again` : ''}`);
1353
+ toolbar.append(
1354
+ title,
1355
+ this._pauseBtn, this._stepBtn, el('span', 'pci-sep'),
1356
+ this._pickBtn, this._flyBtn, this._orbitBtn,
1357
+ el('span', 'pci-spacer'),
1358
+ this._popBtn, closeBtn
1359
+ );
1360
+
1361
+ this._pauseBtn.addEventListener('click', () => {
1362
+ this.paused = !this._paused;
1363
+ });
1364
+ this._stepBtn.addEventListener('click', () => this.step());
1365
+ this._pickBtn.addEventListener('click', () => this._setPicking(this._canvasMode !== 'pick'));
1366
+ this._flyBtn.addEventListener('click', () => this._toggleDrive('fly'));
1367
+ this._orbitBtn.addEventListener('click', () => this._toggleDrive('orbit'));
1368
+ this._popBtn.addEventListener('click', () => {
1369
+ if (this._popup) this._dockBack();
1370
+ else this._popOut();
1371
+ });
1372
+ closeBtn.addEventListener('click', () => {
1373
+ this.visible = false;
1374
+ });
1375
+
1376
+ // body: a tabbed list over the properties, with a draggable splitter
1377
+ const body = el('div', 'pci-body');
1378
+ this._hierarchyEl = el('div', 'pci-hierarchy');
1379
+
1380
+ const tabs = el('div', 'pci-tabs');
1381
+ this._tabButtons = {};
1382
+ const tabList = [
1383
+ ['hierarchy', 'Hierarchy'], ['cameras', 'Cameras'], ['assets', 'Assets'], ['passes', 'Frame graph'],
1384
+ ['targets', 'Render targets'], ['textures', 'Textures'], ['meshes', 'Meshes'], ['materials', 'Materials'], ['scripts', 'Scripts'], ['memory', 'Memory'],
1385
+ ['shaders', 'Shaders'], ['physics', 'Physics']
1386
+ ];
1387
+ for (const [id, label] of tabList) {
1388
+ const tab = el('button', 'pci-tab', label);
1389
+ setTip(tab, TAB_TIPS[id]);
1390
+ tab.addEventListener('click', () => this._setTab(/** @type {any} */ (id)));
1391
+ tabs.appendChild(tab);
1392
+ this._tabButtons[id] = tab;
1393
+ }
1394
+
1395
+ const filter = el('div', 'pci-filter');
1396
+ // what the hierarchy filter matches, shown on that tab only: the lists match names
1397
+ this._filterBy = /** @type {HTMLSelectElement} */ (document.createElement('select'));
1398
+ this._filterBy.className = 'pci-select';
1399
+ this._fillSelect(this._filterBy, [['name', 'entity name'], ['component', 'component'], ['script', 'script']]);
1400
+ setTip(this._filterBy, 'What the filter matches in the hierarchy: entity names, the types of their components,\nor the names of their scripts');
1401
+ this._filterInput = /** @type {HTMLInputElement} */ (document.createElement('input'));
1402
+ this._filterInput.placeholder = 'Filter by name…';
1403
+ setTip(this._filterInput, 'Show only the items of this tab whose name contains the text');
1404
+ this._filterInput.spellcheck = false;
1405
+ // the component types or script names in the scene, offered while filtering by them
1406
+ this._filterSuggestions = /** @type {HTMLDataListElement} */ (document.createElement('datalist'));
1407
+ this._filterSuggestions.id = 'pci-filter-suggestions';
1408
+ this._filterInput.setAttribute('list', this._filterSuggestions.id);
1409
+ filter.append(this._filterBy, this._filterInput, this._filterSuggestions);
1410
+
1411
+ const tree = el('div', 'pci-tree');
1412
+
1413
+ const passPanel = el('div', 'pci-listpanel');
1414
+ const passBar = el('div', 'pci-subbar');
1415
+ this._gpuToggle = this._makeToggle(passBar, 'GPU timings',
1416
+ 'Enable the GPU profiler and show the time each pass takes on the GPU. Measuring adds a little overhead');
1417
+ this._freezeToggle = this._makeToggle(passBar, 'Freeze',
1418
+ 'Keep showing the frame captured now while the app runs on, to read it at leisure. Pause stops the app itself');
1419
+ this._passPreviewToggle = this._makeToggle(passBar, 'Preview',
1420
+ 'Draw the selected pass\'s render target over the free part of the viewport');
1421
+ this._passPreviewToggle.checked = true;
1422
+ this._debugFrameToggle = this._makeToggle(passBar, 'Debug frame',
1423
+ 'Pause and draw the selected forward pass only up to a chosen draw, stepping with the arrow keys');
1424
+ if (!this._app.renderer?.debugDrawLimitSupported) {
1425
+ this._debugFrameToggle.disabled = true;
1426
+ setTip(this._debugFrameToggle.parentElement, 'Stepping through draws needs the debug engine');
1427
+ }
1428
+ this._passNote = el('div', 'pci-note pci-note-info');
1429
+ this._passNote.style.display = 'none';
1430
+ const passList = el('div', 'pci-list');
1431
+ passPanel.append(passBar, this._passNote, passList);
1432
+
1433
+ // render targets: a live preview of the selected target, drawn over the canvas
1434
+ const targetPanel = el('div', 'pci-listpanel');
1435
+ const targetBar = el('div', 'pci-subbar');
1436
+ this._previewToggle = this._makeToggle(targetBar, 'Preview',
1437
+ 'Draw the selected target\'s texture in the corner of the viewport, sampled on the GPU every frame');
1438
+ this._previewToggle.checked = true;
1439
+ this._previewAttachment = this._makeSelect(targetBar, 'Attachment', [['color0', 'color']],
1440
+ 'Which texture of the render target to preview');
1441
+ this._previewChannels = this._makeSelect(targetBar, 'Channels', [
1442
+ ['rgb', 'color'], ['rrr', 'red'], ['ggg', 'green'], ['bbb', 'blue'], ['aaa', 'alpha']
1443
+ ], CHANNELS_TIP);
1444
+ this._previewNote = el('div', 'pci-note pci-note-info');
1445
+ this._previewNote.style.display = 'none';
1446
+ const targetList = el('div', 'pci-list');
1447
+ targetPanel.append(targetBar, this._previewNote, targetList);
1448
+
1449
+ // textures: the same live preview for the selected texture
1450
+ const texturePanel = el('div', 'pci-listpanel');
1451
+ const textureBar = el('div', 'pci-subbar');
1452
+ this._texturePreviewToggle = this._makeToggle(textureBar, 'Preview',
1453
+ 'Draw the selected texture in the corner of the viewport, sampled on the GPU every frame');
1454
+ this._texturePreviewToggle.checked = true;
1455
+ this._textureChannels = this._makeSelect(textureBar, 'Channels', [
1456
+ ['rgb', 'color'], ['rrr', 'red'], ['ggg', 'green'], ['bbb', 'blue'], ['aaa', 'alpha']
1457
+ ], CHANNELS_TIP);
1458
+ this._textureNote = el('div', 'pci-note pci-note-info');
1459
+ this._textureNote.style.display = 'none';
1460
+ const textureList = el('div', 'pci-list');
1461
+ texturePanel.append(textureBar, this._textureNote, textureList);
1462
+
1463
+ // assets: the registry, in a chosen order
1464
+ const assetPanel = el('div', 'pci-listpanel');
1465
+ const assetBar = el('div', 'pci-subbar');
1466
+ this._assetSort = this._makeSelect(assetBar, 'Sort by', ASSET_SORTS, 'The order of the asset list');
1467
+ const assetList = el('div', 'pci-list');
1468
+ assetPanel.append(assetBar, assetList);
1469
+
1470
+ // meshes: a note when some vertex buffers belong to no mesh found, over the list
1471
+ const meshPanel = el('div', 'pci-listpanel');
1472
+ this._meshNote = el('div', 'pci-note pci-note-info');
1473
+ this._meshNote.style.display = 'none';
1474
+ const meshList = el('div', 'pci-list');
1475
+ meshPanel.append(this._meshNote, meshList);
1476
+
1477
+ // materials: a plain list
1478
+ const materialPanel = el('div', 'pci-listpanel');
1479
+ const materialList = el('div', 'pci-list');
1480
+ materialPanel.append(materialList);
1481
+
1482
+ // cameras: the render mode and wireframe over the list
1483
+ const cameraPanel = el('div', 'pci-listpanel');
1484
+ const cameraBar = el('div', 'pci-subbar');
1485
+ this._renderMode = this._makeSelect(cameraBar, 'Render', RENDER_MODES,
1486
+ 'Draw with the lit scene, or a debug view of one input of the materials');
1487
+ this._renderScope = this._makeSelect(cameraBar, 'for', [['all', 'all cameras']],
1488
+ 'The camera to switch the render mode of, or all of them');
1489
+ this._wireframeToggle = this._makeToggle(cameraBar, 'Wireframe', 'Draw every mesh instance of the scene in wireframe, for every camera');
1490
+ this._resetViewBtn = /** @type {HTMLButtonElement} */ (el('button', 'pci-btn', 'Reset'));
1491
+ setTip(this._resetViewBtn, 'Put back the render mode each camera had, and turn wireframe off');
1492
+ this._resetViewBtn.disabled = true;
1493
+ this._resetViewBtn.addEventListener('click', () => this._resetRenderOverrides());
1494
+ cameraBar.appendChild(this._resetViewBtn);
1495
+ const cameraList = el('div', 'pci-list');
1496
+ cameraPanel.append(cameraBar, cameraList);
1497
+ this._renderMode.addEventListener('change', () => this._applyRenderMode());
1498
+ // choosing a camera shows its render mode, and changes nothing until a mode is picked
1499
+ this._renderScope.addEventListener('change', () => {
1500
+ const camera = this._scopeCamera();
1501
+ if (camera) this._renderMode.value = camera.camera.shaderPassInfo?.name ?? RENDER_MODES[0][0];
1502
+ });
1503
+ this._wireframeToggle.addEventListener('change', () => this._applyWireframe());
1504
+
1505
+ // scripts: a plain list
1506
+ const scriptPanel = el('div', 'pci-listpanel');
1507
+ const scriptList = el('div', 'pci-list');
1508
+ scriptPanel.append(scriptList);
1509
+
1510
+ // memory: the totals over the buffers, which can be narrowed to one kind
1511
+ 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
+ const bufferList = el('div', 'pci-list');
1517
+ memoryPanel.append(memoryBar, this._memoryNote, bufferList);
1518
+
1519
+ // shaders: a plain list
1520
+ const shaderPanel = el('div', 'pci-listpanel');
1521
+ const shaderList = el('div', 'pci-list');
1522
+ shaderPanel.append(shaderList);
1523
+
1524
+ for (const input of [this._previewToggle, this._previewAttachment, this._previewChannels, this._texturePreviewToggle, this._textureChannels, this._assetSort, this._bufferKind]) {
1525
+ input.addEventListener('change', () => this._saveSettings());
1526
+ }
1527
+
1528
+ // physics: a master switch, the options it governs, then the list of bodies
1529
+ const physicsPanel = el('div', 'pci-listpanel');
1530
+ const physicsMaster = el('div', 'pci-subbar pci-master');
1531
+ this._drawToggle = this._makeToggle(physicsMaster, 'Draw physics world',
1532
+ 'Draw the physics world over the scene through the engine\'s debug drawer. The options below only apply while this is on');
1533
+ this._drawToggle.parentElement.classList.add('pci-strong');
1534
+ physicsMaster.appendChild(el('span', 'pci-hint', 'options below apply while on'));
1535
+ const physicsBar = el('div', 'pci-subbar pci-wrap pci-options');
1536
+ this._physicsOptionsBar = physicsBar;
1537
+ const options = [
1538
+ ['wireframe', 'Wireframe', 'Collision shapes. White: awake, green: asleep, cyan: about to sleep, red: never sleeps, yellow: not simulated'],
1539
+ ['aabb', 'AABB', 'Axis-aligned bounds of each body'],
1540
+ ['contacts', 'Contacts', 'Contact points and normals from the last step'],
1541
+ ['constraints', 'Constraints', 'Joint frames'],
1542
+ ['limits', 'Limits', 'Joint limits'],
1543
+ ['normals', 'Normals', 'Face normals of mesh shapes'],
1544
+ ['frames', 'Frames', 'Local axes of each body'],
1545
+ ['keepAwake', 'Keep awake', 'Stop bodies from falling asleep while drawing']
1546
+ ];
1547
+ this._physicsToggles = {};
1548
+ for (const [key, label, title] of options) {
1549
+ const toggle = this._makeToggle(physicsBar, label, title);
1550
+ toggle.addEventListener('change', () => this._applyPhysicsSettings());
1551
+ this._physicsToggles[key] = toggle;
1552
+ }
1553
+ this._depthToggle = this._makeToggle(physicsBar, 'Depth test', 'Hide lines behind geometry');
1554
+ const range = el('label', 'pci-check', 'Range');
1555
+ setTip(range, 'Only draw lines within this distance of the camera, in meters. 0 draws everything');
1556
+ this._rangeInput = /** @type {HTMLInputElement} */ (document.createElement('input'));
1557
+ this._rangeInput.type = 'number';
1558
+ this._rangeInput.className = 'pci-number';
1559
+ this._rangeInput.min = '0';
1560
+ this._rangeInput.step = '1';
1561
+ this._rangeInput.value = '0';
1562
+ range.appendChild(this._rangeInput);
1563
+ physicsBar.appendChild(range);
1564
+ this._physicsNote = el('div', 'pci-note');
1565
+ const bodyList = el('div', 'pci-list');
1566
+ physicsPanel.append(physicsMaster, physicsBar, this._physicsNote, bodyList);
1567
+
1568
+ for (const input of [this._drawToggle, this._depthToggle, this._rangeInput]) {
1569
+ input.addEventListener('change', () => this._applyPhysicsSettings());
1570
+ }
1571
+ this._rangeInput.addEventListener('input', () => this._applyPhysicsSettings());
1572
+
1573
+ this._panels = {
1574
+ hierarchy: tree,
1575
+ assets: assetPanel,
1576
+ passes: passPanel,
1577
+ targets: targetPanel,
1578
+ textures: texturePanel,
1579
+ meshes: meshPanel,
1580
+ materials: materialPanel,
1581
+ scripts: scriptPanel,
1582
+ cameras: cameraPanel,
1583
+ memory: memoryPanel,
1584
+ shaders: shaderPanel,
1585
+ physics: physicsPanel
1586
+ };
1587
+ this._hierarchyEl.append(tabs, filter, tree, cameraPanel, assetPanel, passPanel, targetPanel, texturePanel, meshPanel, materialPanel, scriptPanel, memoryPanel, shaderPanel, physicsPanel);
1588
+
1589
+ const splitter = el('div', 'pci-splitter');
1590
+ const properties = el('div', 'pci-properties');
1591
+ body.append(this._hierarchyEl, splitter, properties);
1592
+
1593
+ this._gpuToggle.addEventListener('change', () => {
1594
+ const profiler = this._app.graphicsDevice.gpuProfiler;
1595
+ if (profiler) profiler.enabled = this._gpuToggle.checked;
1596
+ this._saveSettings();
1597
+ });
1598
+ this._passPreviewToggle.addEventListener('change', () => this._saveSettings());
1599
+ this._debugFrameToggle.addEventListener('change', () => this._setDebugFrame(this._debugFrameToggle.checked));
1600
+ this._freezeToggle.addEventListener('change', () => {
1601
+ this._frozen = this._freezeToggle.checked;
1602
+ this._updateStatus();
1603
+ });
1604
+
1605
+ this._filterInput.addEventListener('input', () => this._applyFilter(this._filterInput.value));
1606
+ // the scene may have gained components or scripts since the suggestions were made
1607
+ this._filterInput.addEventListener('focus', () => this._updateFilterHint());
1608
+ this._filterBy.addEventListener('change', () => {
1609
+ this._updateFilterHint();
1610
+ this._applyFilter(this._filterInput.value);
1611
+ this._saveSettings();
1612
+ });
1613
+ this._filterInput.addEventListener('keydown', (e) => {
1614
+ if (e.key === 'Escape') {
1615
+ this._filterInput.value = '';
1616
+ this._applyFilter('');
1617
+ this._filterInput.blur();
1618
+ }
1619
+ });
1620
+
1621
+ this._makeDraggable(splitter, (e) => {
1622
+ const rect = body.getBoundingClientRect();
1623
+ const height = Math.max(60, Math.min(rect.height - 60, e.clientY - rect.top));
1624
+ this._hierarchyEl.style.flexBasis = `${height}px`;
1625
+ });
1626
+
1627
+ // status bar
1628
+ const status = el('div', 'pci-status');
1629
+ this._countsEl = el('span', 'pci-counts');
1630
+ this._pausedEl = el('span', 'pci-paused');
1631
+ this._debugEl = el('span', 'pci-paused');
1632
+ this._modeEl = el('span', 'pci-paused');
1633
+ this._pathEl = el('span', 'pci-path');
1634
+ status.append(this._countsEl, this._pausedEl, this._debugEl, this._modeEl, this._pathEl);
1635
+
1636
+ // width handle on the inner edge
1637
+ const edge = el('div', 'pci-edge');
1638
+ this._makeDraggable(edge, (e) => {
1639
+ const view = /** @type {Window} */ (edge.ownerDocument.defaultView);
1640
+ this._setWidth(this._dock === 'right' ? view.innerWidth - e.clientX : e.clientX);
1641
+ });
1642
+
1643
+ panel.append(toolbar, body, status, edge);
1644
+ installTooltip(panel);
1645
+ shadow.append(style, panel);
1646
+
1647
+ // keep the app's input handlers from seeing interaction with the panel
1648
+ for (const type of SWALLOWED_EVENTS) {
1649
+ host.addEventListener(type, (e) => {
1650
+ e.stopPropagation();
1651
+ if (type === 'keydown' && !isTextTarget(e)) this._onKeyDown(/** @type {KeyboardEvent} */ (e));
1652
+ });
1653
+ }
1654
+
1655
+ document.body.appendChild(host);
1656
+
1657
+ this._host = host;
1658
+ this._panel = panel;
1659
+ this._properties = new PropertyView(properties, target => this._selectAny(target));
1660
+ this._hierarchy = new HierarchyView(tree, (node) => {
1661
+ this._selected = node;
1662
+ if (this._tab === 'hierarchy') this._properties.setSubject(node, buildNodeModel);
1663
+ if (node && this._fly instanceof CameraOrbit) this._fly.setTarget(node);
1664
+ this._applyOrbitState();
1665
+ this._updateStatus();
1666
+ });
1667
+ this._hierarchy.isLocked = node => this._isLocked(node);
1668
+ this._hierarchy.onToggle = () => this._properties.refresh();
1669
+ this._passList = new ListView(passList, (item, key) => {
1670
+ if (this._tab === 'passes') this._properties.setSubject(item, this._passListModel(item), key);
1671
+ if (this._debugFrame) this._moveDebugFrameTo(item, key);
1672
+ this._updateStatus();
1673
+ }, target => this._selectAny(target));
1674
+ this._targetList = new ListView(targetList, (rt, key) => {
1675
+ if (this._tab === 'targets') this._properties.setSubject(rt, this._targetModel, key);
1676
+ this._updateStatus();
1677
+ }, target => this._selectAny(target));
1678
+ this._textureList = new ListView(textureList, (texture, key) => {
1679
+ if (this._tab === 'textures') this._properties.setSubject(texture, this._textureModel, key);
1680
+ this._updateStatus();
1681
+ }, target => this._selectAny(target));
1682
+ this._shaderList = new ListView(shaderList, (shader, key) => {
1683
+ if (this._tab === 'shaders') this._properties.setSubject(shader, this._shaderModel, key);
1684
+ this._updateStatus();
1685
+ }, target => this._selectAny(target));
1686
+ this._materialList = new ListView(materialList, (material, key) => {
1687
+ if (this._tab === 'materials') this._properties.setSubject(material, this._materialModel, key);
1688
+ this._updateStatus();
1689
+ }, target => this._selectAny(target));
1690
+ this._cameraList = new ListView(cameraList, (camera, key) => {
1691
+ if (this._tab === 'cameras') this._properties.setSubject(camera, this._cameraModel, key);
1692
+ this._updateStatus();
1693
+ }, target => this._selectAny(target));
1694
+ this._scriptList = new ListView(scriptList, (cls, key) => {
1695
+ if (this._tab === 'scripts') this._properties.setSubject(cls, this._scriptModel, key);
1696
+ this._updateStatus();
1697
+ }, target => this._selectAny(target));
1698
+ this._meshList = new ListView(meshList, (mesh, key) => {
1699
+ if (this._tab === 'meshes') this._properties.setSubject(mesh, this._meshModel, key);
1700
+ this._updateStatus();
1701
+ }, target => this._selectAny(target));
1702
+ this._bufferList = new ListView(bufferList, (buffer, key) => {
1703
+ if (this._tab === 'memory') this._properties.setSubject(buffer, this._bufferModel, key);
1704
+ this._updateStatus();
1705
+ }, target => this._selectAny(target));
1706
+ this._assetList = new ListView(assetList, (asset, key) => {
1707
+ if (this._tab === 'assets') this._properties.setSubject(asset, this._assetModel, key);
1708
+ this._updateStatus();
1709
+ }, target => this._selectAny(target));
1710
+ this._bodyList = new ListView(bodyList, (entity) => {
1711
+ if (this._tab === 'physics') this._properties.setSubject(entity, buildNodeModel);
1712
+ this._updateStatus();
1713
+ }, target => this._selectAny(target));
1714
+ this._bodyList.onToggle = (entity, drawn) => this._setBodyDrawn(entity, drawn);
1715
+
1716
+ // a texture or render target previews while hovered, without having to follow its link
1717
+ const onHover = (el, target) => {
1718
+ this._hoverLink = el && target ? { el, target } : null;
1719
+ };
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;
1725
+ }
1726
+
1727
+ /**
1728
+ * What to preview for the link or row the pointer is over: a texture, or the first attachment of
1729
+ * a render target, the way the Render targets tab shows it. The element is checked to still be on
1730
+ * screen, as a refresh can remove it and a tab switch hide it without the pointer leaving it. The
1731
+ * `:hover` state cannot tell instead: browsers do not reliably report it for elements in a shadow
1732
+ * root.
1733
+ *
1734
+ * @returns {{ texture: Texture, label: string, depth: boolean, channels: HTMLSelectElement, renderTarget?: RenderTarget }|null}
1735
+ * The texture to draw and how, or null when nothing previewable is hovered.
1736
+ * @private
1737
+ */
1738
+ _hoveredPreview() {
1739
+ const link = this._hoverLink;
1740
+ if (!link) return null;
1741
+ if (!link.el.isConnected || link.el.getClientRects().length === 0) {
1742
+ this._hoverLink = null;
1743
+ return null;
1744
+ }
1745
+ const target = link.target();
1746
+ if (target instanceof Texture) {
1747
+ return { texture: target, label: `Texture "${target.name}"`, depth: isDepthFormat(target.format), channels: this._textureChannels };
1748
+ }
1749
+ if (target instanceof RenderTarget) {
1750
+ const attachment = previewAttachments(target, this._app.graphicsDevice)[0];
1751
+ if (!attachment) return null;
1752
+ return {
1753
+ texture: attachment.texture,
1754
+ label: `the ${attachment.label} of ${target.name || 'its target'}`,
1755
+ depth: attachment.key === 'depth',
1756
+ channels: this._previewChannels,
1757
+ renderTarget: target
1758
+ };
1759
+ }
1760
+ return null;
1761
+ }
1762
+
1763
+ /**
1764
+ * @param {HTMLElement} handle - The element to drag.
1765
+ * @param {(e: PointerEvent) => void} onMove - Called with every pointer move while dragging.
1766
+ * @private
1767
+ */
1768
+ _makeDraggable(handle, onMove) {
1769
+ handle.addEventListener('pointerdown', (e) => {
1770
+ e.preventDefault();
1771
+ handle.setPointerCapture(e.pointerId);
1772
+ const move = onMove;
1773
+ const up = () => {
1774
+ handle.removeEventListener('pointermove', move);
1775
+ handle.removeEventListener('pointerup', up);
1776
+ handle.removeEventListener('pointercancel', up);
1777
+ };
1778
+ handle.addEventListener('pointermove', move);
1779
+ handle.addEventListener('pointerup', up);
1780
+ handle.addEventListener('pointercancel', up);
1781
+ });
1782
+ }
1783
+
1784
+ /**
1785
+ * @returns {Storage|null} The window's local storage, or null where there is none or reading
1786
+ * it throws, as in some sandboxed frames.
1787
+ * @private
1788
+ */
1789
+ static _storage() {
1790
+ try {
1791
+ return typeof window !== 'undefined' ? window.localStorage ?? null : null;
1792
+ } catch (e) {
1793
+ return null;
1794
+ }
1795
+ }
1796
+
1797
+ /**
1798
+ * Restores the settings kept under {@link InspectorOptions#storageKey}, if any.
1799
+ *
1800
+ * @private
1801
+ */
1802
+ _loadSettings() {
1803
+ if (!this._storageKey) return;
1804
+
1805
+ let stored;
1806
+ try {
1807
+ const json = Inspector._storage()?.getItem(this._storageKey);
1808
+ stored = json ? JSON.parse(json) : null;
1809
+ } catch (e) {
1810
+ // storage unavailable, e.g. a sandboxed frame, or unreadable content
1811
+ }
1812
+ if (!stored || typeof stored !== 'object') return;
1813
+
1814
+ if (stored.physicsDrawOptions && typeof stored.physicsDrawOptions === 'object') {
1815
+ this._physicsDrawOptions = stored.physicsDrawOptions;
1816
+ }
1817
+ if (typeof stored.physicsDraw === 'boolean') this._physicsDraw = stored.physicsDraw;
1818
+ if (Array.isArray(stored.hiddenBodies)) {
1819
+ this._pendingHiddenPaths = new Set(stored.hiddenBodies.filter(path => typeof path === 'string'));
1820
+ }
1821
+ if (typeof stored.width === 'number') this._setWidth(stored.width);
1822
+ 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;
1827
+ }
1828
+ if (stored.targetPreview && typeof stored.targetPreview === 'object') {
1829
+ if (typeof stored.targetPreview.enabled === 'boolean') this._previewToggle.checked = stored.targetPreview.enabled;
1830
+ if (typeof stored.targetPreview.channels === 'string') this._previewChannels.value = stored.targetPreview.channels;
1831
+ }
1832
+ if (typeof stored.assetSort === 'string') this._assetSort.value = stored.assetSort;
1833
+ if (typeof stored.bufferKind === 'string') this._bufferKind.value = stored.bufferKind;
1834
+ if (typeof stored.filterBy === 'string') {
1835
+ this._filterBy.value = stored.filterBy;
1836
+ this._hierarchy.filterBy = /** @type {any} */ (this._filterBy.value);
1837
+ }
1838
+ if (stored.texturePreview && typeof stored.texturePreview === 'object') {
1839
+ if (typeof stored.texturePreview.enabled === 'boolean') this._texturePreviewToggle.checked = stored.texturePreview.enabled;
1840
+ if (typeof stored.texturePreview.channels === 'string') this._textureChannels.value = stored.texturePreview.channels;
1841
+ }
1842
+ if (stored.tab in this._panels) this._setTab(stored.tab);
1843
+ }
1844
+
1845
+ /**
1846
+ * Writes the settings kept under {@link InspectorOptions#storageKey}, if any. Called whenever
1847
+ * one of them changes; suppressed while the panel is being built and restored.
1848
+ *
1849
+ * @private
1850
+ */
1851
+ _saveSettings() {
1852
+ if (!this._storageKey || this._restoring || !this._host) return;
1853
+
1854
+ const hiddenBodies = [...this._pendingHiddenPaths];
1855
+ for (const entity of this._hiddenBodies.keys()) {
1856
+ hiddenBodies.push(entity.path);
1857
+ }
1858
+
1859
+ try {
1860
+ Inspector._storage()?.setItem(this._storageKey, JSON.stringify({
1861
+ physicsDraw: this._physicsDraw,
1862
+ physicsDrawOptions: this._physicsDrawOptions,
1863
+ hiddenBodies,
1864
+ tab: this._tab,
1865
+ width: this._width,
1866
+ gpuTimings: this._gpuToggle.checked,
1867
+ passPreview: this._passPreviewToggle.checked,
1868
+ targetPreview: { enabled: this._previewToggle.checked, channels: this._previewChannels.value },
1869
+ texturePreview: { enabled: this._texturePreviewToggle.checked, channels: this._textureChannels.value },
1870
+ assetSort: this._assetSort.value,
1871
+ bufferKind: this._bufferKind.value,
1872
+ filterBy: this._filterBy.value
1873
+ }));
1874
+ } catch (e) {
1875
+ // storage unavailable or full: settings simply do not persist
1876
+ }
1877
+ }
1878
+
1879
+ /**
1880
+ * Includes or excludes one body from the physics drawing, from its checkbox in the list.
1881
+ *
1882
+ * @param {Entity} entity - The entity carrying the rigid body.
1883
+ * @param {boolean} drawn - Whether the body is drawn.
1884
+ * @private
1885
+ */
1886
+ _setBodyDrawn(entity, drawn) {
1887
+ const physics = this._physics;
1888
+ if (drawn) {
1889
+ const body = this._hiddenBodies.get(entity);
1890
+ this._hiddenBodies.delete(entity);
1891
+ if (body && physics) physics.showBody(body);
1892
+ } else {
1893
+ const body = entity.rigidbody?.body ?? null;
1894
+ this._hiddenBodies.set(entity, body);
1895
+ if (body && physics) physics.hideBody(body);
1896
+ }
1897
+ if (this._tab === 'physics') this._refreshLists(false);
1898
+ this._saveSettings();
1899
+ }
1900
+
1901
+ /**
1902
+ * Keeps the exclusions in step with the engine: a body the engine rebuilt is excluded again, a
1903
+ * destroyed one is forgotten without being touched, and an entity that lost its component
1904
+ * drops out.
1905
+ *
1906
+ * @private
1907
+ */
1908
+ _pruneHiddenBodies() {
1909
+ const physics = this._physics;
1910
+
1911
+ // exclusions restored from storage attach to the entities once they exist
1912
+ if (this._pendingHiddenPaths.size) {
1913
+ const store = this._app.systems.rigidbody?.store;
1914
+ for (const record of Object.values(store ?? {})) {
1915
+ const entity = record.entity;
1916
+ if (this._pendingHiddenPaths.delete(entity.path)) {
1917
+ const body = entity.rigidbody?.body ?? null;
1918
+ this._hiddenBodies.set(entity, body);
1919
+ if (body && physics) physics.hideBody(body);
1920
+ }
1921
+ }
1922
+ }
1923
+
1924
+ for (const [entity, body] of this._hiddenBodies) {
1925
+ const rigidbody = entity.rigidbody;
1926
+ const current = rigidbody?.body ?? null;
1927
+ if (current === body) continue;
1928
+ if (body && physics) physics.forgetBody(body);
1929
+ if (!rigidbody) {
1930
+ this._hiddenBodies.delete(entity);
1931
+ } else {
1932
+ this._hiddenBodies.set(entity, current);
1933
+ if (current && physics) physics.hideBody(current);
1934
+ }
1935
+ }
1936
+ }
1937
+
1938
+ /**
1939
+ * Pushes the physics tab's controls into the debug drawer.
1940
+ *
1941
+ * @private
1942
+ */
1943
+ _applyPhysicsSettings() {
1944
+ const physics = this._physics;
1945
+ if (!physics) return;
1946
+
1947
+ let mode = 0;
1948
+ for (const [key, flag] of Object.entries(PHYSICS_FLAGS)) {
1949
+ if (this._physicsToggles[key].checked) mode |= flag;
1950
+ }
1951
+
1952
+ const draw = this._drawToggle.checked;
1953
+ physics.enabled = this._visible && draw;
1954
+ physics.mode = mode;
1955
+ physics.depthTest = this._depthToggle.checked;
1956
+ physics.range = Math.max(0, parseFloat(this._rangeInput.value) || 0);
1957
+
1958
+ // the options and the per-body checkboxes mean nothing while the master switch is off
1959
+ this._physicsOptionsBar.classList.toggle('pci-inactive', !draw);
1960
+ for (const input of this._physicsOptionsBar.querySelectorAll('input')) {
1961
+ input.disabled = !draw;
1962
+ }
1963
+ if (this._tab === 'physics') this._refreshLists(false);
1964
+ this._saveSettings();
1965
+ }
1966
+
1967
+ /**
1968
+ * @param {HTMLElement} parent - The bar to add the selector to.
1969
+ * @param {string} label - The label.
1970
+ * @param {[string, string][]} options - Value and label pairs.
1971
+ * @param {string} title - The tooltip.
1972
+ * @returns {HTMLSelectElement} The selector.
1973
+ * @private
1974
+ */
1975
+ _makeSelect(parent, label, options, title) {
1976
+ const wrap = el('label', 'pci-check', label);
1977
+ setTip(wrap, title);
1978
+ const select = /** @type {HTMLSelectElement} */ (document.createElement('select'));
1979
+ select.className = 'pci-select';
1980
+ this._fillSelect(select, options);
1981
+ wrap.appendChild(select);
1982
+ parent.appendChild(wrap);
1983
+ return select;
1984
+ }
1985
+
1986
+ /**
1987
+ * @param {HTMLSelectElement} select - The selector.
1988
+ * @param {[string, string][]} options - Value and label pairs.
1989
+ * @private
1990
+ */
1991
+ _fillSelect(select, options) {
1992
+ const previous = select.value;
1993
+ select.textContent = '';
1994
+ for (const [value, label] of options) {
1995
+ const option = document.createElement('option');
1996
+ option.value = value;
1997
+ option.textContent = label;
1998
+ select.appendChild(option);
1999
+ }
2000
+ if (options.some(([value]) => value === previous)) select.value = previous;
2001
+ }
2002
+
2003
+ /**
2004
+ * Draws the selected render target's texture in the free corner of the viewport, on the UI
2005
+ * layer: it renders after a camera frame's post-processing and into the backbuffer, so
2006
+ * previewing the scene's own color target never samples a texture being rendered to. Runs
2007
+ * every frame while the Render targets tab is active; the renderer only shows what is
2008
+ * submitted that frame.
2009
+ *
2010
+ * @private
2011
+ */
2012
+ _drawTargetPreview() {
2013
+ const rt = this._targetList.selected;
2014
+ const device = this._app.graphicsDevice;
2015
+ let note = '';
2016
+
2017
+ if (rt && this._previewToggle.checked) {
2018
+ const attachments = previewAttachments(rt, device);
2019
+ const keys = attachments.map(a => a.key).join(',');
2020
+ if (keys !== this._previewKeys) {
2021
+ this._previewKeys = keys;
2022
+ this._fillSelect(this._previewAttachment, attachments.map(a => [a.key, a.label]));
2023
+ }
2024
+ const attachment = attachments.find(a => a.key === this._previewAttachment.value) ?? attachments[0];
2025
+
2026
+ if (!attachment) {
2027
+ note = rt === device.backBuffer ? 'The backbuffer is the screen itself, there is nothing to preview.' : 'This target has no texture to preview.';
2028
+ } else {
2029
+ note = this._drawPreviewQuad(attachment.texture, `the ${attachment.label} attachment`, attachment.key === 'depth', this._previewChannels, 'corner', rt);
2030
+ }
2031
+ }
2032
+
2033
+ Inspector._setNote(this._previewNote, note);
2034
+ }
2035
+
2036
+ /**
2037
+ * Draws the texture selected on the textures tab, when its preview is enabled. Runs every frame
2038
+ * while the tab is active.
2039
+ *
2040
+ * @private
2041
+ */
2042
+ _drawTexturePreview() {
2043
+ const texture = this._textureList.selected;
2044
+ let note = '';
2045
+ if (texture && this._texturePreviewToggle.checked) {
2046
+ note = this._drawPreviewQuad(texture, `Texture "${texture.name}"`, isDepthFormat(texture.format), this._textureChannels);
2047
+ }
2048
+ Inspector._setNote(this._textureNote, note);
2049
+ }
2050
+
2051
+ /**
2052
+ * Draws a texture keeping its aspect, either at 30% of the viewport height in the corner the
2053
+ * panel leaves free, or as large as fits the part of the viewport the panel leaves free. The
2054
+ * quad goes on the UI layer, drawn by the last camera rendering that layer to the screen:
2055
+ * cameras rendering into a texture would put the quad in their target, and the UI layer
2056
+ * renders after a camera frame's post-processing, so previewing the scene's own color target
2057
+ * never samples a texture being rendered to.
2058
+ *
2059
+ * @param {Texture} texture - The texture.
2060
+ * @param {string} label - What is being previewed, for the note.
2061
+ * @param {boolean} depth - Whether it is a raw depth texture, which the channel selection
2062
+ * does not apply to.
2063
+ * @param {HTMLSelectElement|null} channelsSelect - The channel selection to apply, or null for
2064
+ * color.
2065
+ * @param {'corner'|'large'} [size] - Where and how large to draw it. Defaults to the corner.
2066
+ * @param {RenderTarget|null} [renderTarget] - The render target the texture is attached to,
2067
+ * which decides whether it is stored upside down. Looked up on the device when not given.
2068
+ * @returns {string} What is shown where, or why nothing is.
2069
+ * @private
2070
+ */
2071
+ _drawPreviewQuad(texture, label, depth, channelsSelect, size = 'corner', renderTarget) {
2072
+ const device = this._app.graphicsDevice;
2073
+ const uiLayer = this._app.scene?.layers?.getLayerById(LAYERID_UI) ?? null;
2074
+ const cameras = uiLayer ? this._app.systems.camera?.cameras ?? [] : [];
2075
+ const uiCamera = cameras.filter(camera => !camera.renderTarget && camera.layers.includes(LAYERID_UI)).at(-1) ?? null;
2076
+ if (!uiCamera) return 'The preview is drawn on the UI layer, which no camera renders to the screen in this scene.';
2077
+
2078
+ const support = previewSupport(texture, device);
2079
+ if (!support.ok) return `Cannot preview ${label}: ${support.reason}.`;
2080
+
2081
+ const right = this._dock === 'left' || !!this._popup;
2082
+ let rect;
2083
+ if (size === 'large') {
2084
+ rect = this._freePreviewRect(texture);
2085
+ } else {
2086
+ const margin = 0.02;
2087
+ const height = 0.3;
2088
+ const width = texture.height > 0 && device.width > 0 ?
2089
+ height * (texture.width / texture.height) * (device.height / device.width) : height;
2090
+ rect = { x: right ? 1 - width - margin : margin, y: 1 - height - margin, width, height };
2091
+ }
2092
+
2093
+ // a channel the format does not store samples as a constant, so show the color instead and say why
2094
+ const selected = channelsSelect?.value ?? 'rgb';
2095
+ const selectedLabel = channelsSelect?.selectedOptions[0]?.textContent ?? 'color';
2096
+ const stored = depth ? '' : formatChannels(texture.format);
2097
+ const missing = selected !== 'rgb' && stored !== '' && !stored.includes(selected[0]);
2098
+
2099
+ this._textures.layer = uiLayer;
2100
+ this._textures.camera = uiCamera;
2101
+ this._textures.channels = missing ? 'rgb' : selected;
2102
+ // a negative height draws the rows from the bottom edge up, turning a bottom-up image upright
2103
+ if (storedBottomUp(texture, device, renderTarget)) {
2104
+ this._textures.draw(texture, rect.x, rect.y + rect.height, rect.width, -rect.height);
2105
+ } else {
2106
+ this._textures.draw(texture, rect.x, rect.y, rect.width, rect.height);
2107
+ }
2108
+
2109
+ // depth previews are raw grayscale, the channel selection does not apply to them
2110
+ const channels = depth ? '' : ` (${missing ? 'color' : selectedLabel})`;
2111
+ const where = size === 'large' ? 'over the free part of the viewport' : `at the bottom ${right ? 'right' : 'left'} of the viewport`;
2112
+ let note = `Previewing ${label}${channels} ${where}.`;
2113
+ if (missing) note += ` ${formatName(texture.format)} has no ${selectedLabel} channel.`;
2114
+ return note;
2115
+ }
2116
+
2117
+ /**
2118
+ * The largest rectangle of the texture's aspect that fits the part of the viewport the panel
2119
+ * leaves free, in normalized viewport coordinates. The whole viewport is free while the panel
2120
+ * is popped out.
2121
+ *
2122
+ * @param {Texture} texture - The texture to fit.
2123
+ * @returns {{ x: number, y: number, width: number, height: number }} The rectangle.
2124
+ * @private
2125
+ */
2126
+ _freePreviewRect(texture) {
2127
+ const device = this._app.graphicsDevice;
2128
+ const canvasRect = /** @type {any} */ (device).canvas?.getBoundingClientRect?.();
2129
+ let left = 0;
2130
+ let right = 1;
2131
+ if (canvasRect?.width > 0 && !this._popup) {
2132
+ const panelRect = this._panel?.getBoundingClientRect?.();
2133
+ if (panelRect?.width > 0) {
2134
+ if (this._dock === 'left') {
2135
+ left = Math.min(1, Math.max(0, (panelRect.right - canvasRect.left) / canvasRect.width));
2136
+ } else {
2137
+ right = Math.max(0, Math.min(1, (panelRect.left - canvasRect.left) / canvasRect.width));
2138
+ }
2139
+ }
2140
+ }
2141
+
2142
+ const margin = 0.02;
2143
+ const freeWidth = Math.max(0.05, right - left - 2 * margin);
2144
+ const freeHeight = 1 - 2 * margin;
2145
+ const textureAspect = texture.height > 0 ? texture.width / texture.height : 1;
2146
+ const viewAspect = device.height > 0 ? device.width / device.height : 1;
2147
+ let height = freeHeight;
2148
+ let width = height * textureAspect / viewAspect;
2149
+ if (width > freeWidth) {
2150
+ width = freeWidth;
2151
+ height = width * viewAspect / textureAspect;
2152
+ }
2153
+ return { x: left + margin + (freeWidth - width) / 2, y: margin + (freeHeight - height) / 2, width, height };
2154
+ }
2155
+
2156
+ /**
2157
+ * Draws the render target of the pass selected on the frame graph tab, large, when its preview
2158
+ * is on. A pass drawing to the screen needs no preview: the view is its output.
2159
+ *
2160
+ * @private
2161
+ */
2162
+ _drawPassPreview() {
2163
+ const item = this._passList.selected;
2164
+ const pass = item instanceof LayerStepSelection ? item.pass : item;
2165
+ const device = this._app.graphicsDevice;
2166
+ let note = '';
2167
+
2168
+ if (pass && this._passPreviewToggle.checked) {
2169
+ const renderTarget = this._frame?.entries.find(entry => entry.pass === pass)?.renderTarget;
2170
+ if (renderTarget === device.backBuffer) {
2171
+ note = 'This pass draws to the screen, which is the view itself.';
2172
+ } else if (renderTarget) {
2173
+ const attachment = previewAttachments(renderTarget, device)[0];
2174
+ note = attachment ?
2175
+ this._drawPreviewQuad(attachment.texture, `the ${attachment.label} of ${renderTarget.name || 'its target'}`,
2176
+ attachment.key === 'depth', null, 'large', renderTarget) :
2177
+ 'This pass\'s target has no texture to preview.';
2178
+ }
2179
+ }
2180
+ Inspector._setNote(this._passNote, note);
2181
+ }
2182
+
2183
+ /**
2184
+ * Turns the debug frame on or off. On, it pauses the app, stops the selected forward pass at its
2185
+ * last draw, and takes the arrow keys ahead of the app to step through the draws. Off, the pass
2186
+ * draws in full again and the app returns to its earlier pause state.
2187
+ *
2188
+ * @param {boolean} on - Whether to turn it on.
2189
+ * @private
2190
+ */
2191
+ _setDebugFrame(on) {
2192
+ if (on === !!this._debugFrame) return;
2193
+ const renderer = this._app.renderer;
2194
+ if (on) {
2195
+ if (!renderer?.debugDrawLimitSupported) return;
2196
+ this._debugFrame = { stepKey: null, index: 0, instance: null, wasPaused: this._paused };
2197
+ this.paused = true;
2198
+ this._moveDebugFrameTo(this._passList.selected, this._passList.selectedKey);
2199
+ // ahead of the app's own listeners, which would otherwise move the camera
2200
+ window.addEventListener('keydown', this._onDebugKey, true);
2201
+ } else {
2202
+ const wasPaused = this._debugFrame.wasPaused;
2203
+ this._debugFrame = null;
2204
+ window.removeEventListener('keydown', this._onDebugKey, true);
2205
+ if (renderer) renderer.debugDrawLimit = null;
2206
+ this.paused = wasPaused;
2207
+ }
2208
+ if (this._debugFrameToggle) this._debugFrameToggle.checked = on;
2209
+ this._updateDebugStatus(null);
2210
+ this._properties?.refresh();
2211
+ }
2212
+
2213
+ /**
2214
+ * Moves the debug frame to the last draw of a selected pass or layer step. Selecting anything
2215
+ * else leaves it where it was.
2216
+ *
2217
+ * @param {*} item - What the pass list selected.
2218
+ * @param {string|null} key - The key of its row.
2219
+ * @private
2220
+ */
2221
+ _moveDebugFrameTo(item, key) {
2222
+ const state = this._debugFrame;
2223
+ if (!state || !key) return;
2224
+ const visible = this._frame?.visible;
2225
+ let stepKey = null;
2226
+ let list = null;
2227
+ if (item instanceof LayerStepSelection) {
2228
+ stepKey = key;
2229
+ list = visible?.get(item.step) ?? null;
2230
+ } else if (item instanceof RenderPassForward) {
2231
+ // the last step that drew anything
2232
+ item.layerRenderSteps.forEach((step, i) => {
2233
+ const drawn = visible?.get(step) ?? null;
2234
+ if (drawn?.instances.length) {
2235
+ stepKey = `${key}/${i}`;
2236
+ list = drawn;
2237
+ }
2238
+ });
2239
+ }
2240
+ if (!stepKey) return;
2241
+ state.stepKey = stepKey;
2242
+ state.index = Math.max(0, (list?.instances.length ?? 1) - 1);
2243
+ state.instance = list?.instances[state.index] ?? null;
2244
+ this._revealDebugDraw();
2245
+ }
2246
+
2247
+ /**
2248
+ * @param {string} stepKey - The list key of a layer step.
2249
+ * @param {number} index - A draw in its list.
2250
+ * @param {MeshInstance} instance - The instance at that draw.
2251
+ * @private
2252
+ */
2253
+ _chooseDebugDraw(stepKey, index, instance) {
2254
+ const state = this._debugFrame;
2255
+ if (!state) return;
2256
+ state.stepKey = stepKey;
2257
+ state.index = index;
2258
+ state.instance = instance;
2259
+ }
2260
+
2261
+ /**
2262
+ * Finds the layer step the debug frame stops in, in the latest captured frame. Forward passes
2263
+ * are rebuilt every frame, so the step is found again by its list key each time.
2264
+ *
2265
+ * @returns {{ pass: RenderPassForward, step: *, stepIndex: number, passKey: string, list: import('./frame-graph-view.js').VisibleList|null }|null}
2266
+ * The step, or null when it is not in the frame.
2267
+ * @private
2268
+ */
2269
+ _resolveDebugStep() {
2270
+ const stepKey = this._debugFrame?.stepKey;
2271
+ if (!stepKey || !this._frame) return null;
2272
+ const slash = stepKey.lastIndexOf('/');
2273
+ const passKey = stepKey.slice(0, slash);
2274
+ const stepIndex = Number(stepKey.slice(slash + 1));
2275
+ const pass = this._frame.entries.find(entry => entry.key === passKey)?.pass;
2276
+ const step = pass instanceof RenderPassForward ? pass.layerRenderSteps[stepIndex] : undefined;
2277
+ if (!step) return null;
2278
+ return { pass, step, stepIndex, passKey, list: this._frame.visible?.get(step) ?? null };
2279
+ }
2280
+
2281
+ /**
2282
+ * Hands the renderer the limit for this frame: the steps of the pass before the chosen one
2283
+ * draw in full, the chosen one draws up to and including its instance, and the rest draw
2284
+ * nothing, so the pass's target shows exactly what that draw left behind.
2285
+ *
2286
+ * @private
2287
+ */
2288
+ _applyDebugFrame() {
2289
+ const renderer = this._app.renderer;
2290
+ const state = this._debugFrame;
2291
+ const found = this._resolveDebugStep();
2292
+ if (!renderer || !state || !found?.list) {
2293
+ if (renderer) renderer.debugDrawLimit = null;
2294
+ this._updateDebugStatus(null);
2295
+ return;
2296
+ }
2297
+
2298
+ // keep the chosen instance where the latest list put it
2299
+ const instances = found.list.instances;
2300
+ const at = state.instance ? instances.indexOf(state.instance) : -1;
2301
+ if (at >= 0) state.index = at;
2302
+ state.index = Math.min(Math.max(0, state.index), Math.max(0, instances.length - 1));
2303
+ state.instance = instances[state.index] ?? null;
2304
+
2305
+ const camera = found.step.cameraComponent?.camera;
2306
+ const renderTarget = found.step.renderTarget ?? this._app.graphicsDevice.backBuffer;
2307
+ const layers = new Map();
2308
+ found.pass.layerRenderSteps.forEach((step, i) => {
2309
+ if (step.cameraComponent?.camera !== camera || i < found.stepIndex) return;
2310
+ const entry = layers.get(step.layer) ?? [undefined, undefined];
2311
+ entry[step.transparent ? 1 : 0] = i === found.stepIndex ? { instance: state.instance, index: state.index } : 0;
2312
+ layers.set(step.layer, entry);
2313
+ });
2314
+ renderer.debugDrawLimit = { camera, renderTarget, layers };
2315
+
2316
+ // outline the draw on the UI layer, drawn after a camera frame's scene pass so the limit
2317
+ // does not cut it
2318
+ const aabb = state.instance?.aabb;
2319
+ if (aabb) {
2320
+ const wire = this._wire;
2321
+ const previous = wire.layer;
2322
+ wire.layer = this._app.scene?.layers?.getLayerById(LAYERID_UI) ?? previous;
2323
+ wire.color.copy(this._highlightColor);
2324
+ wire.depthTest = false;
2325
+ wire.box(aabb);
2326
+ wire.layer = previous;
2327
+ }
2328
+ this._updateDebugStatus(found);
2329
+ }
2330
+
2331
+ /**
2332
+ * Steps the debug frame one draw on or back, carrying on into the neighboring steps of the same
2333
+ * camera in the pass, and skipping those that drew nothing.
2334
+ *
2335
+ * @param {number} delta - 1 for the next draw, -1 for the previous.
2336
+ * @private
2337
+ */
2338
+ _stepDebugDraw(delta) {
2339
+ const state = this._debugFrame;
2340
+ const found = this._resolveDebugStep();
2341
+ if (!state || !found?.list) return;
2342
+ const steps = found.pass.layerRenderSteps;
2343
+ const camera = found.step.cameraComponent?.camera;
2344
+ const listOf = i => (steps[i].cameraComponent?.camera === camera ? this._frame?.visible?.get(steps[i]) ?? null : null);
2345
+
2346
+ let stepIndex = found.stepIndex;
2347
+ let index = state.index + delta;
2348
+ if (index >= found.list.instances.length) {
2349
+ index = found.list.instances.length - 1;
2350
+ for (let i = stepIndex + 1; i < steps.length; i++) {
2351
+ if (listOf(i)?.instances.length) {
2352
+ stepIndex = i;
2353
+ index = 0;
2354
+ break;
2355
+ }
2356
+ }
2357
+ } else if (index < 0) {
2358
+ index = 0;
2359
+ for (let i = stepIndex - 1; i >= 0; i--) {
2360
+ const list = listOf(i);
2361
+ if (list?.instances.length) {
2362
+ stepIndex = i;
2363
+ index = list.instances.length - 1;
2364
+ break;
2365
+ }
2366
+ }
2367
+ }
2368
+
2369
+ const stepKey = `${found.passKey}/${stepIndex}`;
2370
+ // follow into a new step in the list when a step, rather than the whole pass, is shown
2371
+ if (stepKey !== state.stepKey && this._passList.selected instanceof LayerStepSelection) {
2372
+ this._passList.select(stepKey);
2373
+ }
2374
+ state.stepKey = stepKey;
2375
+ state.index = index;
2376
+ state.instance = listOf(stepIndex)?.instances[index] ?? null;
2377
+ this._revealDebugDraw();
2378
+ }
2379
+
2380
+ /**
2381
+ * Brings the draw the debug frame stops at into view: its page, and its row.
2382
+ *
2383
+ * @private
2384
+ */
2385
+ _revealDebugDraw() {
2386
+ const state = this._debugFrame;
2387
+ if (!state?.stepKey) return;
2388
+ this._instancePages.set(state.stepKey, Math.floor(state.index / INSTANCES_PER_PAGE));
2389
+ this._properties.refresh();
2390
+ this._properties.container.querySelector('.pci-prop.pci-active')?.scrollIntoView?.({ block: 'nearest' });
2391
+ }
2392
+
2393
+ /**
2394
+ * Takes the arrow keys while the debug frame is on, ahead of the app, unless typing in a field.
2395
+ *
2396
+ * @param {KeyboardEvent} e - The event.
2397
+ * @returns {boolean} Whether the key stepped the frame.
2398
+ * @private
2399
+ */
2400
+ _onDebugKey = (e) => {
2401
+ if (!this._debugFrame || (e.key !== 'ArrowUp' && e.key !== 'ArrowDown')) return false;
2402
+ // events from inside the panel's shadow root reach the window retargeted to its host
2403
+ const target = /** @type {any} */ (e.composedPath?.()[0] ?? e.target);
2404
+ if (['INPUT', 'SELECT', 'TEXTAREA'].includes(target?.tagName)) return false;
2405
+ e.preventDefault();
2406
+ e.stopImmediatePropagation();
2407
+ this._stepDebugDraw(e.key === 'ArrowDown' ? 1 : -1);
2408
+ return true;
2409
+ };
2410
+
2411
+ /**
2412
+ * @param {{ step: *, list: import('./frame-graph-view.js').VisibleList|null }|null} found - The
2413
+ * step the debug frame stops in, or null.
2414
+ * @private
2415
+ */
2416
+ _updateDebugStatus(found) {
2417
+ const state = this._debugFrame;
2418
+ let text = '';
2419
+ if (state) {
2420
+ text = found?.list ?
2421
+ `DEBUG FRAME · draw ${state.index} of ${found.list.instances.length} · ${found.step.layer.name} ${found.step.transparent ? 'transparent' : 'opaque'}` :
2422
+ 'DEBUG FRAME · select a forward pass';
2423
+ }
2424
+ if (this._debugEl && this._debugEl.textContent !== text) this._debugEl.textContent = text;
2425
+ }
2426
+
2427
+ /**
2428
+ * Words the filter box after what it matches on the active tab, and fills its suggestions with
2429
+ * the component types or script names of the scene while the hierarchy is filtered by those.
2430
+ *
2431
+ * @private
2432
+ */
2433
+ _updateFilterHint() {
2434
+ const by = this._tab === 'hierarchy' ? this._filterBy.value : 'name';
2435
+ this._filterInput.placeholder = by === 'component' ? 'Filter by component…' :
2436
+ by === 'script' ? 'Filter by script…' : this._tab === 'hierarchy' ? 'Filter by entity name…' : 'Filter by name…';
2437
+
2438
+ const values = filterSuggestions(this._app.root ?? null, /** @type {any} */ (by));
2439
+ const options = this._filterSuggestions.options;
2440
+ if (options.length === values.length && values.every((value, i) => options[i].value === value)) return;
2441
+ this._filterSuggestions.replaceChildren(...values.map((value) => {
2442
+ const option = document.createElement('option');
2443
+ option.value = value;
2444
+ return option;
2445
+ }));
2446
+ }
2447
+
2448
+ /**
2449
+ * @param {HTMLElement} element - A note element.
2450
+ * @param {string} text - The text, empty to hide the note.
2451
+ * @private
2452
+ */
2453
+ static _setNote(element, text) {
2454
+ if (element.textContent !== text) element.textContent = text;
2455
+ const display = text ? '' : 'none';
2456
+ if (element.style.display !== display) element.style.display = display;
2457
+ }
2458
+
2459
+ /**
2460
+ * @param {HTMLElement} parent - The bar to add the toggle to.
2461
+ * @param {string} label - The label.
2462
+ * @param {string} title - The tooltip.
2463
+ * @returns {HTMLInputElement} The checkbox.
2464
+ * @private
2465
+ */
2466
+ _makeToggle(parent, label, title) {
2467
+ const wrap = el('label', 'pci-check', label);
2468
+ setTip(wrap, title);
2469
+ const input = /** @type {HTMLInputElement} */ (document.createElement('input'));
2470
+ input.type = 'checkbox';
2471
+ wrap.prepend(input);
2472
+ parent.appendChild(wrap);
2473
+ return input;
2474
+ }
2475
+
2476
+ /**
2477
+ * Switches the list tab and points the property view at that tab's selection.
2478
+ *
2479
+ * @param {'hierarchy'|'cameras'|'assets'|'passes'|'targets'|'textures'|'meshes'|'materials'|'scripts'|'memory'|'shaders'|'physics'} tab - The tab.
2480
+ * @private
2481
+ */
2482
+ _setTab(tab) {
2483
+ this._tab = tab;
2484
+ this._filterBy.style.display = tab === 'hierarchy' ? '' : 'none';
2485
+ this._updateFilterHint();
2486
+ for (const [id, button] of Object.entries(this._tabButtons)) {
2487
+ button.classList.toggle('pci-active', id === tab);
2488
+ }
2489
+ for (const [id, panel] of Object.entries(this._panels)) {
2490
+ panel.style.display = id === tab ? '' : 'none';
2491
+ }
2492
+ this._refreshLists(false);
2493
+ if (tab === 'hierarchy') {
2494
+ this._properties.setSubject(this._hierarchy.selected, buildNodeModel);
2495
+ }
2496
+ this._updateStatus();
2497
+ this._saveSettings();
2498
+ }
2499
+
2500
+ /**
2501
+ * Refreshes the active list. The frame graph is re-captured only when asked and not frozen, so
2502
+ * switching tabs keeps the frame the links were built from. Forward passes are recreated every
2503
+ * frame, so the property view is pointed at the current object under the selected row's key.
2504
+ *
2505
+ * @param {boolean} capture - Whether to take a fresh frame snapshot first.
2506
+ * @private
2507
+ */
2508
+ _refreshLists(capture) {
2509
+ const device = this._app.graphicsDevice;
2510
+
2511
+ if (this._tab === 'hierarchy') {
2512
+ this._hierarchy.refresh();
2513
+ } else if (this._tab === 'physics') {
2514
+ const system = this._app.systems.rigidbody;
2515
+ const note = !system ? 'No rigid body component system is registered in this app.' :
2516
+ !system.dynamicsWorld ? 'The physics world has not been created. Is Ammo loaded?' :
2517
+ !AmmoDebugDraw.isAvailable(this._app) ? 'This Ammo build has no DebugDrawer, so the world cannot be drawn.' : '';
2518
+ this._physicsNote.textContent = note;
2519
+ this._physicsNote.style.display = note ? '' : 'none';
2520
+
2521
+ this._bodyList.setRows([...bodyRows(this._app, this._hiddenBodies, this._drawToggle.checked), ...jointRows(this._app)]);
2522
+ const entity = this._bodyList.selected;
2523
+ if (entity !== this._properties.subject) {
2524
+ this._properties.setSubject(entity, buildNodeModel);
2525
+ }
2526
+ } else if (this._tab === 'textures') {
2527
+ this._textureList.setRows(textureRows(device));
2528
+ const texture = this._textureList.selected;
2529
+ if (texture !== this._properties.subject) {
2530
+ this._properties.setSubject(texture, this._textureModel, this._textureList.selectedKey);
2531
+ }
2532
+ } else if (this._tab === 'meshes') {
2533
+ const survey = surveyMeshes(this._app);
2534
+ Inspector._setNote(this._meshNote, meshNote(survey));
2535
+ this._meshList.setRows(meshListRows(survey));
2536
+ const mesh = this._meshList.selected;
2537
+ if (mesh !== this._properties.subject) {
2538
+ this._properties.setSubject(mesh, this._meshModel, this._meshList.selectedKey);
2539
+ }
2540
+ } else if (this._tab === 'materials') {
2541
+ this._materialList.setRows(materialListRows(surveyMaterials(this._app)));
2542
+ const material = this._materialList.selected;
2543
+ if (material !== this._properties.subject) {
2544
+ this._properties.setSubject(material, this._materialModel, this._materialList.selectedKey);
2545
+ }
2546
+ } else if (this._tab === 'cameras') {
2547
+ const rows = cameraRows(this._app, this._fly?.camera ?? null);
2548
+ this._cameraList.setRows(rows);
2549
+ // the render mode can be switched for any one camera, or all of them. The options are
2550
+ // rebuilt only when the cameras change: rebuilding them closes an open drop down
2551
+ const scopes = [['all', 'all cameras'], ...rows.map(row => [row.key, row.name])];
2552
+ const signature = scopes.map(([key, name]) => `${key}\0${name}`).join('\n');
2553
+ if (signature !== this._scopeSignature) {
2554
+ this._scopeSignature = signature;
2555
+ this._fillSelect(this._renderScope, scopes);
2556
+ }
2557
+ const camera = this._cameraList.selected;
2558
+ if (camera !== this._properties.subject) {
2559
+ this._properties.setSubject(camera, this._cameraModel, this._cameraList.selectedKey);
2560
+ }
2561
+ } else if (this._tab === 'scripts') {
2562
+ this._scriptList.setRows(scriptListRows(surveyScripts(this._app)));
2563
+ const cls = this._scriptList.selected;
2564
+ if (cls !== this._properties.subject) {
2565
+ this._properties.setSubject(cls, this._scriptModel, this._scriptList.selectedKey);
2566
+ }
2567
+ } else if (this._tab === 'memory') {
2568
+ Inspector._setNote(this._memoryNote, memorySummary(device));
2569
+ this._bufferList.setRows(bufferRows(device, bufferOwners(this._app), this._bufferKind.value));
2570
+ const buffer = this._bufferList.selected;
2571
+ if (buffer !== this._properties.subject) {
2572
+ this._properties.setSubject(buffer, this._bufferModel, this._bufferList.selectedKey);
2573
+ }
2574
+ } else if (this._tab === 'assets') {
2575
+ this._assetList.setRows(assetRows(this._app.assets, this._assetSort.value));
2576
+ const asset = this._assetList.selected;
2577
+ if (asset !== this._properties.subject) {
2578
+ this._properties.setSubject(asset, this._assetModel, this._assetList.selectedKey);
2579
+ }
2580
+ } else if (this._tab === 'shaders') {
2581
+ this._shaderList.setRows(shaderRows(device));
2582
+ const shader = this._shaderList.selected;
2583
+ if (shader !== this._properties.subject) {
2584
+ this._properties.setSubject(shader, this._shaderModel, this._shaderList.selectedKey);
2585
+ }
2586
+ } else {
2587
+ if ((capture && !this._frozen) || !this._frame) {
2588
+ this._frame = captureFrameGraph(this._app);
2589
+ }
2590
+ if (this._tab === 'passes') {
2591
+ this._passList.setRows(passRows(this._frame, device));
2592
+ const item = this._passList.selected;
2593
+ if (item !== this._properties.subject) {
2594
+ this._properties.setSubject(item, this._passListModel(item), this._passList.selectedKey);
2595
+ }
2596
+ } else {
2597
+ this._targetList.setRows(renderTargetRows(device, this._frame));
2598
+ const rt = this._targetList.selected;
2599
+ if (rt !== this._properties.subject) {
2600
+ this._properties.setSubject(rt, this._targetModel, this._targetList.selectedKey);
2601
+ }
2602
+ }
2603
+ }
2604
+
2605
+ this._updateStatus();
2606
+ }
2607
+
2608
+ /**
2609
+ * @param {string} value - The filter text, applied to every list.
2610
+ * @private
2611
+ */
2612
+ _applyFilter(value) {
2613
+ this._hierarchy.filter = value;
2614
+ this._hierarchy.filterBy = /** @type {any} */ (this._filterBy.value);
2615
+ const names = value;
2616
+ this._passList.filter = names;
2617
+ this._targetList.filter = names;
2618
+ this._textureList.filter = names;
2619
+ this._shaderList.filter = names;
2620
+ this._assetList.filter = names;
2621
+ this._bufferList.filter = names;
2622
+ this._meshList.filter = names;
2623
+ this._materialList.filter = names;
2624
+ this._scriptList.filter = names;
2625
+ this._cameraList.filter = names;
2626
+ this._bodyList.filter = names;
2627
+ this._refreshLists(false);
2628
+ // the instances listed under a forward pass narrow with the filter too
2629
+ this._properties.refresh();
2630
+ }
2631
+
2632
+ /**
2633
+ * Reveals a linked object in the tab that lists it: nodes in the hierarchy, passes in the frame
2634
+ * graph, render targets in their list.
2635
+ *
2636
+ * @param {*} target - The object.
2637
+ * @private
2638
+ */
2639
+ _selectAny(target) {
2640
+ if (target instanceof GraphNode) {
2641
+ this._setTab('hierarchy');
2642
+ this._hierarchy.select(target);
2643
+ } else if (target instanceof RenderTarget) {
2644
+ this._setTab('targets');
2645
+ this._targetList.selectItem(target);
2646
+ } else if (target instanceof FramePass) {
2647
+ this._setTab('passes');
2648
+ this._passList.selectItem(target);
2649
+ } else if (target instanceof Texture) {
2650
+ this._setTab('textures');
2651
+ this._textureList.selectItem(target);
2652
+ } else if (target instanceof Shader) {
2653
+ this._setTab('shaders');
2654
+ this._shaderList.selectItem(target);
2655
+ } else if (target instanceof Asset) {
2656
+ this._setTab('assets');
2657
+ this._assetList.selectItem(target);
2658
+ } else if (isScriptClass(target)) {
2659
+ this._setTab('scripts');
2660
+ this._scriptList.selectItem(target);
2661
+ } else if (target instanceof Material) {
2662
+ this._setTab('materials');
2663
+ this._materialList.selectItem(target);
2664
+ } else if (target instanceof Mesh) {
2665
+ this._setTab('meshes');
2666
+ this._meshList.selectItem(target);
2667
+ } 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
+ this._setTab('memory');
2671
+ this._bufferList.selectItem(target);
2672
+ }
2673
+ }
2674
+
2675
+ /**
2676
+ * @returns {PassModelContext & { app: AppBase }} What the model builders need besides their
2677
+ * subject: the app and device, the captured frame, and the paging state and filter of the
2678
+ * instances listed under a forward pass.
2679
+ * @private
2680
+ */
2681
+ _context() {
2682
+ return {
2683
+ app: this._app,
2684
+ device: this._app.graphicsDevice,
2685
+ frame: this._frame,
2686
+ passKey: this._passList?.selectedKey ?? null,
2687
+ pages: this._instancePages,
2688
+ filter: this._filterInput?.value.trim().toLowerCase() ?? '',
2689
+ stable: this._frozen || this._paused,
2690
+ debug: this._debugFrame ? {
2691
+ stepKey: this._debugFrame.stepKey,
2692
+ index: this._debugFrame.index,
2693
+ instance: this._debugFrame.instance,
2694
+ choose: (stepKey, index, instance) => this._chooseDebugDraw(stepKey, index, instance)
2695
+ } : null
2696
+ };
2697
+ }
2698
+
2699
+ /**
2700
+ * @param {KeyboardEvent} e - The event.
2701
+ * @private
2702
+ */
2703
+ _onKeyDown = (e) => {
2704
+ if (this._onDebugKey(e)) return;
2705
+ if (e.repeat) return;
2706
+
2707
+ // match on either the physical code ('Backquote') or the logical key ('`')
2708
+ const matches = key => !!key && (e.code === key || e.key === key);
2709
+
2710
+ if (matches(this._toggleKey)) {
2711
+ e.preventDefault();
2712
+ this.visible = !this._visible;
2713
+ } else if (matches(this._pauseKey)) {
2714
+ e.preventDefault();
2715
+ this.paused = !this._paused;
2716
+ } else if (matches(this._stepKey)) {
2717
+ e.preventDefault();
2718
+ this.step();
2719
+ }
2720
+ };
2721
+
2722
+ /**
2723
+ * @private
2724
+ */
2725
+ _onPopupHide = () => {
2726
+ this._dockBack();
2727
+ };
2728
+
2729
+ /**
2730
+ * @private
2731
+ */
2732
+ _applyVisibility() {
2733
+ if (!this._host) return;
2734
+ this._host.style.display = this._visible ? '' : 'none';
2735
+ }
2736
+
2737
+ /**
2738
+ * @param {number} value - The panel width in CSS pixels, clamped to a usable range.
2739
+ * @private
2740
+ */
2741
+ _setWidth(value) {
2742
+ this._width = Math.max(240, Math.min(1600, value || 420));
2743
+ this._applyLayout();
2744
+ this._saveSettings();
2745
+ }
2746
+
2747
+ /**
2748
+ * @private
2749
+ */
2750
+ _applyLayout() {
2751
+ if (!this._panel) return;
2752
+ const popped = !!this._popup;
2753
+ this._panel.classList.toggle('pci-popout', popped);
2754
+ this._panel.classList.toggle('pci-dock-left', !popped && this._dock === 'left');
2755
+ this._panel.style.width = popped ? '' : `${this._width}px`;
2756
+ this._panel.style.top = popped ? '' : `${this._top}px`;
2757
+ setIcon(this._popBtn, popped ? 'dock' : 'popout');
2758
+ this._popBtn.setAttribute('aria-label', popped ? 'Dock' : 'Pop out');
2759
+ this._popBtn.classList.remove('pci-warn');
2760
+ setTip(this._popBtn, popped ? 'Bring the panel back into the page' : 'Move the panel to a window of its own');
2761
+ }
2762
+
2763
+ /**
2764
+ * @param {string} key - A `KeyboardEvent.code` or `key`.
2765
+ * @returns {string} The key as shown on a button, or an empty string when unset.
2766
+ * @private
2767
+ */
2768
+ static _keyLabel(key) {
2769
+ if (!key) return '';
2770
+ const labels = { Backquote: '`', Space: 'Space', Escape: 'Esc' };
2771
+ return labels[key] ?? key.replace(/^Key|^Digit/, '');
2772
+ }
2773
+
2774
+ /**
2775
+ * @param {string} key - A `KeyboardEvent.code` or `key`.
2776
+ * @returns {string} The key in brackets for a button label, or an empty string when unset.
2777
+ * @private
2778
+ */
2779
+ static _keyHint(key) {
2780
+ const label = Inspector._keyLabel(key);
2781
+ return label ? ` (${label})` : '';
2782
+ }
2783
+
2784
+ /**
2785
+ * @private
2786
+ */
2787
+ _applyPauseState() {
2788
+ if (!this._pauseBtn) return;
2789
+ const paused = this._paused;
2790
+ setIcon(this._pauseBtn, paused ? 'play' : 'pause');
2791
+ this._pauseBtn.setAttribute('aria-label', paused ? 'Resume' : 'Pause');
2792
+ setTip(this._pauseBtn, paused ?
2793
+ `Resume the app${Inspector._keyHint(this._pauseKey)}` :
2794
+ `Pause the app${Inspector._keyHint(this._pauseKey)}: rendering continues, time stands still`);
2795
+ this._pauseBtn.classList.toggle('pci-active', paused);
2796
+ setTip(this._stepBtn, `Advance one frame while paused${Inspector._keyHint(this._stepKey)}`);
2797
+ this._stepBtn.disabled = !paused;
2798
+ this._pausedEl.textContent = paused ? 'PAUSED' : '';
2799
+ }
2800
+
2801
+ /**
2802
+ * @private
2803
+ */
2804
+ _updateStatus() {
2805
+ if (!this._countsEl) return;
2806
+ const device = this._app.graphicsDevice;
2807
+ let counts = '';
2808
+ let selected = '';
2809
+
2810
+ switch (this._tab) {
2811
+ case 'passes': {
2812
+ const gpu = this._frame?.frameTime;
2813
+ // WebGL times the frame with a single query; only WebGPU timestamps each pass
2814
+ const perPass = device.isWebGPU ? '' : ' (per-pass times need WebGPU)';
2815
+ counts = `${this._frame?.entries.length ?? 0} passes` +
2816
+ `${gpu !== undefined ? ` · GPU ${gpu.toFixed(2)} ms${perPass}` : ''}${this._frozen ? ' · frozen' : ''}`;
2817
+ const item = this._passList.selected;
2818
+ selected = item instanceof LayerStepSelection ?
2819
+ `${passDisplayName(item.pass)} › ${item.step.layer.name} ${item.step.transparent ? 'transparent' : 'opaque'}` :
2820
+ item ? passDisplayName(item) : '';
2821
+ break;
2822
+ }
2823
+ case 'targets': {
2824
+ counts = `${this._targetList.rowCount} render targets · ${this._frame?.usage.size ?? 0} used this frame`;
2825
+ const rt = this._targetList.selected;
2826
+ selected = rt ? (rt === device.backBuffer ? 'Backbuffer' : rt.name) : '';
2827
+ break;
2828
+ }
2829
+ case 'textures': {
2830
+ const textures = collectTextures(device);
2831
+ const bytes = textures.reduce((sum, texture) => sum + texture.gpuSize, 0);
2832
+ counts = `${textures.length} textures · ${formatBytes(bytes)}`;
2833
+ selected = this._textureList.selected?.name ?? '';
2834
+ break;
2835
+ }
2836
+ case 'meshes': {
2837
+ const survey = surveyMeshes(this._app);
2838
+ const bytes = [...survey.users.keys()].reduce((sum, mesh) => sum + meshBytes(mesh), 0);
2839
+ counts = `${survey.users.size} meshes · ${formatBytes(bytes)} · ${survey.instances} mesh instances`;
2840
+ const mesh = this._meshList.selected;
2841
+ selected = mesh ? `Mesh #${mesh.id}` : '';
2842
+ break;
2843
+ }
2844
+ case 'materials': {
2845
+ const materials = [...surveyMaterials(this._app).keys()];
2846
+ const used = materials.filter(material => material.meshInstances.size > 0).length;
2847
+ counts = `${materials.length} materials · ${used} in use`;
2848
+ const material = this._materialList.selected;
2849
+ selected = material ? `${material.name || 'Material'} #${material.id}` : '';
2850
+ break;
2851
+ }
2852
+ case 'cameras': {
2853
+ const cameras = collectCameras(this._app);
2854
+ const screen = cameras.filter(isScreenCamera).length;
2855
+ counts = `${cameras.length} cameras · ${screen} drawing to the screen`;
2856
+ selected = this._cameraList.selected?.entity.name ?? '';
2857
+ break;
2858
+ }
2859
+ case 'scripts': {
2860
+ const survey = surveyScripts(this._app);
2861
+ const instances = [...survey.values()].reduce((sum, script) => sum + script.instances.length, 0);
2862
+ counts = `${survey.size} scripts · ${instances} instances`;
2863
+ selected = survey.get(this._scriptList.selected)?.name ?? '';
2864
+ break;
2865
+ }
2866
+ 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)}` : '';
2872
+ break;
2873
+ }
2874
+ case 'assets': {
2875
+ const assets = collectAssets(this._app.assets);
2876
+ const loaded = assets.filter(asset => asset.loaded).length;
2877
+ const bytes = assets.reduce((sum, asset) => sum + (asset.file?.size ?? 0), 0);
2878
+ counts = `${assets.length} assets · ${loaded} loaded${bytes ? ` · ${formatBytes(bytes)}` : ''}`;
2879
+ selected = this._assetList.selected?.name ?? '';
2880
+ break;
2881
+ }
2882
+ case 'shaders': {
2883
+ const shaders = collectShaders(device);
2884
+ const failed = shaders.filter(shader => shader.failed).length;
2885
+ const compiling = shaders.filter(shader => !shader.ready && !shader.failed).length;
2886
+ counts = `${shaders.length} shaders${compiling ? ` · ${compiling} compiling` : ''}${failed ? ` · ${failed} failed` : ''}`;
2887
+ const shader = this._shaderList.selected;
2888
+ selected = shader ? `${shader.name} (${stateName(shader)})` : '';
2889
+ break;
2890
+ }
2891
+ case 'physics': {
2892
+ const stats = physicsStats(this._app);
2893
+ const physics = this._physics;
2894
+ counts = `${stats.bodies} bodies · ${stats.active} awake · ${stats.contacts} contacts` +
2895
+ `${stats.joints ? ` · ${stats.joints} joints` : ''}` +
2896
+ ` · step ${stats.time.toFixed(2)} ms${physics?.enabled ? ` · ${physics.lineCount} lines` : ''}` +
2897
+ `${physics?.culledCount ? ` (${physics.culledCount} out of range)` : ''}`;
2898
+ selected = this._bodyList.selected?.name ?? '';
2899
+ break;
2900
+ }
2901
+ default: {
2902
+ const { nodeCount, entityCount } = this._hierarchy;
2903
+ counts = `${entityCount} entities · ${nodeCount - entityCount} graph nodes`;
2904
+ selected = this._selected?.path ?? '';
2905
+ }
2906
+ }
2907
+
2908
+ this._countsEl.textContent = counts;
2909
+ this._pathEl.textContent = selected;
2910
+ setTip(this._pathEl, selected);
2911
+ }
2912
+
2913
+ /**
2914
+ * Picking: hovering the view outlines the entity under the pointer, and a click selects it in
2915
+ * the hierarchy. The pointer is taken from the app while it is on.
2916
+ *
2917
+ * @param {boolean} on - Whether to pick.
2918
+ * @private
2919
+ */
2920
+ _setPicking(on) {
2921
+ if (on === (this._canvasMode === 'pick')) return;
2922
+ this._releaseCanvas();
2923
+ if (on) {
2924
+ this._stopFly();
2925
+ this._picker ??= new ViewportPicker(this._app);
2926
+ this._takeCanvas('pick', this._onPickEvent);
2927
+ }
2928
+ this._pickBtn.classList.toggle('pci-active', on);
2929
+ }
2930
+
2931
+ /**
2932
+ * @param {Event} e - A pointer event on the canvas, while picking.
2933
+ * @private
2934
+ */
2935
+ _onPickEvent = (e) => {
2936
+ const pointer = /** @type {PointerEvent} */ (e);
2937
+ if (e.type === 'pointermove') {
2938
+ // a moving pointer picks where it is now, not everywhere it has been
2939
+ const busy = !!this._hoverPoint;
2940
+ this._hoverPoint = [pointer.clientX, pointer.clientY];
2941
+ if (!busy) this._pickHover();
2942
+ } else if (e.type === 'pointerup') {
2943
+ this._picker.pick(pointer.clientX, pointer.clientY).then((hit) => {
2944
+ if (hit && this._canvasMode === 'pick') this._selectAny(hit.entity);
2945
+ });
2946
+ }
2947
+ };
2948
+
2949
+ /**
2950
+ * Picks under the latest pointer position until the pointer rests, outlining what it finds.
2951
+ *
2952
+ * @private
2953
+ */
2954
+ _pickHover() {
2955
+ const [x, y] = this._hoverPoint;
2956
+ this._picker.pick(x, y).then((hit) => {
2957
+ const latest = this._hoverPoint;
2958
+ if (this._canvasMode !== 'pick' || !latest) {
2959
+ this._hoverPoint = null;
2960
+ return;
2961
+ }
2962
+ this._hovered = hit?.entity ?? null;
2963
+ // pick again only if the pointer moved while this one was reading back
2964
+ if (latest[0] !== x || latest[1] !== y) {
2965
+ this._pickHover();
2966
+ } else {
2967
+ this._hoverPoint = null;
2968
+ }
2969
+ });
2970
+ }
2971
+
2972
+ /**
2973
+ * Starts Fly or Orbit from its button, or stops it when it is on.
2974
+ *
2975
+ * @param {'fly'|'orbit'} kind - Which.
2976
+ * @private
2977
+ */
2978
+ _toggleDrive(kind) {
2979
+ const on = this._canvasMode === 'choose' ? this._chooseKind === kind : this._driveKind() === kind;
2980
+ this._stopFly();
2981
+ if (!on) this._startDrive(kind, null);
2982
+ }
2983
+
2984
+ /**
2985
+ * @returns {'fly'|'orbit'|null} Which of Fly and Orbit drives the camera, if either does.
2986
+ * @private
2987
+ */
2988
+ _driveKind() {
2989
+ if (this._fly instanceof CameraOrbit) return 'orbit';
2990
+ return this._fly ? 'fly' : null;
2991
+ }
2992
+
2993
+ /**
2994
+ * Flies a camera, or with no camera given, the one camera drawing to the screen, or the one
2995
+ * clicked next when several do.
2996
+ *
2997
+ * @param {CameraComponent|null} camera - The camera to fly, or null to find it from the view.
2998
+ * @private
2999
+ */
3000
+ _startFly(camera) {
3001
+ this._startDrive('fly', camera);
3002
+ }
3003
+
3004
+ /**
3005
+ * Flies a camera, or orbits it around the selected node. With no camera given, drives the one
3006
+ * camera drawing to the screen, or the one clicked next when several do.
3007
+ *
3008
+ * @param {'fly'|'orbit'} kind - Whether to fly or to orbit.
3009
+ * @param {CameraComponent|null} camera - The camera to drive, or null to find it from the view.
3010
+ * @private
3011
+ */
3012
+ _startDrive(kind, camera) {
3013
+ this._stopFly();
3014
+ this._setPicking(false);
3015
+ const target = this._selected;
3016
+ if (kind === 'orbit' && !target) return;
3017
+ const button = kind === 'orbit' ? this._orbitBtn : this._flyBtn;
3018
+ if (!camera) {
3019
+ const screen = collectCameras(this._app).filter(isScreenCamera);
3020
+ if (screen.length > 1) {
3021
+ this._chooseKind = kind;
3022
+ this._takeCanvas('choose', (e) => {
3023
+ if (e.type !== 'pointerup') return;
3024
+ const pointer = /** @type {PointerEvent} */ (e);
3025
+ const bounds = /** @type {HTMLCanvasElement} */ (this._app.graphicsDevice.canvas).getBoundingClientRect();
3026
+ const chosen = screenCameraAt(this._app, (pointer.clientX - bounds.left) / bounds.width, (pointer.clientY - bounds.top) / bounds.height);
3027
+ if (chosen) this._startDrive(kind, chosen);
3028
+ });
3029
+ button.classList.add('pci-active');
3030
+ return;
3031
+ }
3032
+ camera = screen[0] ?? null;
3033
+ if (!camera) {
3034
+ this._modeEl.textContent = kind === 'orbit' ?
3035
+ 'ORBIT · no camera draws to the screen' :
3036
+ 'FLY · no camera draws to the screen, fly one from the Cameras tab';
3037
+ return;
3038
+ }
3039
+ }
3040
+ this._fly = kind === 'orbit' ?
3041
+ new CameraOrbit(this._app, camera, target, () => this._stopFly()) :
3042
+ new CameraFly(this._app, camera, () => this._stopFly());
3043
+ button.classList.add('pci-active');
3044
+ this._properties.refresh();
3045
+ }
3046
+
3047
+ /** @private */
3048
+ _stopFly() {
3049
+ if (this._canvasMode === 'choose') this._releaseCanvas();
3050
+ if (this._fly) {
3051
+ this._fly.destroy();
3052
+ this._fly = null;
3053
+ this._properties.refresh();
3054
+ }
3055
+ this._flyBtn?.classList.remove('pci-active');
3056
+ this._orbitBtn?.classList.remove('pci-active');
3057
+ this._applyOrbitState();
3058
+ }
3059
+
3060
+ /**
3061
+ * Orbit needs a node to orbit around, so its button is off until one is selected.
3062
+ *
3063
+ * @private
3064
+ */
3065
+ _applyOrbitState() {
3066
+ if (this._orbitBtn) this._orbitBtn.disabled = !this._selected && !(this._fly instanceof CameraOrbit);
3067
+ }
3068
+
3069
+ /**
3070
+ * Takes the pointer on the canvas for a mode, and Esc to end it.
3071
+ *
3072
+ * @param {'pick'|'choose'} mode - The mode.
3073
+ * @param {(e: Event) => void} onEvent - Called with the pointer events.
3074
+ * @private
3075
+ */
3076
+ _takeCanvas(mode, onEvent) {
3077
+ this._canvasCapture = new CanvasCapture(/** @type {HTMLCanvasElement} */ (this._app.graphicsDevice.canvas), onEvent);
3078
+ this._canvasMode = mode;
3079
+ window.addEventListener('keydown', this._onModeKey, true);
3080
+ }
3081
+
3082
+ /** @private */
3083
+ _releaseCanvas() {
3084
+ this._canvasCapture?.destroy();
3085
+ this._canvasCapture = null;
3086
+ if (this._canvasMode === 'choose') {
3087
+ this._flyBtn.classList.remove('pci-active');
3088
+ this._orbitBtn.classList.remove('pci-active');
3089
+ }
3090
+ this._canvasMode = null;
3091
+ this._hovered = null;
3092
+ this._hoverPoint = null;
3093
+ window.removeEventListener('keydown', this._onModeKey, true);
3094
+ }
3095
+
3096
+ /**
3097
+ * @param {KeyboardEvent} e - A key pressed while the canvas is taken.
3098
+ * @private
3099
+ */
3100
+ _onModeKey = (e) => {
3101
+ if (e.key !== 'Escape') return;
3102
+ e.stopImmediatePropagation();
3103
+ if (this._canvasMode === 'pick') this._setPicking(false);
3104
+ else this._stopFly();
3105
+ };
3106
+
3107
+ /**
3108
+ * Ends every mode that changes the view: picking, flying, the render modes and wireframe.
3109
+ *
3110
+ * @private
3111
+ */
3112
+ _endViewportModes() {
3113
+ if (!this._pickBtn) return;
3114
+ this._setPicking(false);
3115
+ this._stopFly();
3116
+ this._resetRenderOverrides();
3117
+ this._modeEl.textContent = '';
3118
+ }
3119
+
3120
+ /**
3121
+ * Puts back the shader pass each camera had before the panel changed it, and turns wireframe
3122
+ * off.
3123
+ *
3124
+ * @private
3125
+ */
3126
+ _resetRenderOverrides() {
3127
+ for (const [camera, name] of this._changedPasses) camera.setShaderPass(name);
3128
+ this._changedPasses.clear();
3129
+ this._renderMode.value = RENDER_MODES[0][0];
3130
+ this._wireframe.restore();
3131
+ this._wireframeToggle.checked = false;
3132
+ this._updateResetButton();
3133
+ this._refreshLists(false);
3134
+ this._properties.refresh();
3135
+ }
3136
+
3137
+ /**
3138
+ * Enables the reset button while a camera renders with a changed mode or wireframe is on.
3139
+ *
3140
+ * @private
3141
+ */
3142
+ _updateResetButton() {
3143
+ const changed = this._wireframeToggle.checked ||
3144
+ [...this._changedPasses].some(([camera, name]) => (camera.camera.shaderPassInfo?.name ?? null) !== name);
3145
+ this._resetViewBtn.disabled = !changed;
3146
+ }
3147
+
3148
+ /**
3149
+ * Applies the render mode chosen on the Cameras tab to the selected camera, or to every camera,
3150
+ * keeping the shader pass each had to put back when the panel closes.
3151
+ *
3152
+ * @private
3153
+ */
3154
+ _applyRenderMode() {
3155
+ const name = this._renderMode.value;
3156
+ const chosen = this._scopeCamera();
3157
+ const cameras = chosen ? [chosen] : collectCameras(this._app);
3158
+ for (const camera of cameras) {
3159
+ if (!this._changedPasses.has(camera)) this._changedPasses.set(camera, camera.camera.shaderPassInfo?.name ?? null);
3160
+ const original = this._changedPasses.get(camera);
3161
+ // back to standard gives a camera the pass it had before, which the app may have chosen
3162
+ camera.setShaderPass(name === RENDER_MODES[0][0] ? original : name);
3163
+ }
3164
+ this._updateResetButton();
3165
+ this._refreshLists(false);
3166
+ this._properties.refresh();
3167
+ }
3168
+
3169
+ /**
3170
+ * @returns {CameraComponent|null} The camera the render mode is switched for, or null when it is
3171
+ * switched for all of them.
3172
+ * @private
3173
+ */
3174
+ _scopeCamera() {
3175
+ const key = this._renderScope.value;
3176
+ if (key === 'all') return null;
3177
+ return cameraRows(this._app, null).find(row => row.key === key)?.item ?? null;
3178
+ }
3179
+
3180
+ /** @private */
3181
+ _applyWireframe() {
3182
+ if (this._wireframeToggle.checked) this._wireframe.apply(this._app);
3183
+ else this._wireframe.restore();
3184
+ this._updateResetButton();
3185
+ }
3186
+
3187
+ /**
3188
+ * Says in the status bar what the view is doing while it is picked or flown.
3189
+ *
3190
+ * @private
3191
+ */
3192
+ _updateModeStatus() {
3193
+ let text = '';
3194
+ if (this._canvasMode === 'pick') {
3195
+ text = `PICK · ${this._hovered ? `"${this._hovered.name}", click to select` : 'hover an entity, click to select'} · Esc stops`;
3196
+ } else if (this._canvasMode === 'choose') {
3197
+ text = `${this._chooseKind.toUpperCase()} · click the view of the camera to ${this._chooseKind} · Esc stops`;
3198
+ } else if (this._fly instanceof CameraOrbit) {
3199
+ text = `ORBIT · "${this._fly.camera.entity.name}" around "${this._fly.target.name}" · drag to orbit, right-drag or Shift-drag to pan, wheel to zoom · Esc stops`;
3200
+ } else if (this._fly) {
3201
+ const keys = this._fly.zooms ? 'W S zoom, A D Q E pan' : 'WASD QE move';
3202
+ text = `FLY · "${this._fly.camera.entity.name}" · ${keys}, drag to look, wheel speed ${this._fly.speed.toFixed(1)}, Shift faster · Esc stops`;
3203
+ }
3204
+ if (this._modeEl.textContent !== text && (text || !this._modeEl.textContent.includes(' · no camera'))) this._modeEl.textContent = text;
3205
+ }
3206
+
3207
+ /**
3208
+ * Outlines a node in the viewport for the current frame.
3209
+ *
3210
+ * @param {GraphNode} node - The node.
3211
+ * @param {Color} [color] - The color to outline it in. Defaults to the highlight color.
3212
+ * @private
3213
+ */
3214
+ _drawHighlight(node, color = this._highlightColor) {
3215
+ const wire = this._wire;
3216
+ wire.color.copy(color);
3217
+ wire.depthTest = false;
3218
+
3219
+ let drawn = false;
3220
+
3221
+ if (node instanceof Entity) {
3222
+ const meshInstances = node.render?.meshInstances ?? node.model?.meshInstances;
3223
+ if (meshInstances) {
3224
+ for (const meshInstance of meshInstances) {
3225
+ if (meshInstance.visible) {
3226
+ wire.box(meshInstance.aabb);
3227
+ drawn = true;
3228
+ }
3229
+ }
3230
+ }
3231
+
3232
+ const splatAabb = node.gsplat?.customAabb;
3233
+ if (splatAabb) {
3234
+ wire.box(splatAabb);
3235
+ drawn = true;
3236
+ }
3237
+
3238
+ if (node.camera) {
3239
+ wire.frustum(node.camera);
3240
+ drawn = true;
3241
+ }
3242
+
3243
+ if (node.light) {
3244
+ wire.light(node.light, this._highlightSize(node));
3245
+ drawn = true;
3246
+ }
3247
+
3248
+ const corners = node.element?.worldCorners;
3249
+ if (corners) {
3250
+ wire.loop(corners);
3251
+ drawn = true;
3252
+ }
3253
+ }
3254
+
3255
+ if (!drawn) {
3256
+ wire.axes(node.getWorldTransform(), this._highlightSize(node));
3257
+ }
3258
+ }
3259
+
3260
+ /**
3261
+ * {@link lockedNode} and its ancestors cannot be disabled from the panel, as that would switch
3262
+ * the panel off with them.
3263
+ *
3264
+ * @param {GraphNode} node - The node.
3265
+ * @returns {boolean} Whether the node's enabled checkbox is withheld.
3266
+ * @private
3267
+ */
3268
+ _isLocked(node) {
3269
+ for (let current = this._lockedNode; current; current = current.parent) {
3270
+ if (current === node) return true;
3271
+ }
3272
+ return false;
3273
+ }
3274
+
3275
+ /**
3276
+ * @param {GraphNode} node - The node.
3277
+ * @returns {number} A size that reads well from the closest camera.
3278
+ * @private
3279
+ */
3280
+ _highlightSize(node) {
3281
+ const cameras = this._app.systems.camera?.cameras;
3282
+ let distance = 10;
3283
+ if (cameras?.length) {
3284
+ distance = Infinity;
3285
+ for (const camera of cameras) {
3286
+ distance = Math.min(distance, camera.entity.getPosition().distance(node.getPosition()));
3287
+ }
3288
+ }
3289
+ return Math.max(0.05, distance * 0.06);
3290
+ }
3291
+ }
3292
+
3293
+ export { Inspector };