Debian Codegraph @

src/base/castleapplicationproperties.pas

raw
1 {
2 Copyright 2014-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 { Events and properties of the Castle Game Engine application
17 (TCastleApplicationProperties). }
18 unit CastleApplicationProperties;
19
20 {$I castleconf.inc}
21
22 interface
23
24 uses SysUtils, Generics.Collections, Contnrs, Classes,
25 CastleClassUtils;
26
27 type
28 TGLContextEvent = procedure;
29
30 TGLContextEventList = class({$ifdef FPC}specialize{$endif} TList<TGLContextEvent>)
31 public
32 { Call all items, first to last. }
33 procedure ExecuteForward;
34 { Call all items, last to first. }
35 procedure ExecuteBackward;
36 end;
37
38 TWarningEvent = procedure (const Category, Message: String) of object;
39 TLogEvent = procedure (const Message: String) of object;
40
41 TWarningEventList = class({$ifdef FPC}specialize{$endif} TList<TWarningEvent>)
42 public
43 procedure ExecuteAll(const Category, Message: String);
44 end;
45
46 TLogEventList = class({$ifdef FPC}specialize{$endif} TList<TLogEvent>)
47 public
48 procedure ExecuteAll(const Message: String);
49 end;
50
51 { Events and properties of the Castle Game Engine application,
52 usually accessed through the @link(ApplicationProperties) singleton.
53
54 These members work regardless if you use CastleWindow or CastleControl.
55 For more fine-grained application control,
56 see TCastleApplication (in case you use CastleWindow)
57 or Lazarus (LCL) TApplication (in case you use CastleControl). }
58 TCastleApplicationProperties = class
59 private
60 FIsGLContextOpen, FFileAccessSafe: boolean;
61 FOnGLContextEarlyOpen, FOnGLContextOpen, FOnGLContextClose: TGLContextEventList;
62 FOnUpdate, FOnInitializeJavaActivity,
63 FOnGLContextOpenObject, FOnGLContextCloseObject,
64 FOnPause, FOnResume: TNotifyEventList;
65 FOnWarning: TWarningEventList;
66 FOnLog: TLogEventList;
67 FOnInitializeDebug: TProcedureList;
68 FVersion: String;
69 FTouchDevice: boolean;
70 FLimitFPS: Single;
71 FShowUserInterfaceToQuit: Boolean;
72 FCaption: String;
73 // Maybe we will expose them as public read-only properties in the future.
74 FInitializedDebug: Boolean;
75 FInitializedRelease: Boolean;
76 FPendingToFree: TComponentList;
77 function GetApplicationName: String;
78 procedure SetApplicationName(const Value: String);
79 procedure DoPendingFree;
80 public
81 const
82 DefaultLimitFPS = 120.0;
83
84 { Some platforms do not support Application.ProcessMessages, which means you
85 cannot just write a function like MessageYesNo that waits until user clicks
86 something.
87 You *have* to implement modal boxes then using views,
88 e.g. using CastleDialogViews or your own TCastleView descendants. }
89 PlatformAllowsModalRoutines = {$if defined(CASTLE_IOS) or defined(CASTLE_NINTENDO_SWITCH)} false {$else} true {$endif};
90
91 constructor Create;
92 destructor Destroy; override;
93
94 { Application short name.
95 Used e.g. by @link(InitializeLog) to name the log file.
96
97 When compiled with FPC, this returns and sets the same thing
98 as standard SysUtils.ApplicationName.
99 When setting this, we automatically set SysUtils.OnGetApplicationName. }
100 property ApplicationName: String read GetApplicationName write SetApplicationName;
101
102 { @abstract(Pretty application name, to show to user e.g. as a window caption.) }
103 property Caption: String read FCaption write FCaption;
104
105 { Version of this application.
106 It may be used e.g. by @link(InitializeLog) and
107 @link(TCastleApplication.ParseStandardParameters). }
108 property Version: String read FVersion write FVersion;
109
110 { Initialized to @true on devices with a touch screen (Android, iOS, Nintendo Switch).
111
112 On such devices:
113
114 @unorderedList(
115 @item(We cannot track @link(TCastleContainer.MousePosition)
116 when nothing is pressed (@link(TCastleContainer.MousePressed) is [])
117 on a touch device.)
118
119 @item(The only "mouse button" you will ever see pressed
120 on a touch device is buttonLeft.)
121
122 @item(On the other hand, touch devices support multitouch, exposed by
123 @link(TCastleContainer.Touches) and @link(TCastleContainer.TouchesCount).
124 On touch devices, @link(TCastleContainer.TouchesCount) can range
125 from 0 to a few (modern touch devices support up to 5 simultaneous
126 touches).
127
128 On non-touch devices, @link(TCastleContainer.TouchesCount) is always 1.)
129 )
130
131 See @url(https://castle-engine.io/touch_input documentation
132 about touch input).
133
134 As a debugging feature, you can set this to @true
135 to simulate touch devices on a desktop.
136 The idea is that when an application shows a different input behavior
137 on touch devices, it should always condition it depending on
138 this boolean property. So an application may do this:
139
140 @longCode(#
141 // show the button only on mobile
142 ButtonExit.Exists := ApplicationProperties.TouchDevice;
143 #)
144
145 To test on desktop whether everything behaves OK on mobile,
146 you can just earlier call this:
147
148 @longCode(#
149 if DebugTouchDeviceOnDesktop then
150 ApplicationProperties.TouchDevice := true;
151 #)
152
153 If you use our standard initialization using @link(TCastleWindow.ParseParameters),
154 you can also pass command-line option @code(--pretend-touch-device) to do this.
155 If you execute the game from our editor, you can also use the menu item
156 @italic("Run -> Run Parameters -> Pretend Touch Device") to do this.
157 Underneath, all these methods do is set this property to @true. }
158 property TouchDevice: boolean read FTouchDevice write FTouchDevice;
159
160 { Is it common, on current platform, to show the "Quit" button in your application.
161 E.g. it is normal to show "Quit" on PC (Windows, Linux etc.).
162 But on mobile devices and consoles (like Nintendo Switch) you should not
163 show "Quit", it is expected that user knows how to use OS-specific
164 mechanism to just switch to a different application.
165
166 Just like the @link(TouchDevice), you can change this at runtime
167 for debug purposes (to e.g. easily test mobile UI on PC). }
168 property ShowUserInterfaceToQuit: Boolean read FShowUserInterfaceToQuit write FShowUserInterfaceToQuit;
169
170 { Limit the number of (real) frames per second, to not hog the CPU.
171 Set to zero to not limit.
172
173 The mechanism is implemented by occasionally sleeping
174 (when we see that we render way faster than we need to).
175 So it's a global thing, not just a property of TCastleWindow or TCastleControl.
176
177 In some cases, this also means the "desired number of FPS".
178 This happens when we may be clogged with events
179 (which is especially possible in case of mouse look,
180 when we use CastleControl, or when we use CastleWindow with LCL backend).
181 In such cases we try hard to call "update" and (if necessary) "render"
182 events at least as often as LimitFPS.
183 When LimitFPS is used for this purpose ("desired number of FPS, not just a limit"),
184 it is also capped (by 100.0).
185
186 @unorderedList(
187 @item(Comments specifically about TCastleWindow:
188
189 This limits the number of TCastleApplication.ProcessMessage
190 calls per second, in situations when we do not have to process any user input.
191 So we limit not only rendering (TCastleWindow.OnRender)
192 but also other animation processing (TCastleWindow.OnUpdate) calls per second.
193 See TCastleApplication.ProcessMessage.
194
195 See TCastleWindow.ProcessMessage documentation about WaitToLimitFPS
196 parameter, and see TCastleApplication.LimitFPS documentation.)
197
198 @item(Comments specifically about TCastleControl:
199
200 This mechanism is activated only when some TCastleControl
201 component is used, and only when LCL idle is fired (so we have no pending
202 events, as LCL idle is "lazy" and fires only when process is really idle),
203 and not at Lazarus design time.)
204 )
205 }
206 property LimitFPS: Single read FLimitFPS write FLimitFPS {$ifdef FPC} default DefaultLimitFPS {$endif};
207
208 { Called before OnGLContextOpen, even before Application.OnInitialize,
209 but after we can read files. }
210 property OnGLContextEarlyOpen: TGLContextEventList read FOnGLContextEarlyOpen;
211
212 { Callbacks called when the OpenGL context is opened or closed.
213 Use when you want to be notified about OpenGL context availability,
214 but cannot refer to a particular instance of TCastleControl or TCastleWindow.
215
216 Note that we may have many OpenGL contexts (many
217 TCastleWindow or TCastleControl instances) open simultaneously.
218 They all share OpenGL resources.
219 OnGLContextOpen is called when first OpenGL context is open,
220 that is: no previous context was open.
221 OnGLContextClose is called when last OpenGL context is closed,
222 that is: no more contexts remain open.
223 Note that this implies that they may be called many times:
224 e.g. if you open one window, then close it, then open another
225 window then close it.
226
227 Callbacks on OnGLContextOpen are called from first to last.
228 Callbacks on OnGLContextClose are called in reverse order,
229 so OnGLContextClose[0] is called last.
230
231 @groupBegin }
232 property OnGLContextOpen: TGLContextEventList read FOnGLContextOpen;
233 property OnGLContextOpenObject: TNotifyEventList read FOnGLContextOpenObject;
234 property OnGLContextClose: TGLContextEventList read FOnGLContextClose;
235 property OnGLContextCloseObject: TNotifyEventList read FOnGLContextCloseObject;
236 { @groupEnd }
237
238 { Is the OpenGL context available. IOW, we are between the first OnGLContextOpen
239 and last OnGLContextClose. }
240 property IsGLContextOpen: boolean read FIsGLContextOpen;
241
242 { Callbacks called continuously when (at least one) window is open.
243 You can use this just like @link(TCastleControl.OnUpdate)
244 or @link(TCastleWindow.OnUpdate). }
245 property OnUpdate: TNotifyEventList read FOnUpdate;
246
247 { Callbacks called when Android Java activity started.
248 Called every time a Java activity is created.
249
250 @unorderedList(
251 @item(For the first time, it's called right before
252 @link(TCastleApplication.OnInitialize).)
253
254 @item(Later this is called when Java activity
255 died (and is restarting now), but the native code thread survived.
256 So all native code memory is already cool (no need to call
257 @link(TCastleApplication.OnInitialize)),
258 but we need to reinitialize Java part.
259
260 Note that this is different from @link(TCastleWindow.OnOpen).
261 We lose OpenGL context often, actually every time user switches to another
262 app, without having neither Java nor native threads killed.
263 )
264 )
265
266 For non-Android applications, this is simply always called exactly
267 once, exactly before calling @link(TCastleApplication.OnInitialize). }
268 property OnInitializeJavaActivity: TNotifyEventList read FOnInitializeJavaActivity;
269
270 { Callbacks called when Android Java activity is paused or resumed.
271 @italic(For now) not called on non-Android, but this may change ---
272 consider these events somewhat internal for the time being.
273 @groupBegin }
274 property OnPause: TNotifyEventList read FOnPause;
275 property OnResume: TNotifyEventList read FOnResume;
276 { @groupEnd }
277
278 { Events called upon @link(WritelnWarning). }
279 property OnWarning: TWarningEventList read FOnWarning;
280
281 { Events called upon any @link(WritelnLog), including @link(WritelnWarning). }
282 property OnLog: TLogEventList read FOnLog;
283
284 { Events called at @link(InitializeDebug).
285 If @link(InitializeDebug) was already called, then we call the listener
286 @italic(now), from this AddInitializeDebugListener! }
287 procedure AddInitializeDebugListener(const Listener: TProcedure);
288
289 { Add this to OnWarning to output warnings to standard output (usually, console).
290 Eventually, on GUI Windows programs, it will make a dialog box.
291 This is handled by @link(WarningWrite) procedure. }
292 procedure WriteWarningOnConsole(const Category, Message: String);
293
294 { Internal for Castle Game Engine.
295 Called from CastleWindow or CastleControl.
296 Don't call these methods yourself.
297 @groupBegin
298 @exclude }
299 procedure _GLContextOpen;
300 { @exclude }
301 procedure _GLContextEarlyOpen;
302 { @exclude }
303 procedure _GLContextClose;
304 { @exclude }
305 procedure _Update;
306 { @exclude }
307 procedure _UpdateEnd;
308 { @exclude }
309 procedure _InitializeJavaActivity;
310 { @exclude }
311 procedure _Pause;
312 { @exclude }
313 procedure _Resume;
314 { @exclude }
315 procedure _Warning(const Category, Message: String);
316 { @exclude }
317 procedure _Log(const Message: String);
318 { @exclude
319 Indicates that operating on files (opening, saving, creating dirs) is safe.
320
321 Always @true when not using CastleWindow (e.g. in command-line utilities,
322 Lazarus CastleControl, or custom context situations like
323 https://gist.github.com/michaliskambi/ca0eb18aeb7e326e5dc79c3b5002bcc5 ).
324
325 In case of CastleWindow:
326 On Android, opening files before Android application started (on the Java side)
327 is not possible.
328 On iOS, some things (like ApplicationConfig path) may not be initialized so early. }
329 property _FileAccessSafe: boolean read FFileAccessSafe write FFileAccessSafe;
330 { @groupEnd }
331
332 { Print some common information about application,
333 for example to use in --help command-line output.
334 It shows application name, version, CGE version, compiler version, platform.
335
336 Includes the output of SCompilerDescription and SPlatformDescription. }
337 function Description: String;
338
339 { Initialize debug facilities, that should not be enabled in released
340 applications, but are very useful when enabled out-of-the-box
341 during development.
342 Must be called early (before any files are loaded).
343
344 This includes now:
345
346 @unorderedList(
347 @item(Setting up @link(TCastleContainer.InputInspector) to enable
348 invoking inspector at runtime, by pressing F8 key or
349 pressing 3 fingers for 1 second on the screen.)
350
351 @item(Setting up file monitor, so that it is possible to enable it
352 at runtime, using "Monitor and Auto-Reload Data" from inspector.)
353 )
354
355 This is called automatically from auto-generated CastleAutoGenerated unit
356 in each project, if the DEBUG symbol was defined during compilation.
357
358 For backward compatibility, it is also called when the CGE units
359 like CastleInternalFileMonitor and CastleUiControls
360 are compiled with the DEBUG symbol, but please don't depend on this,
361 it will be removed in future engine versions.
362 You shall not depend on DEBUG / RELEASE symbols used when compiling the engine,
363 they may be independent from the project DEBUG / RELEASE symbols. }
364 procedure InitializeDebug;
365
366 { Enable release features at run-time.
367 This does *nothing* for now, but enables possible future extensions
368 (e.g. special optimizations). }
369 procedure InitializeRelease;
370
371 { Free given component, at the nearest suitable moment.
372 The pending free operations are done at least after processing
373 all "update" events and before processing the "render" event
374 (so the items pending to be freed will not be rendered). }
375 procedure FreeDelayed(const Item: TComponent);
376 end;
377
378 function ApplicationProperties(
379 const CreateIfNotExisting: boolean = true): TCastleApplicationProperties;
380
381 implementation
382
383 uses CastleUtils;
384
385 { TGLContextEventList -------------------------------------------------------- }
386
387 procedure TGLContextEventList.ExecuteForward;
388 var
389 I: Integer;
390 begin
391 for I := 0 to Count - 1 do
392 Items[I]();
393 end;
394
395 procedure TGLContextEventList.ExecuteBackward;
396 var
397 I: Integer;
398 begin
399 for I := Count - 1 downto 0 do
400 Items[I]();
401 end;
402
403 { TWarningEventList ---------------------------------------------------------- }
404
405 procedure TWarningEventList.ExecuteAll(const Category, Message: String);
406 var
407 I: Integer;
408 begin
409 for I := 0 to Count - 1 do
410 Items[I](Category, Message);
411 end;
412
413 { TLogEventList ---------------------------------------------------------- }
414
415 procedure TLogEventList.ExecuteAll(const Message: String);
416 var
417 I: Integer;
418 begin
419 for I := 0 to Count - 1 do
420 Items[I](Message);
421 end;
422
423 { TCastleApplicationProperties ----------------------------------------------- }
424
425 var
426 FApplicationProperties: TCastleApplicationProperties;
427
428 function ApplicationProperties(const CreateIfNotExisting: boolean): TCastleApplicationProperties;
429 begin
430 if (FApplicationProperties = nil) and CreateIfNotExisting then
431 FApplicationProperties := TCastleApplicationProperties.Create;
432 Result := FApplicationProperties;
433 end;
434
435 constructor TCastleApplicationProperties.Create;
436 begin
437 inherited;
438 FOnGLContextOpen := TGLContextEventList.Create;
439 FOnGLContextEarlyOpen := TGLContextEventList.Create;
440 FOnGLContextOpenObject := TNotifyEventList.Create;
441 FOnGLContextClose := TGLContextEventList.Create;
442 FOnGLContextCloseObject := TNotifyEventList.Create;
443 FOnUpdate := TNotifyEventList.Create;
444 FOnInitializeJavaActivity := TNotifyEventList.Create;
445 FOnPause := TNotifyEventList.Create;
446 FOnResume := TNotifyEventList.Create;
447 FOnWarning := TWarningEventList.Create;
448 FOnLog := TLogEventList.Create;
449 FOnInitializeDebug := TProcedureList.Create;
450 FFileAccessSafe := true;
451 FTouchDevice :=
452 {$if defined(ANDROID) or defined(CASTLE_IOS) or defined(CASTLE_NINTENDO_SWITCH)}
453 true
454 {$else}
455 false
456 {$endif};
457 { Note: for now, FShowUserInterfaceToQuit starts just as a negation of FTouchDevice.
458 But it will not always be like that.
459 E.g. on other consoles, FTouchDevice may be false,
460 but FShowUserInterfaceToQuit may be true. }
461 FShowUserInterfaceToQuit :=
462 {$if defined(ANDROID) or defined(CASTLE_IOS) or defined(CASTLE_NINTENDO_SWITCH)}
463 false
464 {$else}
465 true
466 {$endif};
467 FLimitFPS := DefaultLimitFPS;
468 end;
469
470 destructor TCastleApplicationProperties.Destroy;
471 begin
472 FreeAndNil(FPendingToFree);
473 FreeAndNil(FOnGLContextOpen);
474 FreeAndNil(FOnGLContextEarlyOpen);
475 FreeAndNil(FOnGLContextOpenObject);
476 FreeAndNil(FOnGLContextClose);
477 FreeAndNil(FOnGLContextCloseObject);
478 FreeAndNil(FOnUpdate);
479 FreeAndNil(FOnInitializeJavaActivity);
480 FreeAndNil(FOnPause);
481 FreeAndNil(FOnResume);
482 FreeAndNil(FOnWarning);
483 FreeAndNil(FOnLog);
484 FreeAndNil(FOnInitializeDebug);
485 inherited;
486 end;
487
488 function TCastleApplicationProperties.GetApplicationName: String;
489 begin
490 Result := {$ifdef FPC} SysUtils {$else} CastleUtils {$endif} .ApplicationName;
491 end;
492
493 var
494 CastleApplicationNameValue: String;
495
496 function CastleGetApplicationName: String;
497 begin
498 Result := CastleApplicationNameValue;
499 end;
500
501 procedure TCastleApplicationProperties.SetApplicationName(const Value: String);
502 begin
503 OnGetApplicationName := @CastleGetApplicationName;
504 CastleApplicationNameValue := Value;
505 end;
506
507 procedure TCastleApplicationProperties._GLContextEarlyOpen;
508 begin
509 FIsGLContextOpen := true;
510 FOnGLContextEarlyOpen.ExecuteForward;
511 end;
512
513 procedure TCastleApplicationProperties._GLContextOpen;
514 begin
515 FIsGLContextOpen := true;
516 FOnGLContextOpen.ExecuteForward;
517 FOnGLContextOpenObject.ExecuteForward(Self);
518 end;
519
520 procedure TCastleApplicationProperties._GLContextClose;
521 begin
522 FOnGLContextCloseObject.ExecuteBackward(Self);
523 FOnGLContextClose.ExecuteBackward;
524 FIsGLContextOpen := false;
525 end;
526
527 procedure TCastleApplicationProperties._Update;
528 begin
529 DoPendingFree;
530 FOnUpdate.ExecuteAll(Self);
531 end;
532
533 procedure TCastleApplicationProperties._UpdateEnd;
534 begin
535 DoPendingFree;
536 end;
537
538 procedure TCastleApplicationProperties.DoPendingFree;
539 var
540 I: Integer;
541 begin
542 if FPendingToFree <> nil then
543 for I := FPendingToFree.Count - 1 downto 0 do
544 if I < FPendingToFree.Count then
545 FPendingToFree[I].Free; // this will remove it from children, and from FPendingToFree
546 end;
547
548 procedure TCastleApplicationProperties.FreeDelayed(const Item: TComponent);
549 begin
550 if FPendingToFree = nil then
551 FPendingToFree := TComponentList.Create(false);
552 { Do not allow duplicates on FPendingToFree list (which would happen
553 if code calls FreeDelayed(xxx) with the same object).
554 Duplicates make list not behave OK when item is freed, not all copies
555 disappear from TComponentList then (looks like it removes only the 1st),
556 and then FPendingToFree contains dangling pointer.
557 Testcase: space_shooter, fly into rocks. }
558 if FPendingToFree.IndexOf(Item) = -1 then
559 FPendingToFree.Add(Item);
560 end;
561
562 procedure TCastleApplicationProperties._InitializeJavaActivity;
563 begin
564 FOnInitializeJavaActivity.ExecuteAll(Self);
565 end;
566
567 procedure TCastleApplicationProperties._Pause;
568 begin
569 FOnPause.ExecuteAll(Self);
570 end;
571
572 procedure TCastleApplicationProperties._Resume;
573 begin
574 FOnResume.ExecuteAll(Self);
575 end;
576
577 procedure TCastleApplicationProperties._Warning(const Category, Message: String);
578 begin
579 FOnWarning.ExecuteAll(Category, Message);
580 end;
581
582 procedure TCastleApplicationProperties._Log(const Message: String);
583 begin
584 if FOnLog.Count <> 0 then // quickly eliminate most often case
585 FOnLog.ExecuteAll(Message);
586 end;
587
588 procedure TCastleApplicationProperties.WriteWarningOnConsole(const Category, Message: String);
589 var
590 WarningCategory: String;
591 begin
592 if Category <> '' then
593 WarningCategory := 'Warning: ' + Category
594 else
595 WarningCategory := 'Warning';
596 WarningWrite(ApplicationName + ': ' + WarningCategory + ': ' + Message);
597 end;
598
599 function TCastleApplicationProperties.Description: String;
600 begin
601 Result :=
602 ApplicationName + ' version ' + Version + '.' + NL +
603 'Using Castle Game Engine ( https://castle-engine.io/ ) version ' + CastleEngineVersion + '.' + NL +
604 'Compiled with ' + SCompilerDescription + '.' + NL +
605 'Platform: ' + SPlatformDescription + '.';
606 end;
607
608 procedure TCastleApplicationProperties.InitializeDebug;
609 begin
610 if FInitializedDebug or FInitializedRelease then
611 raise Exception.Create('Cannot call InitializeDebug after InitializeRelease or InitializeDebug was already called');
612 FInitializedDebug := true;
613
614 FOnInitializeDebug.ExecuteAll;
615 end;
616
617 procedure TCastleApplicationProperties.InitializeRelease;
618 begin
619 if FInitializedDebug or FInitializedRelease then
620 raise Exception.Create('Cannot call InitializeRelease after InitializeDebug or InitializeRelease was already called');
621 FInitializedRelease := true;
622
623 { Does nothing for now, but exists to provide easy extension point
624 for future release-specific features.
625 Called from CastleAutoGenerated unit in new projects. }
626 end;
627
628 procedure TCastleApplicationProperties.AddInitializeDebugListener(const Listener: TProcedure);
629 begin
630 FOnInitializeDebug.Add(Listener);
631 if FInitializedDebug then
632 Listener();
633 end;
634
635 initialization
636 finalization
637 FreeAndNil(FApplicationProperties);
638 end.