Debian Codegraph @

src/ui/castleinternalinspector.pas

raw
1 {
2 Copyright 2015-2024 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Inspect Castle Game Engine state at runtime (TCastleInspector).
17 Invoke this automatically in debug builds by F8 (see @link(TCastleContainer.InputInspector)). }
18 unit CastleInternalInspector;
19
20 {$I castleconf.inc}
21
22 interface
23
24 uses Classes, Generics.Collections, TypInfo,
25 CastleControls, CastleUIControls, CastleColors, CastleRectangles,
26 CastleVectors, CastleKeysMouse, CastleComponentSerialize, CastleTimeUtils,
27 CastleTransform;
28
29 type
30 { Inspect Castle Game Engine state.
31 Show log, current UI and viewports state.
32 Invoke this automatically in debug builds by F8 (see @link(TCastleContainer.InputInspector)). }
33 TCastleInspector = class(TCastleUserInterfaceFont)
34 strict private
35 const
36 ProfilerDataCount = 100;
37 type
38 TProfilerMetric = (pmUpdate, pmPhysics, pmRender, pmSwap);
39
40 TProfilerDataItem = record
41 { Frame time, in 0..1 range (how much of frame do they occupy. }
42 Time: array [TProfilerMetric] of Single;
43 Fps: Single;
44 end;
45 PProfilerDataItem = ^TProfilerDataItem;
46
47 TProfilerData = array [0..ProfilerDataCount - 1] of TProfilerDataItem;
48
49 TAutoSelect = (asNothing, asUi, asTransform);
50
51 { Display a single property of an object. }
52 TPropertyDisplay = class(TComponent)
53 strict private
54 LabelName: TCastleLabel;
55 EditValue: TCastleEdit;
56 CheckboxValue: TCastleCheckbox;
57 PropObject: TObject;
58 PropInfo: PPropInfo;
59 IsBool: Boolean; //< Result of PropertyIsBool
60 procedure CheckboxChanged(Sender: TObject);
61 public
62 Ui: TCastleUserInterface;
63 procedure Initialize(const APropObject: TObject;
64 const APropInfo: PPropInfo; const APropName: String);
65 procedure UpdateCurrentValue;
66 end;
67 TPropertyDisplayList = {$ifdef FPC}specialize{$endif} TObjectList<TPropertyDisplay>;
68
69 var
70 { Controls loaded from inspector_ui.castle-user-interface.inc }
71 CheckboxShowEvenInternal: TCastleCheckbox;
72 CheckboxUiBatching: TCastleCheckbox;
73 RectOptions, RectProperties, RectLog, RectHierarchy, RectProfiler: TCastleRectangleControl;
74 ButtonHierarchyShow, ButtonHierarchyHide,
75 ButtonLogShow, ButtonLogHide,
76 ButtonPropertiesShow, ButtonPropertiesHide,
77 ButtonProfilerShow, ButtonProfilerHide: TCastleButton;
78 HorizontalGroupShow: TCastleUserInterface;
79 HierarchyRowParent: TCastleUserInterface;
80 PropertyRowParent: TCastleUserInterface;
81 ScrollLogs: TCastleScrollView;
82 ScrollProperties: TCastleScrollView;
83 LogsVerticalGroup: TCastleVerticalGroup;
84 LabelEarlierLogsRemoved: TCastleLabel;
85 LabelLogHeader: TCastleLabel;
86 LabelPropertiesHeader: TCastleLabel;
87 LabelInspectorHelp: TCastleLabel;
88 SliderOpacity: TCastleFloatSlider;
89 ButtonLogClear: TCastleButton;
90 CheckboxLogAutoScroll: TCastleCheckbox;
91 LabelProfilerHeader: TCastleLabel;
92 CheckboxProfilerDetailsInLog: TCastleCheckbox;
93 CheckboxProfilerMore: TCastleCheckbox;
94 CheckboxFileMonitorEnabled: TCastleCheckbox;
95 ProfilerGraph: TCastleUserInterface;
96 RectStatsMore: TCastleUserInterface;
97 LabelStatsMore: TCastleLabel;
98 ButtonAutoSelectNothing: TCastleButton;
99 ButtonAutoSelectUi: TCastleButton;
100 ButtonAutoSelectTransform: TCastleButton;
101 SafeBorderContainer: TCastleUserInterface;
102 HeaderProfiler, HeaderProfiler2ndRow: TCastleUserInterface;
103
104 FOpacity: Single;
105 FSelectedComponent: TComponent;
106 InsideLogCallback: Boolean;
107 SerializedHierarchyRowFactory: TCastleComponentFactory;
108 SerializedPropertyRowFactory: TCastleComponentFactory;
109 ProfilerData: TProfilerData;
110 ProfilerDataNonEmpty: Boolean;
111 { We have useful data at ProfilerDataFirst...ProfilerDataLast-1 indexes,
112 if ProfilerDataNonEmpty.
113 So ProfilerDataNonEmpty and (ProfilerDataLast = ProfilerDataFirst) means that queue is full.
114
115 When ProfilerDataLast < ProfilerDataFirst, then it wraps modulo ProfilerDataCount.
116 Both ProfilerDataFirst and ProfilerDataLast are always between 0 and ProfilerDataCount-1. }
117 ProfilerDataFirst, ProfilerDataLast: Integer;
118 LogCount: Cardinal;
119 AutoSelect: TAutoSelect;
120 { Properties of the SelectedComponent. }
121 Properties: TPropertyDisplayList;
122 TimeToUpdatePropertiesValues: TFloatTime;
123
124 procedure ChangeOpacity(Sender: TObject);
125 procedure SetOpacity(const Value: Single);
126 { Show component in hierarchy, allow to select it. }
127 function Selectable(const C: TComponent): Boolean;
128 procedure ClickHierarchyShow(Sender: TObject);
129 procedure ClickHierarchyHide(Sender: TObject);
130 procedure ClickLogShow(Sender: TObject);
131 procedure ClickLogHide(Sender: TObject);
132 procedure ClickPropertiesShow(Sender: TObject);
133 procedure ClickPropertiesHide(Sender: TObject);
134 procedure ClickProfilerShow(Sender: TObject);
135 procedure ClickProfilerHide(Sender: TObject);
136 procedure ClickLogClear(Sender: TObject);
137 procedure ChangeProfilerDetailsInLog(Sender: TObject);
138 procedure ChangeProfilerMore(Sender: TObject);
139 procedure ChangeFileMonitorEnabled(Sender: TObject);
140 { Synchronize state of HorizontalGroupShow and its children with the existence of rectangles
141 like RectHierarchy. So you only need to change RectHierarchy.Exists and call this method
142 to have UI consistent. }
143 procedure SynchronizeButtonsToShow;
144 procedure LogCallback(const Message: String);
145 procedure SetSelectedComponent(const Value: TComponent);
146 procedure UpdateHierarchy(Sender: TObject);
147 procedure ClickHierarchyRow(Sender: TObject);
148 { Update properties to reflect current FSelectedComponent.
149 Only SetSelectedComponent needs to call it. }
150 procedure UpdateProperties;
151 { Like UpdateProperties, but only updates property Values, assuming SelectedComponent
152 didn't change. }
153 procedure UpdatePropertiesValues;
154 procedure ProfilerSummaryAvailable(Sender: TObject);
155 procedure ProfilerGraphRender(const Sender: TCastleUserInterface);
156 { Synchronize state of ButtonAutoSelectXxx based on current AutoSelect value. }
157 procedure SynchronizeButtonsAutoSelect;
158 procedure ClickAutoSelectNothing(Sender: TObject);
159 procedure ClickAutoSelectUi(Sender: TObject);
160 procedure ClickAutoSelectTransform(Sender: TObject);
161 { Detect TCastleTransform that mouse hovers over.
162 Adjusted from CGE editor TDesignFrame.TDesignerLayer.HoverTransform }
163 function HoverTransform(const AMousePosition: TVector2): TCastleTransform;
164 { Detect UI control that mouse hovers over.
165 Adjusted from CGE editor TDesignFrame.TDesignerLayer.HoverUserInterface }
166 function HoverUserInterface(const AMousePosition: TVector2): TCastleUserInterface;
167 procedure UpdateLabelProfilerHeader;
168 procedure UpdateLabelStatsMore;
169 procedure ChangeUiBatching(Sender: TObject);
170 procedure BeforeRenderHierarchyRows(const Sender: TCastleUserInterface);
171 protected
172 procedure Notification(AComponent: TComponent; Operation: TOperation); override;
173 public
174 const
175 DefaultOpacity = 0.9;
176 type
177 TPersistentState = record
178 Opacity: Single;
179 RectPropertiesExists: Boolean;
180 RectLogExists: Boolean;
181 RectProfilerExists: Boolean;
182 RectHierarchyExists: Boolean;
183 end;
184 class var
185 { Class variables, to save across all inspector instances. }
186 PersistentState: TPersistentState;
187
188 constructor Create(AOwner: TComponent); override;
189 destructor Destroy; override;
190 procedure Update(const SecondsPassed: Single; var HandleInput: boolean); override;
191 procedure Resize; override;
192 function Press(const Event: TInputPressRelease): Boolean; override;
193 procedure InternalSetContainer(const Value: TCastleContainer); override;
194
195 { Opacity of the whole UI.
196 Can be changed by user while operating this UI. }
197 property Opacity: Single read FOpacity write SetOpacity;
198
199 { Selected object in hierarchy, for which we display the properties.
200 Can be changed by user while operating this UI. }
201 property SelectedComponent: TComponent read FSelectedComponent write SetSelectedComponent;
202 published
203 property KeepInFront stored false;
204 property FullSize stored false;
205 end;
206
207 implementation
208
209 uses SysUtils, StrUtils, RttiUtils,
210 CastleStringUtils, CastleGLUtils, CastleApplicationProperties, CastleClassUtils,
211 CastleUtils, CastleLog, CastleInternalRttiUtils, CastleGLImages,
212 CastleViewport, CastleScene, CastleUriUtils, CastleInternalFileMonitor;
213
214 { ---------------------------------------------------------------------------- }
215
216 type
217 // Just for test, this will also work.
218 // TSimpleLabel = TCastleLabel;
219
220 { Display string. A much simpler alternative to TCastleLabel,
221 missing a lot of its features.
222
223 Compared to TCastleLabel,
224
225 - it only supports displaying a single line
226 (newline characters in Caption will be visible as weird chars).
227
228 - does not support Html.
229
230 - does not support wrapping (MaxWidth), text alignment in any way.
231
232 - does not calculate own width properly (so e.g. anchors to right will not work).
233
234 - doesn't manage visual updates (it assumes screen will always be redrawn
235 after changing Caption; in practice, it is easiest to only
236 change Caption at creation).
237
238 - doesn't allow translation.
239
240 - doesn't serialize to/from JSON.
241 }
242 TSimpleLabel = class(TCastleUserInterfaceFont)
243 protected
244 procedure PreferredSize(var PreferredWidth, PreferredHeight: Single); override;
245 public
246 Caption: String;
247 Color: TCastleColor;
248 procedure Render; override;
249 end;
250
251 procedure TSimpleLabel.PreferredSize(var PreferredWidth, PreferredHeight: Single);
252 begin
253 // inherited; // no need
254 PreferredWidth := 10; // hardcoded arbitrary non-zero value, to return fast
255 { Add Font.DescenderHeight, although it is already contained in Font.Height.
256 See TCastleLabel.PreferredSize for reason. }
257 PreferredHeight := Font.Height + Font.DescenderHeight;
258 end;
259
260 procedure TSimpleLabel.Render;
261 var
262 R: TFloatRectangle;
263 begin
264 // inherited; // no need
265 R := RenderRect;
266 { TODO: Font.DescenderHeight * 1.5 to match button caption alignment,
267 but we should be rather "Font.DescenderHeight * 1" to be consistent with TCastleLabel. }
268 Font.Print(R.Left, R.Bottom + Font.DescenderHeight * 1.5, Color, Caption);
269 end;
270
271 { THierarchyRowLevelDisplay --------------------------------------------------------- }
272
273 type
274 { Display the level (indentation) of hierarchy row. }
275 THierarchyRowLevelDisplay = class(TCastleUserInterface)
276 protected
277 procedure PreferredSize(var PreferredWidth, PreferredHeight: Single); override;
278 public
279 { Both sizes in final pixels.
280 Updated every frame before drawing.
281 This way we properly adjust to current UI scaling. }
282 class var
283 OneLevelWidth, HierarchyRowHeight: Single;
284 var
285 PreviousLevel, Level: Cardinal;
286 procedure Render; override;
287 end;
288
289 procedure THierarchyRowLevelDisplay.PreferredSize(var PreferredWidth, PreferredHeight: Single);
290 begin
291 // inherited; // no need
292 PreferredWidth := OneLevelWidth * Level;
293 PreferredHeight := HierarchyRowHeight;
294 end;
295
296 procedure THierarchyRowLevelDisplay.Render;
297 const
298 ColorBars: TCastleColor = (X: 0.5; Y: 0.5; Z: 0.5; W: 1.0);
299
300 procedure DrawBar(const R: TFloatRectangle; const TopMostY: Single);
301 begin
302 DrawPrimitive2D(pmLineStrip, [
303 Vector2(R.Center.X, TopMostY),
304 Vector2(R.Center.X, R.Bottom)
305 ],
306 ColorBars);
307 end;
308
309 procedure DrawBarToRight(const R: TFloatRectangle; const TopMostY: Single);
310 begin
311 DrawPrimitive2D(pmLineStrip, [
312 Vector2(R.Center.X, TopMostY),
313 Vector2(R.Center.X, R.Center.Y),
314 Vector2(R.Right, R.Center.Y)
315 ],
316 ColorBars);
317 end;
318
319 var
320 I: Integer;
321 RR, R: TFloatRectangle;
322 TopMostY: Single;
323 begin
324 // inherited; // no need
325 if Level = 0 then Exit; // early exit when nothing to do
326 RR := RenderRect;
327 for I := 0 to Integer(Level) - 1 do
328 begin
329 R.Left := RR.Left + I * OneLevelWidth;
330 R.Bottom := RR.Bottom;
331 R.Width := OneLevelWidth;
332 R.Height := RR.Height;
333 // Make TopMostY go to the middle of *previous* hierarchy row, to connect to it
334 if I < PreviousLevel then
335 TopMostY := R.Top + HierarchyRowHeight / 2
336 else
337 TopMostY := R.Top;
338 if I <> Integer(Level) - 1 then
339 DrawBar(R, TopMostY)
340 else
341 DrawBarToRight(R, TopMostY);
342 end;
343 end;
344
345 { TPropertyDisplay ------------------------------------------------------------ }
346
347 procedure TCastleInspector.TPropertyDisplay.Initialize(
348 const APropObject: TObject; const APropInfo: PPropInfo; const APropName: String);
349 begin
350 PropObject := APropObject;
351 PropInfo := APropInfo;
352 IsBool := PropertyIsBool(PropInfo);
353
354 ForceFallbackLook(Ui);
355
356 LabelName := FindRequiredComponent('PropName') as TCastleLabel;
357 LabelName.Caption := APropName;
358
359 if IsBool then
360 begin
361 CheckboxValue := FindRequiredComponent('PropValueCheckbox') as TCastleCheckbox;
362 CheckboxValue.OnChange := {$ifdef FPC}@{$endif} CheckboxChanged;
363 // free (don't waste memory) unused UI
364 FindRequiredComponent('PropValue').Free;
365 end else
366 begin
367 EditValue := FindRequiredComponent('PropValue') as TCastleEdit;
368 // free (don't waste memory) unused UI
369 FindRequiredComponent('PropValueCheckboxParent').Free;
370 end;
371
372 UpdateCurrentValue;
373 end;
374
375 procedure TCastleInspector.TPropertyDisplay.CheckboxChanged(Sender: TObject);
376 begin
377 PropertyBoolSet(PropObject, PropInfo, CheckboxValue.Checked);
378 // refresh colors (based on whether new value is default)
379 UpdateCurrentValue;
380 end;
381
382 procedure TCastleInspector.TPropertyDisplay.UpdateCurrentValue;
383
384 procedure AdjustColorsBasedOnPropertyDefault(
385 const Edit: TCastleEdit; const IsDefault: Boolean); overload;
386 begin
387 if IsDefault then
388 begin
389 // TCastleEdit defaults
390 Edit.FocusedColor := Black;
391 Edit.UnfocusedColor := Vector4(0.25, 0.25, 0.25, 1);
392 end else
393 begin
394 Edit.FocusedColor := Blue;
395 Edit.UnfocusedColor := Vector4(0.25, 0.25, 1, 1);
396 end;
397 end;
398
399 procedure AdjustColorsBasedOnPropertyDefault(
400 const Checkbox: TCastleCheckbox; const IsDefault: Boolean); overload;
401 begin
402 if IsDefault then
403 begin
404 Checkbox.CheckboxColor := Black;
405 end else
406 begin
407 Checkbox.CheckboxColor := Blue;
408 end;
409 end;
410
411 var
412 PropName, PropValue: String;
413 begin
414 Assert(IsBool = Assigned(CheckboxValue));
415 Assert(IsBool = not Assigned(EditValue));
416 if IsBool then
417 begin
418 CheckboxValue.Checked := PropertyBoolGet(PropObject, PropInfo);
419 AdjustColorsBasedOnPropertyDefault(CheckboxValue,
420 PropertyHasDefaultValue(PropObject, PropInfo, true));
421 end else
422 begin
423 if PropertyGet(PropObject, PropInfo, PropName, PropValue) then
424 begin
425 EditValue.Text := PropValue;
426 AdjustColorsBasedOnPropertyDefault(EditValue,
427 PropertyHasDefaultValue(PropObject, PropInfo, true));
428 end else
429 WritelnWarning('Cannot read property name/value, but it was possible to read it earlier');
430 end;
431 end;
432
433 { TCastleInspector ----------------------------------------------------------- }
434
435 { TODO:
436
437 Show size as extra property - (C.EffectiveRect - like in CGE editor)
438
439 Show C.Focused marked by some border of button on hierarchy
440
441 Animate RectXxx existence changes.
442
443 untangle dependencies: it is a bit dirty that CastleUIControls, basic unit,
444 uses this unit -- which includes everything, like TCastleViewport.
445 CastleUIControls should instead expose InternalInspectorClass that this unit would set.
446
447 Hm, but then how to make sure this is always used?
448 This unit will have to be used by CastleWindow, CastleControl...
449 again creating a bigger dependency than needed.
450 Would be best if this unit didn't need some, at least no CastleViewport, CastleScene.
451
452 checkbox to also show X3D nodes
453 }
454
455 const
456 // In hierarchy row, we shift main button caption by Level * LevelWidthInSpaces * space width.
457 LevelWidthInSpaces = 4;
458
459 constructor TCastleInspector.Create(AOwner: TComponent);
460
461 procedure AddLastLogs;
462 var
463 I: Integer;
464 begin
465 for I := LastLogCount - 1 downto 0 do
466 LogCallback(LastLog(I));
467 // TODO: for some reason, this is necessary to correctly layout the newly added logs
468 LogsVerticalGroup.VisibleChange([chChildren]);
469 end;
470
471 { Create TCastleComponentFactory that in every TCastleComponentFactory.ComponentLoad
472 will create a deep clone of Template. }
473 function TemplateToFactory(const Template: TComponent): TCastleComponentFactory;
474 begin
475 Result := TCastleComponentFactory.Create(nil);
476 Result.LoadFromComponent(Template);
477 end;
478
479 var
480 UiOwner: TComponent;
481 Ui: TCastleUserInterface;
482 HierarchyRowTemplate: TCastleButton;
483 PropertyRowTemplate: TCastleUserInterface;
484 begin
485 inherited;
486
487 // adjust inherited published properties
488 FullSize := true;
489 KeepInFront := true;
490
491 UiOwner := TComponent.Create(Self);
492 Ui := StringToComponent({$I designs/inspector_ui.castle-user-interface.inc}, UiOwner)
493 as TCastleUserInterface;
494 InsertFront(Ui);
495
496 CheckboxShowEvenInternal := UiOwner.FindRequiredComponent('CheckboxShowEvenInternal') as TCastleCheckbox;
497 CheckboxUiBatching := UiOwner.FindRequiredComponent('CheckboxUiBatching') as TCastleCheckbox;
498 RectOptions := UiOwner.FindRequiredComponent('RectOptions') as TCastleRectangleControl;
499 RectProperties := UiOwner.FindRequiredComponent('RectProperties') as TCastleRectangleControl;
500 RectLog := UiOwner.FindRequiredComponent('RectLog') as TCastleRectangleControl;
501 RectHierarchy := UiOwner.FindRequiredComponent('RectHierarchy') as TCastleRectangleControl;
502 RectProfiler := UiOwner.FindRequiredComponent('RectProfiler') as TCastleRectangleControl;
503 ButtonHierarchyShow := UiOwner.FindRequiredComponent('ButtonHierarchyShow') as TCastleButton;
504 ButtonHierarchyHide := UiOwner.FindRequiredComponent('ButtonHierarchyHide') as TCastleButton;
505 ButtonLogShow := UiOwner.FindRequiredComponent('ButtonLogShow') as TCastleButton;
506 ButtonLogHide := UiOwner.FindRequiredComponent('ButtonLogHide') as TCastleButton;
507 ButtonPropertiesShow := UiOwner.FindRequiredComponent('ButtonPropertiesShow') as TCastleButton;
508 ButtonPropertiesHide := UiOwner.FindRequiredComponent('ButtonPropertiesHide') as TCastleButton;
509 ButtonProfilerShow := UiOwner.FindRequiredComponent('ButtonProfilerShow') as TCastleButton;
510 ButtonProfilerHide := UiOwner.FindRequiredComponent('ButtonProfilerHide') as TCastleButton;
511 HorizontalGroupShow := UiOwner.FindRequiredComponent('HorizontalGroupShow') as TCastleUserInterface;
512 HierarchyRowTemplate := UiOwner.FindRequiredComponent('HierarchyRowTemplate') as TCastleButton;
513 PropertyRowTemplate := UiOwner.FindRequiredComponent('PropertyRowTemplate') as TCastleUserInterface;
514 HierarchyRowParent := UiOwner.FindRequiredComponent('HierarchyRowParent') as TCastleUserInterface;
515 PropertyRowParent := UiOwner.FindRequiredComponent('PropertyRowParent') as TCastleUserInterface;
516 ScrollLogs := UiOwner.FindRequiredComponent('ScrollLogs') as TCastleScrollView;
517 ScrollProperties := UiOwner.FindRequiredComponent('ScrollProperties') as TCastleScrollView;
518 LogsVerticalGroup := UiOwner.FindRequiredComponent('LogsVerticalGroup') as TCastleVerticalGroup;
519 LabelEarlierLogsRemoved := UiOwner.FindRequiredComponent('LabelEarlierLogsRemoved') as TCastleLabel;
520 LabelLogHeader := UiOwner.FindRequiredComponent('LabelLogHeader') as TCastleLabel;
521 LabelPropertiesHeader := UiOwner.FindRequiredComponent('LabelPropertiesHeader') as TCastleLabel;
522 LabelInspectorHelp := UiOwner.FindRequiredComponent('LabelInspectorHelp') as TCastleLabel;
523 SliderOpacity := UiOwner.FindRequiredComponent('SliderOpacity') as TCastleFloatSlider;
524 ButtonLogClear := UiOwner.FindRequiredComponent('ButtonLogClear') as TCastleButton;
525 CheckboxLogAutoScroll := UiOwner.FindRequiredComponent('CheckboxLogAutoScroll') as TCastleCheckbox;
526 LabelProfilerHeader := UiOwner.FindRequiredComponent('LabelProfilerHeader') as TCastleLabel;
527 CheckboxProfilerDetailsInLog := UiOwner.FindRequiredComponent('CheckboxProfilerDetailsInLog') as TCastleCheckbox;
528 CheckboxProfilerMore := UiOwner.FindRequiredComponent('CheckboxProfilerMore') as TCastleCheckbox;
529 CheckboxFileMonitorEnabled := UiOwner.FindRequiredComponent('CheckboxFileMonitorEnabled') as TCastleCheckbox;
530 ProfilerGraph := UiOwner.FindRequiredComponent('ProfilerGraph') as TCastleUserInterface;
531 RectStatsMore := UiOwner.FindRequiredComponent('RectStatsMore') as TCastleUserInterface;
532 LabelStatsMore := UiOwner.FindRequiredComponent('LabelStatsMore') as TCastleLabel;
533 ButtonAutoSelectNothing := UiOwner.FindRequiredComponent('ButtonAutoSelectNothing') as TCastleButton;
534 ButtonAutoSelectUi := UiOwner.FindRequiredComponent('ButtonAutoSelectUi') as TCastleButton;
535 ButtonAutoSelectTransform := UiOwner.FindRequiredComponent('ButtonAutoSelectTransform') as TCastleButton;
536 SafeBorderContainer := UiOwner.FindRequiredComponent('SafeBorderContainer') as TCastleUserInterface;
537 HeaderProfiler := UiOwner.FindRequiredComponent('HeaderProfiler') as TCastleUserInterface;
538 HeaderProfiler2ndRow := UiOwner.FindRequiredComponent('HeaderProfiler2ndRow') as TCastleUserInterface;
539
540 ForceFallbackLook(Ui);
541
542 HierarchyRowParent.OnRender := {$ifdef FPC}@{$endif} BeforeRenderHierarchyRows;
543
544 // TODO: TCastleCheckbox.Enabled would be useful here
545 CheckboxFileMonitorEnabled.{Enabled}Exists := FileMonitor.PossiblyEnabled;
546 CheckboxFileMonitorEnabled.Checked := FileMonitor.Enabled;
547
548 CheckboxShowEvenInternal.OnChange := {$ifdef FPC}@{$endif} UpdateHierarchy;
549 CheckboxUiBatching.OnChange := {$ifdef FPC}@{$endif} ChangeUiBatching;
550 ButtonHierarchyShow.OnClick := {$ifdef FPC}@{$endif} ClickHierarchyShow;
551 ButtonHierarchyHide.OnClick := {$ifdef FPC}@{$endif} ClickHierarchyHide;
552 ButtonLogShow.OnClick := {$ifdef FPC}@{$endif} ClickLogShow;
553 ButtonLogHide.OnClick := {$ifdef FPC}@{$endif} ClickLogHide;
554 ButtonPropertiesShow.OnClick := {$ifdef FPC}@{$endif} ClickPropertiesShow;
555 ButtonPropertiesHide.OnClick := {$ifdef FPC}@{$endif} ClickPropertiesHide;
556 ButtonProfilerShow.OnClick := {$ifdef FPC}@{$endif} ClickProfilerShow;
557 ButtonProfilerHide.OnClick := {$ifdef FPC}@{$endif} ClickProfilerHide;
558 ButtonLogClear.OnClick := {$ifdef FPC}@{$endif} ClickLogClear;
559 CheckboxProfilerDetailsInLog.OnChange := {$ifdef FPC}@{$endif} ChangeProfilerDetailsInLog;
560 CheckboxProfilerMore.OnChange := {$ifdef FPC}@{$endif} ChangeProfilerMore;
561 CheckboxFileMonitorEnabled.OnChange := {$ifdef FPC}@{$endif} ChangeFileMonitorEnabled;
562 ProfilerGraph.OnRender := {$ifdef FPC}@{$endif} ProfilerGraphRender;
563 ButtonAutoSelectNothing.OnClick := {$ifdef FPC}@{$endif} ClickAutoSelectNothing;
564 ButtonAutoSelectUi.OnClick := {$ifdef FPC}@{$endif} ClickAutoSelectUi;
565 ButtonAutoSelectTransform.OnClick := {$ifdef FPC}@{$endif} ClickAutoSelectTransform;
566
567 { initial state of UI to show/hide }
568 RectProperties.Exists := PersistentState.RectPropertiesExists;
569 RectLog.Exists := PersistentState.RectLogExists;
570 RectHierarchy.Exists := PersistentState.RectHierarchyExists;
571 RectProfiler.Exists := PersistentState.RectProfilerExists;
572 RectStatsMore.Exists := RectProfiler.Exists and CheckboxProfilerMore.Checked;
573 SynchronizeButtonsToShow;
574
575 FOpacity := -1; // to force setting below call SetOpacity
576 Opacity := PersistentState.Opacity;
577 SliderOpacity.Value := Opacity;
578 SliderOpacity.OnChange := {$ifdef FPC}@{$endif} ChangeOpacity;
579
580 { initialize Factories }
581 SerializedHierarchyRowFactory := TemplateToFactory(HierarchyRowTemplate);
582 FreeAndNil(HierarchyRowTemplate);
583 SerializedPropertyRowFactory := TemplateToFactory(PropertyRowTemplate);
584 FreeAndNil(PropertyRowTemplate);
585
586 { initialize log }
587 ApplicationProperties.OnLog.Add({$ifdef FPC}@{$endif} LogCallback);
588 LogCount := 0;
589 LabelLogHeader.Caption := Format('Log (%d)', [LogCount]);
590 CheckboxLogAutoScroll.Checked := true;
591 AddLastLogs;
592
593 { initialize profiler }
594 FrameProfiler.Enabled := RectProfiler.Exists;
595 FrameProfiler.OnSummaryAvailable := {$ifdef FPC}@{$endif} ProfilerSummaryAvailable;
596 // FrameProfiler.FramesForSummary := 2; // useful to quickly test
597 CheckboxProfilerDetailsInLog.Checked := FrameProfiler.LogSummary;
598
599 { initialize AutoSelect }
600 AutoSelect := asNothing;
601 SynchronizeButtonsAutoSelect;
602
603 Properties := TPropertyDisplayList.Create(true);
604 end;
605
606 destructor TCastleInspector.Destroy;
607 begin
608 ApplicationProperties.OnLog.Remove({$ifdef FPC}@{$endif} LogCallback);
609
610 { set to nil by SetSelectedComponent, to detach free notification }
611 SelectedComponent := nil;
612
613 { update PersistentState }
614 PersistentState.Opacity := Opacity;
615 PersistentState.RectPropertiesExists := RectProperties.Exists;
616 PersistentState.RectLogExists := RectLog.Exists;
617 PersistentState.RectHierarchyExists := RectHierarchy.Exists;
618 PersistentState.RectProfilerExists := RectProfiler.Exists;
619
620 FrameProfiler.OnSummaryAvailable := nil;
621 FrameProfiler.Enabled := false;
622
623 FreeAndNil(Properties);
624
625 FreeAndNil(SerializedHierarchyRowFactory);
626 FreeAndNil(SerializedPropertyRowFactory);
627
628 inherited;
629 end;
630
631 procedure TCastleInspector.InternalSetContainer(const Value: TCastleContainer);
632 begin
633 inherited;
634 if Container <> nil then
635 CheckboxUiBatching.Checked := Container.UserInterfaceBatching;
636 end;
637
638 function TCastleInspector.Selectable(const C: TComponent): Boolean;
639 begin
640 { Never show Self,
641 this would cause problems as we'll create HierarchyRow to show HierarchyRow instances... }
642 if C = Self then Exit(false);
643
644 Result := (not (csTransient in C.ComponentStyle)) or CheckboxShowEvenInternal.Checked;
645 end;
646
647 procedure TCastleInspector.BeforeRenderHierarchyRows(const Sender: TCastleUserInterface);
648 var
649 AnyRowUi: TCastleUserInterfaceFont;
650 begin
651 { Set THierarchyRowLevelDisplay.Xxx class variables
652 used when rendering rows. }
653 if HierarchyRowParent.ControlsCount > 0 then
654 begin
655 AnyRowUi := HierarchyRowParent.Controls[0] as TCastleUserInterfaceFont;
656 THierarchyRowLevelDisplay.OneLevelWidth :=
657 { Measure using AnyRowUi, to use current font size adjusted to UI scale. }
658 AnyRowUi.Font.TextWidth(DupeString(' ', LevelWidthInSpaces));
659 THierarchyRowLevelDisplay.HierarchyRowHeight :=
660 AnyRowUi.EffectiveHeight * AnyRowUi.UIScale;
661 end;
662 end;
663
664 procedure TCastleInspector.UpdateHierarchy(Sender: TObject);
665
666 { Parts of this are deliberately consistent with TDesignFrame.UpdateDesign. }
667
668 var
669 RowIndex: Integer;
670 PreviousLevel: Cardinal;
671
672 { Add hierarchy entry.
673 @param Level Determines the initial | (and similar) symbols count.
674 @param MainCaption Displayed using prominent (black) font color.
675 @param DimCaption Displayed using dim font color -- it can be used for class name. }
676 procedure AddHierarchyEntryCore(
677 const Level: Cardinal;
678 const MainCaption, DimCaption: String; const RowTag: Pointer);
679 const
680 // CGE editor uses lighter gray, but inspector is often on partially-transparent bg, darker gray looks better
681 //DimColor: TCastleColor = (X: 0.75; Y: 0.75; Z: 0.75; W: 1.0);
682 DimColor: TCastleColor = (X: 0.6; Y: 0.6; Z: 0.6; W: 1.0);
683 var
684 HierarchyButton: TCastleButton;
685 CaptionWithLevel: String;
686 DimLabel: TSimpleLabel;
687 DimLabelX: Single;
688 LevelDisplay: THierarchyRowLevelDisplay;
689 begin
690 if RowIndex < HierarchyRowParent.ControlsCount then
691 begin
692 HierarchyButton := HierarchyRowParent.Controls[RowIndex] as TCastleButton;
693 DimLabel := HierarchyButton.Controls[0] as TSimpleLabel;
694 LevelDisplay := HierarchyButton.Controls[1] as THierarchyRowLevelDisplay;
695 end else
696 begin
697 HierarchyButton := SerializedHierarchyRowFactory.ComponentLoad(Self) as TCastleButton;
698 HierarchyButton.OnClick := {$ifdef FPC}@{$endif} ClickHierarchyRow;
699 HierarchyButton.Culling := true; // many such buttons are often not visible, in scroll view
700 HierarchyButton.Width := RectHierarchy.EffectiveWidthForChildren;
701 HierarchyRowParent.InsertFront(HierarchyButton);
702
703 DimLabel := TSimpleLabel.Create(HierarchyButton);
704 DimLabel.Color := DimColor;
705 DimLabel.Anchor(vpMiddle);
706 HierarchyButton.InsertFront(DimLabel);
707
708 LevelDisplay := THierarchyRowLevelDisplay.Create(HierarchyButton);
709 HierarchyButton.InsertFront(LevelDisplay);
710
711 ForceFallbackLook(HierarchyButton);
712 end;
713
714 CaptionWithLevel := DupeString(' ', Level * LevelWidthInSpaces) + MainCaption;
715
716 HierarchyButton.Caption := CaptionWithLevel;
717
718 DimLabel.Caption := DimCaption;
719 if MainCaption <> '' then
720 DimLabelX := FallbackFont.TextWidth(CaptionWithLevel + ' ')
721 else
722 DimLabelX := FallbackFont.TextWidth(CaptionWithLevel);
723 DimLabel.Anchor(hpLeft, DimLabelX);
724
725 { TComponent.Tag is a (signed) PtrInt in FPC, (signed) NativeInt in Delphi,
726 so typecast to PtrInt to avoid range check errors. }
727 HierarchyButton.Tag := PtrInt(RowTag);
728
729 LevelDisplay.PreviousLevel := PreviousLevel;
730 LevelDisplay.Level := Level;
731
732 Inc(RowIndex);
733 PreviousLevel := Level;
734 end;
735
736 procedure AddHierarchyEntry(const C: TComponent; const Level: Integer);
737 begin
738 AddHierarchyEntryCore(Level, C.Name,' (' + C.ClassName + ')', C);
739 end;
740
741 { Add given component, and its children in C.NonVisualComponents }
742 procedure AddNonVisualComponent(const C: TComponent; const Level: Integer);
743 var
744 Child: TComponent;
745 begin
746 AddHierarchyEntry(C, Level);
747
748 if C is TCastleComponent then
749 begin
750 for Child in TCastleComponent(C).NonVisualComponentsEnumerate do
751 if Selectable(Child) then
752 AddNonVisualComponent(Child, Level + 1);
753 end;
754 end;
755
756 { If C has some NonVisualComponents, then create a tree item
757 'Non-Visual Components' and add them to it. }
758 procedure AddNonVisualComponentsSection(const C: TCastleComponent; const Level: Integer);
759 var
760 Child: TComponent;
761 begin
762 if C.NonVisualComponentsCount <> 0 then
763 begin
764 AddHierarchyEntryCore(Level, 'Non-Visual Components', '', C);
765 for Child in C.NonVisualComponentsEnumerate do
766 if Selectable(Child) then
767 AddNonVisualComponent(Child, Level + 1);
768 end;
769 end;
770
771 { If T has some Behaviors, then create a tree item
772 'Behaviors' and add them to it. }
773 procedure AddBehaviorsSection(const T: TCastleTransform; const Level: Integer);
774 var
775 Child: TCastleBehavior;
776 begin
777 if T.BehaviorsCount <> 0 then
778 begin
779 AddHierarchyEntryCore(Level, 'Behaviors', '', T);
780 for Child in T.BehaviorsEnumerate do
781 if Selectable(Child) then
782 AddNonVisualComponent(Child, Level + 1);
783 end;
784 end;
785
786 { Add given transform, and its children
787 (transform children, T.NonVisualComponents, T.Behaviors). }
788 procedure AddTransform(const T: TCastleTransform; const Level: Integer);
789 var
790 I: Integer;
791 begin
792 AddHierarchyEntry(T, Level);
793
794 AddNonVisualComponentsSection(T, Level + 1);
795 AddBehaviorsSection(T, Level + 1);
796
797 for I := 0 to T.Count - 1 do
798 if Selectable(T[I]) then
799 AddTransform(T[I], Level + 1);
800 end;
801
802 { Add given UI control, and its children. }
803 procedure AddControl(const C: TCastleUserInterface; const Level: Integer);
804 var
805 I: Integer;
806 Viewport: TCastleViewport;
807 begin
808 AddHierarchyEntry(C, Level);
809
810 AddNonVisualComponentsSection(C, Level + 1);
811
812 for I := 0 to C.ControlsCount - 1 do
813 begin
814 if Selectable(C.Controls[I]) then
815 AddControl(C.Controls[I], Level + 1);
816 end;
817
818 if C is TCastleViewport then
819 begin
820 Viewport := TCastleViewport(C);
821 if Selectable(Viewport.Items) then
822 AddTransform(Viewport.Items, Level + 1);
823 end;
824 end;
825
826 var
827 C: TCastleUserInterface;
828 I: Integer;
829 begin
830 { To avoid recreating lots of UI controls each frame,
831 we use RowIndex and AddHierarchyEntry to preserve previous instances of HierarchyRowTemplate
832 across update calls, if possible.
833 In effect, usual call to UpdateHierarchy should be mostly an analysis that says "nothing has
834 changed, so not updating any UI". }
835 RowIndex := 0;
836 PreviousLevel := 0;
837
838 for I := 0 to Container.Controls.Count - 1 do
839 begin
840 C := Container.Controls[I];
841 if Selectable(C) then
842 AddControl(C, 0);
843 end;
844
845 while HierarchyRowParent.ControlsCount > RowIndex do
846 HierarchyRowParent.Controls[RowIndex].Free;
847 end;
848
849 procedure TCastleInspector.UpdateLabelProfilerHeader;
850 begin
851 LabelProfilerHeader.Caption := 'Profiler | Current FPS: ' + Container.Fps.ToString;
852 end;
853
854 procedure TCastleInspector.UpdateLabelStatsMore;
855
856 { Viewport implied by current SelectedComponent.
857 Similar to CGE editor TDesignFrame.SelectedViewport. }
858 function SelectedViewport: TCastleViewport;
859
860 { Return viewport indicated by T, or @nil if none. }
861 function ViewportOfTransform(const T: TCastleTransform): TCastleViewport;
862 begin
863 if T.World <> nil then
864 Result := T.World.Owner as TCastleViewport
865 else
866 Result := nil;
867 end;
868
869 { Return viewport indicated by B, or @nil if none. }
870 function ViewportOfBehavior(const B: TCastleBehavior): TCastleViewport;
871 begin
872 if B.Parent <> nil then
873 Result := ViewportOfTransform(B.Parent)
874 else
875 Result := nil;
876 end;
877
878 { Return viewport indicated by C, or @nil if none. }
879 function ViewportOfComponent(const C: TComponent): TCastleViewport;
880 var
881 ViewportChild: TCastleUserInterface;
882 begin
883 Result := nil;
884
885 if C is TCastleViewport then
886 begin
887 Result := C as TCastleViewport;
888 end else
889 if C is TCastleUserInterface then
890 begin
891 { When hovering over TCastleNavigation, or TCastleTouchNavigation,
892 or really any UI as viewport child -> select viewport. }
893 ViewportChild := C as TCastleUserInterface;
894 if {ViewportChild.FullSize and} (ViewportChild.Parent is TCastleViewport) then
895 begin
896 Result := ViewportChild.Parent as TCastleViewport;
897 end;
898 end else
899 if C is TCastleTransform then
900 Result := ViewportOfTransform(C as TCastleTransform)
901 else
902 if C is TCastleBehavior then
903 Result := ViewportOfBehavior(C as TCastleBehavior);
904 end;
905
906 begin
907 Result := ViewportOfComponent(SelectedComponent);
908 end;
909
910 { Viewport to act on.
911 Similar to CGE editor TDesignFrame.CurrentViewport, that has similar goal. }
912 function CurrentViewport: TCastleViewport;
913 var
914 HoverUi: TCastleUserInterface;
915 begin
916 Result := SelectedViewport;
917 if Result = nil then
918 begin
919 { try HoverUserInterface as TCastleViewport }
920 HoverUi := HoverUserInterface(Container.MousePosition);
921 if HoverUi is TCastleViewport then // also checks HoverUi <> nil
922 Result := TCastleViewport(HoverUi)
923 else
924 { try HoverUserInterface as TCastleViewport child, like TCastleNavigation, TCastleTouchNavigation }
925 if (HoverUi <> nil) and (HoverUi.Parent is TCastleViewport) then // also checks HoverUi.Parent <> nil
926 Result := TCastleViewport(HoverUi.Parent);
927 end;
928 end;
929
930 var
931 S: String;
932 CurrentV: TCastleViewport;
933 begin
934 if CheckboxProfilerMore.Checked then
935 begin
936 S := 'TDrawableImage.Statistics: ' + TDrawableImage.Statistics.ToString + NL +
937 ' (TODO: Rendering inspector may easily cause ~100 draw calls now. Better UI batching is coming.)';
938 CurrentV := CurrentViewport;
939 if CurrentV <> nil then
940 begin
941 S := S + NL +
942 'Viewport "' + CurrentV.Name + '":' + NL +
943 CurrentV.Statistics.ToString;
944 end;
945 LabelStatsMore.Caption := S;
946 end;
947 end;
948
949 procedure TCastleInspector.ChangeUiBatching(Sender: TObject);
950 begin
951 Container.UserInterfaceBatching := CheckboxUiBatching.Checked;
952 end;
953
954 function TCastleInspector.HoverUserInterface(const AMousePosition: TVector2): TCastleUserInterface;
955
956 { Like TCastleUserInterface.CapturesEventsAtPosition, but
957 - ignores CapturesEvents
958 - uses RenderRectWithBorder (to be able to drag complete control)
959 - doesn't need "if the control covers the whole Container" hack. }
960 function SimpleCapturesEventsAtPosition(const UI: TCastleUserInterface;
961 const Position: TVector2; const TestWithBorder: Boolean): Boolean;
962 begin
963 if TestWithBorder then
964 Result := UI.RenderRectWithBorder.Contains(Position)
965 else
966 Result := UI.RenderRect.Contains(Position);
967 end;
968
969 function ControlUnder(const C: TCastleUserInterface;
970 const MousePos: TVector2; const TestWithBorder: Boolean): TCastleUserInterface;
971 var
972 I: Integer;
973 begin
974 Result := nil;
975
976 { To allow selecting even controls that have bad rectangle (outside
977 of parent, which can happen, e.g. if you enlarge caption of label
978 with AutoSize), do not check C.CapturesEventsAtPosition(MousePos)
979 too early here. So the condition
980
981 and C.CapturesEventsAtPosition(MousePos)
982
983 is not present in "if" below. }
984
985 if C.Exists then
986 begin
987 { First try to find children, with TestWithBorder=false (so it doesn't detect
988 control if we merely point at its border). This allows to find controls
989 places on another control's border. }
990 for I := C.ControlsCount - 1 downto 0 do
991 if Selectable(C.Controls[I]) then
992 begin
993 Result := ControlUnder(C.Controls[I], MousePos, false);
994 if Result <> nil then Exit;
995 end;
996
997 { Next try to find children, with TestWithBorder=true, so it tries harder
998 to find something. }
999 for I := C.ControlsCount - 1 downto 0 do
1000 if Selectable(C.Controls[I]) then
1001 begin
1002 Result := ControlUnder(C.Controls[I], MousePos, true);
1003 if Result <> nil then Exit;
1004 end;
1005
1006 { Eventually return yourself, C. }
1007 //if C.CapturesEventsAtPosition(MousePos) then
1008 if SimpleCapturesEventsAtPosition(C, MousePos, TestWithBorder) and
1009 C.EditorSelectOnHover then
1010 Result := C;
1011 end;
1012 end;
1013
1014 var
1015 I: Integer;
1016 begin
1017 Result := nil;
1018 for I := Container.Controls.Count - 1 downto 0 do
1019 if Container.Controls[I] <> Self then
1020 begin
1021 Result := ControlUnder(Container.Controls[I], AMousePosition, true);
1022 if Result <> nil then Exit;
1023 end;
1024 end;
1025
1026 function TCastleInspector.HoverTransform(const AMousePosition: TVector2): TCastleTransform;
1027 var
1028 UI: TCastleUserInterface;
1029 Viewport: TCastleViewport;
1030 RayOrigin, RayDirection: TVector3;
1031 RayHit: TRayCollision;
1032 I: Integer;
1033 begin
1034 UI := HoverUserInterface(AMousePosition);
1035 if UI is TCastleViewport then // also checks UI <> nil
1036 Viewport := TCastleViewport(UI)
1037 else
1038 Viewport := nil;
1039
1040 if Viewport = nil then
1041 Exit(nil);
1042
1043 Viewport.PositionToRay(AMousePosition, true, RayOrigin, RayDirection);
1044 RayHit := Viewport.Items.WorldRay(RayOrigin, RayDirection);
1045 try
1046 Result := nil;
1047 // set the inner-most TCastleTransform hit, but not anything transient (to avoid hitting gizmo)
1048 if RayHit <> nil then
1049 for I := 0 to RayHit.Count - 1 do
1050 if Selectable(RayHit[I].Item) then
1051 begin
1052 Result := RayHit[I].Item;
1053 Break;
1054 end;
1055 finally FreeAndNil(RayHit) end;
1056 end;
1057
1058 procedure TCastleInspector.Update(const SecondsPassed: Single; var HandleInput: boolean);
1059
1060 procedure UpdateAutoSelect;
1061 var
1062 C: TComponent;
1063 begin
1064 case AutoSelect of
1065 asUi: C := HoverUserInterface(Container.MousePosition);
1066 asTransform: C := HoverTransform(Container.MousePosition);
1067 else Exit; // on asNothing, just Exit
1068 end;
1069 { do not change SelectedComponent to nil, this avoids e.g. unselecting UI when going into
1070 asTransform mode for a short time. }
1071 if C <> nil then
1072 SelectedComponent := C;
1073 end;
1074
1075 procedure UpdateSafeBorder;
1076 var
1077 B: TBorder;
1078 begin
1079 { Honor Container.SafeBorder, to
1080 - avoid showing inspector where it would be obscured
1081 - also to show to user that it is correct. }
1082 B := Container.SafeBorder;
1083 SafeBorderContainer.Border.Top := B.Top;
1084 SafeBorderContainer.Border.Right := B.Right;
1085 SafeBorderContainer.Border.Bottom := B.Bottom;
1086 SafeBorderContainer.Border.Left := B.Left;
1087 end;
1088
1089 { When width is small (e.g. on potrait mobile resolutions)
1090 we need 2nd row to display full "Profiler" header. }
1091 procedure UpdateHeaderProfilerNeeds2ndRow;
1092
1093 { Change Control's parent. NewParent may be @nil. }
1094 procedure ChangeParent(const Control, NewParent: TCastleUserInterface);
1095 begin
1096 if Control.Parent <> nil then
1097 Control.Parent.RemoveControl(Control);
1098 if NewParent <> nil then
1099 NewParent.InsertFront(Control);
1100 end;
1101
1102 const
1103 RectProfilerHeightFractionInitial = 0.15;
1104 var
1105 Needs2ndRow: Boolean;
1106 begin
1107 Needs2ndRow := LabelProfilerHeader.EffectiveWidth >
1108 HeaderProfiler.EffectiveWidth
1109 - CheckboxProfilerMore.EffectiveWidth
1110 - CheckboxProfilerDetailsInLog.EffectiveWidth
1111 - ButtonProfilerHide.EffectiveWidth;
1112 if HeaderProfiler2ndRow.Exists <> Needs2ndRow then
1113 begin
1114 HeaderProfiler2ndRow.Exists := Needs2ndRow;
1115 if Needs2ndRow then
1116 begin
1117 ProfilerGraph.Border.Top := HeaderProfiler.EffectiveHeight + HeaderProfiler2ndRow.EffectiveHeight;
1118 RectProfiler.HeightFraction := 0;
1119 RectProfiler.Height :=
1120 RectProfilerHeightFractionInitial * RectProfiler.Parent.EffectiveHeight +
1121 HeaderProfiler2ndRow.EffectiveHeight;
1122 ChangeParent(CheckboxProfilerMore, HeaderProfiler2ndRow);
1123 ChangeParent(CheckboxProfilerDetailsInLog, HeaderProfiler2ndRow);
1124 end else
1125 begin
1126 ProfilerGraph.Border.Top := HeaderProfiler.EffectiveHeight;
1127 RectProfiler.HeightFraction := RectProfilerHeightFractionInitial;
1128 ChangeParent(CheckboxProfilerMore, HeaderProfiler);
1129 ChangeParent(CheckboxProfilerDetailsInLog, HeaderProfiler);
1130 end;
1131 end;
1132 end;
1133
1134 { Update RectStatsMore.Translation,
1135 necessary when RectProfiler.EffectiveRect changes.
1136 Easiest to just do it from Update. }
1137 procedure UpdateRectStatsMoreTranslation;
1138 begin
1139 RectStatsMore.Translation := Vector2(
1140 RectProfiler.EffectiveRect.Left,
1141 RectProfiler.Translation.Y - RectProfiler.EffectiveHeight);
1142 end;
1143
1144 const
1145 { Delay between updating properties. }
1146 UpdatePropertiesValuesInterval = 0.5;
1147 var
1148 InspectorInputStr: String;
1149 begin
1150 inherited;
1151 UpdateHierarchy(nil);
1152
1153 UpdateLabelProfilerHeader;
1154 UpdateLabelStatsMore;
1155
1156 InspectorInputStr := Container.InputInspector.ToString;
1157 LabelInspectorHelp.Exists := InspectorInputStr <> '';
1158 if LabelInspectorHelp.Exists then
1159 LabelInspectorHelp.Caption :=
1160 { Two lines are safer to fit longer InspectorInputStr, but we need
1161 vertical space to show "Monitor and Auto-Reload" checkbox ... }
1162 //'Hide inspector by ' + NL + ' ' + InspectorInputStr + '.';
1163 'Hide inspector: ' + InspectorInputStr;
1164
1165 UpdateAutoSelect;
1166
1167 if RectProperties.Exists then // do not do UpdatePropertiesValues when not visible, to save speed
1168 begin
1169 TimeToUpdatePropertiesValues := TimeToUpdatePropertiesValues - SecondsPassed;
1170 if TimeToUpdatePropertiesValues < 0 then
1171 begin
1172 UpdatePropertiesValues;
1173 TimeToUpdatePropertiesValues := UpdatePropertiesValuesInterval;
1174 end;
1175 end;
1176
1177 UpdateSafeBorder;
1178 UpdateHeaderProfilerNeeds2ndRow;
1179 UpdateRectStatsMoreTranslation;
1180 end;
1181
1182 procedure TCastleInspector.ChangeOpacity(Sender: TObject);
1183 begin
1184 Opacity := SliderOpacity.Value;
1185 end;
1186
1187 procedure TCastleInspector.SetOpacity(const Value: Single);
1188 begin
1189 if FOpacity <> Value then
1190 begin
1191 FOpacity := Value;
1192 RectOptions.ColorPersistent.Alpha := Value;
1193 RectProperties.ColorPersistent.Alpha := Value;
1194 RectLog.ColorPersistent.Alpha := Value;
1195 RectProfiler.ColorPersistent.Alpha := Value;
1196 RectHierarchy.ColorPersistent.Alpha := Value;
1197 end;
1198 end;
1199
1200 procedure TCastleInspector.SynchronizeButtonsToShow;
1201 begin
1202 ButtonLogShow.Exists := not RectLog.Exists;
1203 ButtonPropertiesShow.Exists := not RectProperties.Exists;
1204 ButtonHierarchyShow.Exists := not RectHierarchy.Exists;
1205 ButtonProfilerShow.Exists := not RectProfiler.Exists;
1206 HorizontalGroupShow.Exists :=
1207 ButtonHierarchyShow.Exists or
1208 ButtonLogShow.Exists or
1209 ButtonPropertiesShow.Exists or
1210 ButtonProfilerShow.Exists;
1211 end;
1212
1213 procedure TCastleInspector.ClickHierarchyShow(Sender: TObject);
1214 begin
1215 RectHierarchy.Exists := true;
1216 SynchronizeButtonsToShow;
1217 end;
1218
1219 procedure TCastleInspector.ClickHierarchyHide(Sender: TObject);
1220 begin
1221 RectHierarchy.Exists := false;
1222 SynchronizeButtonsToShow;
1223 end;
1224
1225 procedure TCastleInspector.ClickLogShow(Sender: TObject);
1226 begin
1227 RectLog.Exists := true;
1228 SynchronizeButtonsToShow;
1229 end;
1230
1231 procedure TCastleInspector.ClickLogHide(Sender: TObject);
1232 begin
1233 RectLog.Exists := false;
1234 SynchronizeButtonsToShow;
1235 end;
1236
1237 procedure TCastleInspector.ClickPropertiesShow(Sender: TObject);
1238 begin
1239 RectProperties.Exists := true;
1240 SynchronizeButtonsToShow;
1241 { We didn't update properties values when RectProperties.Exists was false,
1242 so update them now. }
1243 UpdatePropertiesValues;
1244 end;
1245
1246 procedure TCastleInspector.ClickPropertiesHide(Sender: TObject);
1247 begin
1248 RectProperties.Exists := false;
1249 SynchronizeButtonsToShow;
1250 end;
1251
1252 procedure TCastleInspector.ClickProfilerShow(Sender: TObject);
1253 begin
1254 RectProfiler.Exists := true;
1255 RectStatsMore.Exists := RectProfiler.Exists and CheckboxProfilerMore.Checked;
1256 SynchronizeButtonsToShow;
1257 end;
1258
1259 procedure TCastleInspector.ClickProfilerHide(Sender: TObject);
1260 begin
1261 RectProfiler.Exists := false;
1262 RectStatsMore.Exists := RectProfiler.Exists and CheckboxProfilerMore.Checked;
1263 SynchronizeButtonsToShow;
1264 end;
1265
1266 procedure TCastleInspector.LogCallback(const Message: String);
1267 const
1268 { Do not keep too many logs, to not slow down rendering. }
1269 MaxLogs = 100;
1270 var
1271 NewLabelLog: TCastleLabel;
1272 begin
1273 { Use InsideLogCallback to prevent from infinite recursion,
1274 in case anything inside would also cause WritelnLog. }
1275 if InsideLogCallback then Exit;
1276
1277 InsideLogCallback := true;
1278 try
1279 if LogsVerticalGroup.ControlsCount = MaxLogs then
1280 begin
1281 LogsVerticalGroup.Controls[1].Free; // free 1st, leave LabelEarlierLogsRemoved
1282 LabelEarlierLogsRemoved.Exists := true;
1283 end;
1284
1285 { Creating new TCastleLabel for each log is more efficient than stuffing all logs
1286 into one big TCastleLabel, tested (with "Log Details" of profiler). }
1287 NewLabelLog := TCastleLabel.Create(Self);
1288 ForceFallbackLook(NewLabelLog);
1289 NewLabelLog.Text.AddMultiLine(TrimEndingNewline(Message));
1290 NewLabelLog.Culling := true; // makes rendering much faster in case of multiple logs
1291 LogsVerticalGroup.InsertFront(NewLabelLog);
1292
1293 Inc(LogCount);
1294 LabelLogHeader.Caption := Format('Log (%d)', [LogCount]);
1295 if CheckboxLogAutoScroll.Checked then
1296 ScrollLogs.Scroll := ScrollLogs.ScrollMax;
1297 finally InsideLogCallback := false end;
1298 end;
1299
1300 procedure TCastleInspector.ClickLogClear(Sender: TObject);
1301 begin
1302 LogCount := 0;
1303 LabelLogHeader.Caption := Format('Log (%d)', [LogCount]);
1304 LogsVerticalGroup.ClearControls;
1305 LabelEarlierLogsRemoved.Exists := false;
1306 end;
1307
1308 procedure TCastleInspector.ClickHierarchyRow(Sender: TObject);
1309 begin
1310 SelectedComponent := TComponent(Pointer((Sender as TCastleButton).Tag));
1311 end;
1312
1313 procedure TCastleInspector.SetSelectedComponent(const Value: TComponent);
1314
1315 { Used to display C as String. }
1316 function ComponentCaption(const C: TComponent): String;
1317 begin
1318 Result := C.Name + ' (' + C.ClassName + ')';
1319 end;
1320
1321 var
1322 HierarchyRow: TCastleUserInterface;
1323 HierachyRowButton: TCastleButton;
1324 begin
1325 if FSelectedComponent <> Value then
1326 begin
1327 if FSelectedComponent <> nil then
1328 FSelectedComponent.RemoveFreeNotification(Self);
1329 FSelectedComponent := Value;
1330 if FSelectedComponent <> nil then
1331 FSelectedComponent.FreeNotification(Self);
1332
1333 for HierarchyRow in HierarchyRowParent do
1334 begin
1335 HierachyRowButton := HierarchyRow as TCastleButton;
1336 HierachyRowButton.Pressed := TComponent(Pointer(HierachyRowButton.Tag)) = FSelectedComponent;
1337 end;
1338
1339 if FSelectedComponent <> nil then
1340 LabelPropertiesHeader.Caption := 'Properties - ' + ComponentCaption(FSelectedComponent)
1341 else
1342 LabelPropertiesHeader.Caption := 'Properties';
1343
1344 ScrollProperties.Scroll := ScrollProperties.ScrollMin;
1345
1346 UpdateProperties;
1347 end;
1348 end;
1349
1350 procedure TCastleInspector.Notification(AComponent: TComponent; Operation: TOperation);
1351 begin
1352 inherited;
1353 if (Operation = opRemove) and (AComponent = FSelectedComponent) then
1354 { set to nil by SetSelectedComponent to clean nicely }
1355 SelectedComponent := nil;
1356 end;
1357
1358 procedure TCastleInspector.UpdateProperties;
1359
1360 procedure AddPropertyRow(const PropObject: TObject; const PropInfo: PPropInfo;
1361 const PropName: String);
1362 var
1363 PropertyDisplay: TPropertyDisplay;
1364 begin
1365 PropertyDisplay := TPropertyDisplay.Create(Self);
1366
1367 PropertyDisplay.Ui := SerializedPropertyRowFactory.ComponentLoad(PropertyDisplay) as TCastleUserInterface;
1368 PropertyDisplay.Ui.Culling := true; // many such rows are often not visible, in scroll view
1369 PropertyDisplay.Ui.Width := RectProperties.EffectiveWidthForChildren;
1370
1371 PropertyDisplay.Initialize(PropObject, PropInfo, PropName);
1372
1373 Properties.Add(PropertyDisplay);
1374 PropertyRowParent.InsertFront(PropertyDisplay.Ui);
1375 end;
1376
1377 function PropertyShow(const PropObject: TComponent; const PropInfo: PPropInfo): Boolean;
1378 var
1379 PropName: String;
1380 begin
1381 PropName := PropInfo^.Name;
1382 if (PropName = 'Name') and
1383 (csSubComponent in PropObject.ComponentStyle) then
1384 begin
1385 { Do not show names of subcomponents, they are not useful (to view or edit).
1386 CastleComponentSerialize also doesn't save them (see TCastleJsonWriter.StreamProperty),
1387 CGE editor also doesn't show them (see TDesignFrame.InspectorFilter). }
1388 Exit(false);
1389 end;
1390
1391 Result := true;
1392 end;
1393
1394 var
1395 PropInfos: TPropInfoList;
1396 PropInfo: PPropInfo;
1397 I: Integer;
1398 PropName, PropValue: String;
1399 begin
1400 // frees TPropertyOwner instances along with their UIs
1401 Properties.Clear;
1402
1403 if FSelectedComponent <> nil then
1404 begin
1405 PropInfos := TPropInfoList.Create(FSelectedComponent, tkProperties);
1406 try
1407 for I := 0 to PropInfos.Count - 1 do
1408 begin
1409 PropInfo := PropInfos.Items[I];
1410 if PropertyShow(FSelectedComponent, PropInfo) and
1411 { We get but don't actually pass PropValue to AddPropertyRow,
1412 UpdateCurrentValue (called by AddPropertyRow) will read it again. }
1413 PropertyGet(FSelectedComponent, PropInfo, PropName, PropValue) then
1414 AddPropertyRow(FSelectedComponent, PropInfo, PropName);
1415 end;
1416 finally FreeAndNil(PropInfos) end;
1417 end;
1418 end;
1419
1420 procedure TCastleInspector.UpdatePropertiesValues;
1421 var
1422 Po: TPropertyDisplay;
1423 begin
1424 for Po in Properties do
1425 Po.UpdateCurrentValue;
1426 end;
1427
1428 procedure TCastleInspector.Resize;
1429 var
1430 C: TCastleUserInterface;
1431 begin
1432 inherited;
1433
1434 // TODO: doing this in constructor makes a wild scrollbar move
1435 if CheckboxLogAutoScroll.Checked then
1436 ScrollLogs.Scroll := ScrollLogs.ScrollMax;
1437
1438 { We need to manually adjust rows widths to follow available space,
1439 righ now this is not doable by simple properties,
1440 because ScrollArea looks at children for size (and we cannot look
1441 at children for height, but at the same time determine children width). }
1442 for C in HierarchyRowParent do
1443 C.Width := RectHierarchy.EffectiveWidthForChildren;
1444 for C in PropertyRowParent do
1445 C.Width := RectProperties.EffectiveWidthForChildren;
1446 end;
1447
1448 procedure TCastleInspector.ChangeProfilerDetailsInLog(Sender: TObject);
1449 begin
1450 FrameProfiler.LogSummary := CheckboxProfilerDetailsInLog.Checked;
1451 end;
1452
1453 procedure TCastleInspector.ChangeProfilerMore(Sender: TObject);
1454 begin
1455 RectStatsMore.Exists := RectProfiler.Exists and CheckboxProfilerMore.Checked;
1456 UpdateLabelProfilerHeader;
1457 end;
1458
1459 procedure TCastleInspector.ProfilerSummaryAvailable(Sender: TObject);
1460 var
1461 Data: PProfilerDataItem;
1462 TotalTime: TFloatTime;
1463 begin
1464 { Container = nil may happen if TCastleInspector exists,
1465 but is no longer on the Window.Controls, e.g. if you invoke Window.FileDialog. }
1466 if Container = nil then
1467 Exit;
1468
1469 Data := @ProfilerData[ProfilerDataLast];
1470
1471 TotalTime := FrameProfiler.SummaryTotalFrameTime;
1472
1473 // fmRender includes fmRenderSwapFlush, we make them separate for display
1474 Data^.Time[pmRender] := (FrameProfiler.SummaryTime(fmRender) - FrameProfiler.SummaryTime(fmRenderSwapFlush)) / TotalTime;
1475 Data^.Time[pmSwap] := FrameProfiler.SummaryTime(fmRenderSwapFlush) / TotalTime;
1476 // fmUpdate includes fmUpdatePhysics, we make them separate for display
1477 Data^.Time[pmUpdate] := (FrameProfiler.SummaryTime(fmUpdate) - FrameProfiler.SummaryTime(fmUpdatePhysics)) / TotalTime;
1478 Data^.Time[pmPhysics] := FrameProfiler.SummaryTime(fmUpdatePhysics) / TotalTime;
1479
1480 Data^.Fps := Container.Fps.RealFps;
1481
1482 if ProfilerDataNonEmpty and (ProfilerDataLast = ProfilerDataFirst) then
1483 ProfilerDataFirst := (ProfilerDataFirst + 1) mod ProfilerDataCount;
1484 ProfilerDataLast := (ProfilerDataLast + 1) mod ProfilerDataCount;
1485 ProfilerDataNonEmpty := true;
1486 end;
1487
1488 procedure TCastleInspector.ProfilerGraphRender(const Sender: TCastleUserInterface);
1489 const
1490 { Use instant_fpc_color_hex_to_pascal to easily convert hex colors to TCastleColor
1491 Pascal constants. }
1492 Colors: array [TProfilerMetric] of TCastleColor = (
1493 (X:1.00; Y: 1.00; Z: 0.00; W: 1.00), // hex: FFFF00
1494 (X:0.48; Y: 0.48; Z: 0.00; W: 1.00), // hex: 7A7A00
1495 (X:0.40; Y: 0.40; Z: 1.00; W: 1.00), // hex: 6767FF
1496 (X:0.69; Y: 0.69; Z: 1.00; W: 1.00) // hex: B1B1FF
1497 );
1498 ColorFpsHex: TCastleColor = (X:0.00; Y: 0.70; Z: 0.00; W: 1.00); // hex: 00B300
1499 type
1500 TTimeSum = array [TProfilerMetric] of Single;
1501 TProfilerItemDraw = record
1502 { For each metric: sum of time of this metric + lower metrics, in 0..1. }
1503 TimeSum: TTimeSum;
1504 { From 0 upward. }
1505 Index: Integer;
1506 { From ProfilerDataFirst to ProfilerDataLast-1. }
1507 DataIndex: Integer;
1508 { FPS in 0..1 range. }
1509 Fps: Single;
1510 end;
1511 PProfilerItemDraw = ^TProfilerItemDraw;
1512
1513 { Calcualate ItemDraw.TimeSum, Fps based on ProfilerData[ItemDraw.DataIndex]. }
1514 procedure CalculateItemDraw(var ItemDraw: TProfilerItemDraw);
1515 const
1516 FpsMiddle = 60.0;
1517 var
1518 Data: PProfilerDataItem;
1519 TimeSum: Single;
1520 Metric: TProfilerMetric;
1521 begin
1522 Data := @ProfilerData[ItemDraw.DataIndex];
1523 TimeSum := 0;
1524 for Metric := High(TProfilerMetric) downto Low(TProfilerMetric) do
1525 begin
1526 TimeSum := TimeSum + Data^.Time[Metric];
1527 ItemDraw.TimeSum[Metric] := TimeSum;
1528 end;
1529 ItemDraw.Fps := Clamped(Data^.Fps * 0.5 / FpsMiddle, 0, 1);
1530 end;
1531
1532 var
1533 RR: TFloatRectangle;
1534 Triangles: array [TProfilerMetric] of array of TVector2;
1535 PointsFps: array of TVector2;
1536 CurrentDataCount: Integer;
1537 Previous, Next: TProfilerItemDraw;
1538 Metric: TProfilerMetric;
1539 {ItemWidth, }X1, X2, Y1, Y2: Single;
1540 begin
1541 if not ProfilerDataNonEmpty then Exit; // empty data
1542
1543 if ProfilerDataLast <= ProfilerDataFirst then
1544 CurrentDataCount := ProfilerDataLast + ProfilerDataCount - ProfilerDataFirst
1545 else
1546 CurrentDataCount := ProfilerDataLast - ProfilerDataFirst;
1547 Assert(Between(CurrentDataCount, 1, ProfilerDataCount));
1548
1549 { Allocate all necessary memory for TVector2 arrays }
1550 for Metric := Low(TProfilerMetric) to High(TProfilerMetric) do
1551 SetLength(Triangles[Metric], 6 * (CurrentDataCount - 1));
1552 SetLength(PointsFps, CurrentDataCount);
1553
1554 RR := ProfilerGraph.RenderRect;
1555 { (ProfilerDataCount - 1) is maximum number of rectangles we want to squeeze
1556 within ProfilerGraph area. }
1557 //ItemWidth := RR.Width / (ProfilerDataCount - 1);
1558
1559 Next.Index := 0;
1560 Next.DataIndex := ProfilerDataFirst;
1561 CalculateItemDraw(Next);
1562 PointsFps[0] := Vector2(RR.Left, Lerp(Next.Fps, RR.Bottom, RR.Top));
1563
1564 { Calculate contents of Triangles by iteration over available data items.
1565 This has to be fast, and generate efficient lists to render graphs using
1566 only a few draw calls. }
1567 while (Next.DataIndex + 1) mod ProfilerDataCount <> ProfilerDataLast do
1568 begin
1569 Previous := Next;
1570 Inc(Next.Index);
1571 Next.DataIndex := (Next.DataIndex + 1) mod ProfilerDataCount;
1572 CalculateItemDraw(Next);
1573
1574 X1 := Lerp(Previous.Index / (ProfilerDataCount - 1), RR.Left, RR.Right);
1575 X2 := Lerp(Next.Index / (ProfilerDataCount - 1), RR.Left, RR.Right);
1576
1577 PointsFps[Next.Index] := Vector2(X2, Lerp(Next.Fps, RR.Bottom, RR.Top));
1578
1579 for Metric := Low(TProfilerMetric) to High(TProfilerMetric) do
1580 begin
1581 Y1 := Lerp(Previous.TimeSum[Metric], RR.Bottom, RR.Top);
1582 Y2 := Lerp(Next.TimeSum[Metric], RR.Bottom, RR.Top);
1583 { use 2 triangles to express a quad, from old to new data point }
1584 Triangles[Metric][6 * Previous.Index ] := Vector2(X1, RR.Bottom);
1585 Triangles[Metric][6 * Previous.Index + 1] := Vector2(X2, RR.Bottom);
1586 Triangles[Metric][6 * Previous.Index + 2] := Vector2(X2, Y2);
1587 Triangles[Metric][6 * Previous.Index + 3] := Vector2(X1, RR.Bottom);
1588 Triangles[Metric][6 * Previous.Index + 4] := Vector2(X2, Y2);
1589 Triangles[Metric][6 * Previous.Index + 5] := Vector2(X1, Y1);
1590 end;
1591 end;
1592
1593 Assert(Next.Index + 1 = CurrentDataCount);
1594
1595 for Metric := Low(TProfilerMetric) to High(TProfilerMetric) do
1596 DrawPrimitive2D(pmTriangles, Triangles[Metric], Colors[Metric]);
1597
1598 DrawPrimitive2D(pmLineStrip, PointsFps, ColorFpsHex);
1599 end;
1600
1601 function TCastleInspector.Press(const Event: TInputPressRelease): Boolean;
1602 begin
1603 Result := inherited;
1604 if Result then Exit; // allow the ancestor to handle keys
1605
1606 if Event.IsKey(keyF9) then
1607 begin
1608 if AutoSelect = High(AutoSelect) then
1609 AutoSelect := Low(AutoSelect)
1610 else
1611 AutoSelect := Succ(AutoSelect);
1612 SynchronizeButtonsAutoSelect;
1613 Exit(true);
1614 end;
1615 end;
1616
1617 procedure TCastleInspector.SynchronizeButtonsAutoSelect;
1618 begin
1619 ButtonAutoSelectNothing.Pressed := AutoSelect = asNothing;
1620 ButtonAutoSelectUi.Pressed := AutoSelect = asUi;
1621 ButtonAutoSelectTransform.Pressed := AutoSelect = asTransform;
1622 end;
1623
1624 procedure TCastleInspector.ClickAutoSelectNothing(Sender: TObject);
1625 begin
1626 AutoSelect := asNothing;
1627 SynchronizeButtonsAutoSelect;
1628 end;
1629
1630 procedure TCastleInspector.ClickAutoSelectUi(Sender: TObject);
1631 begin
1632 AutoSelect := asUi;
1633 SynchronizeButtonsAutoSelect;
1634 end;
1635
1636 procedure TCastleInspector.ClickAutoSelectTransform(Sender: TObject);
1637 begin
1638 AutoSelect := asTransform;
1639 SynchronizeButtonsAutoSelect;
1640 end;
1641
1642 procedure TCastleInspector.ChangeFileMonitorEnabled(Sender: TObject);
1643 begin
1644 FileMonitor.Enabled := CheckboxFileMonitorEnabled.Checked;
1645 end;
1646
1647 initialization
1648 TCastleInspector.PersistentState.Opacity := TCastleInspector.DefaultOpacity;
1649 TCastleInspector.PersistentState.RectPropertiesExists := true;
1650 TCastleInspector.PersistentState.RectLogExists := true;
1651 TCastleInspector.PersistentState.RectHierarchyExists := true;
1652 TCastleInspector.PersistentState.RectProfilerExists := true;
1653 end.