Debian Codegraph @

src/window/castlewindow.pas

raw
1 {
2 Copyright 2001-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 { Window with rendering context suitable for rendering of "Castle Game Engine".
17 Provides a window that can render hierarchy of TCastleUserInterface,
18 which includes a hierarchy of 3D and 2D scenes inside TCastleViewport.
19 Use the @link(TCastleWindow) as your window class.
20
21 @link(Application) object (instance of class @link(TCastleApplication))
22 is a central manager of all open @link(TCastleWindow) windows.
23
24 Using this unit:
25
26 @orderedList(
27 @item(Declare and create @link(TCastleWindow) instance. (Or a descendant
28 like @link(TCastleWindow).))
29
30 @item(Assign Window properties and callbacks like
31 @link(TCastleWindow.OnRender OnRender),
32 @link(TCastleWindow.OnResize OnResize),
33 @link(TCastleWindow.Width Width),
34 @link(TCastleWindow.Height Height),
35 @link(TCastleWindow.Caption Caption).)
36
37 @item(To initialize your game, you usually want to use
38 @link(TCastleApplication.OnInitialize Application.OnInitialize).
39
40 If you only care about
41 standalone programs (for normal OSes like Linux, Windows, MacOSX,
42 but not Android) you may also just initialize your game in the main
43 program block, although using
44 @link(TCastleApplication.OnInitialize Application.OnInitialize)
45 is still often comfortable.)
46
47 @item(Call @link(TCastleWindow.Open Window.Open),
48 this will actually show the window and it's
49 associated OpenGL context.
50
51 The first window open calls
52 @link(TCastleApplication.OnInitialize Application.OnInitialize).
53 It also calls
54 @link(TCastleWindow.OnOpen OnOpen) and
55 @link(TCastleWindow.OnResize OnResize) callbacks.)
56
57 @item(Call @link(TCastleApplication.Run Application.Run).
58 This will enter message loop that will call
59 appropriate windows' callbacks at appropriate times
60 (OnRender, OnPress, OnRelease, OnResize, OnUpdate and many more).
61
62 For more advanced needs you can use something like
63
64 @longCode(#
65 while Application.ProcessMessage do <something>;
66 #)
67
68 instead of Application.Run.
69
70 You can also call @link(TCastleWindow.OpenAndRun Window.OpenAndRun),
71 this is just a shortcut for Window.Open + Application.Run.)
72
73 @item(Application.Run ends when you call @link(TCastleApplication.Terminate Application.Terminate)
74 or when you close last visible window using @link(TCastleWindow.Close Close(true)).
75
76 User is also allowed to close a window using WindowManager facilities
77 (clicking on "X" button in the frame corner, pressing Alt+F4 or something
78 like that). By default, such user action will make window close
79 (but you can freely customize what your program does when user
80 tries to close the window using callback
81 @link(TCastleWindow.OnCloseQuery OnCloseQuery)).)
82 )
83
84 So the simplest example of using this unit can look like this:
85
86 @longcode(#
87 uses CastleWindow;
88
89 var
90 Window: TCastleWindow;
91
92 procedure Render(Sender: TCastleContainer);
93 begin
94 // ... e.g. DrawRectangle or TDrawableImage.Draw calls inside
95 end;
96
97 begin
98 Window := TCastleWindow.Create(Application);
99 Window.OnResize := @Resize;
100 Window.Caption := 'Simplest CastleWindow example';
101 Window.OpenAndRun;
102 end.
103 #)
104
105 @italic(More component-like approach):
106 For larger programs, it makes more sense to divide functionality into
107 controls, which are classes descending from TCastleUserInterface.
108 You can override TCastleUserInterface methods to render, capture input and so on
109 (see e.g. @link(TCastleUserInterface.Render),
110 @link(TCastleUserInterface.Press),
111 @link(TCastleUserInterface.Update).)
112 You can then add your control to the TCastleWindow.Controls list.
113
114 Some features list:
115
116 @unorderedList(
117
118 @item(TCastleApplication.ProcessMessage method.
119 This allows you to reimplement
120 event loop handling, which is crucial for implementing things
121 like @link(MessageInputQuery) function that does modal GUI dialog box.)
122
123 @item(TCastleWindow.Pressed to easily and reliably check which keys
124 are pressed.)
125
126 @item(Application speed, see @link(TCastleWindow.Fps),)
127
128 @item(A menu bar under WinAPI and GTK backends.
129
130 You can attach a menu to a window. Menu structure is constructed using
131 various descendants of TMenuEntry class.
132 Then you have to assign such menu structure
133 to TCastleWindow.MainMenu property. When CastleWindow is implemented on top
134 of GTK_2 or WINAPI or LCL we will show this menu and call
135 TCastleWindow.OnMenuClick when user clicks some menu item.
136 Other backends (XLIB for now) ignore MainMenu.
137
138 See @code(examples/window/window_menu/)
139 for an example how to use the menu.)
140
141 @item(Changing screen resolution and bit depth,
142 see TCastleApplication.VideoChange.)
143
144 @item(You can request OpenGL context properties:
145 @unorderedList(
146 @item color buffer
147 @item with alpha channel (@link(TCastleWindow.AlphaBits AlphaBits)),
148 @item stencil buffer (@link(TCastleWindow.StencilBits StencilBits)),
149 @item double buffer (@link(TCastleWindow.DoubleBuffer DoubleBuffer)),
150 @item(multisampling (full-screen antialiasing) buffers (by
151 @link(TCastleWindow.MultiSampling MultiSampling) or higher-level
152 @link(TCastleWindow.AntiAliasing AntiAliasing)))
153 )
154 )
155
156 @item(You can use native modal dialogs for things such as file selection.
157 GTK backend will use GTK dialogs, WinAPI backend
158 will use Windows dialog boxes, XLib backend will fall back
159 on CastleMessages text input.
160
161 See TCastleWindow.FileDialog (for opening and saving files) and
162 TCastleWindow.ColorDialog (for choosing RGB colors).)
163
164 @item(TCastleWindow.ParseParameters method allows you to easily initialize TCastleWindow
165 properties like initial size and position using command-line
166 parameters like @code(@--geometry WIDTHxHEIGHT), @code(@--display) etc.)
167 )
168 }
169
170 unit CastleWindow;
171
172 {$I castleconf.inc}
173
174 { Choose CastleWindow backend ------------------------------------------ }
175
176 { You can define one of the CASTLE_WINDOW_xxx symbols to use
177 a specific CastleWindow backend.
178 See https://castle-engine.io/castlewindow_backends
179 for the documentation of available backends.
180
181 If you don't define any such symbol,
182 below we automatically choose the best backend for given OS. }
183 {$ifndef CASTLE_WINDOW_WINAPI}
184 {$ifndef CASTLE_WINDOW_XLIB}
185 {$ifndef CASTLE_WINDOW_GTK_2}
186 {$ifndef CASTLE_WINDOW_TEMPLATE}
187 {$ifndef CASTLE_WINDOW_FORM}
188 {$ifndef CASTLE_WINDOW_ANDROID}
189 {$ifndef CASTLE_WINDOW_LIBRARY}
190
191 // PasDoc cannot handle "$if defined(xxx)" for now, workaround below
192 {$ifdef PASDOC}
193 {$define CASTLE_WINDOW_GTK_2}
194 {$else}
195
196 {$if defined(MSWINDOWS)}
197 // various possible backends on Windows:
198 {$define CASTLE_WINDOW_WINAPI} // best (looks native and most functional) on Windows
199 { $define CASTLE_WINDOW_GTK_2}
200 { $define CASTLE_WINDOW_FORM}
201 { $define CASTLE_WINDOW_LIBRARY}
202 { $define CASTLE_WINDOW_TEMPLATE} // only useful for developers
203 {$elseif defined(UNIX)}
204 {$if not defined(FPC)}
205 // Delphi on non-Windows supports now only this backend
206 {$define CASTLE_WINDOW_FORM}
207 {$elseif defined(ANDROID)}
208 {$define CASTLE_WINDOW_ANDROID}
209 {$elseif defined(CASTLE_IOS) or defined(CASTLE_NINTENDO_SWITCH)}
210 {$define CASTLE_WINDOW_LIBRARY}
211 {$elseif defined(DARWIN)}
212 // various possible backends on macOS (desktop):
213 {$define CASTLE_WINDOW_COCOA} // best (looks native) on macOS
214 { $define CASTLE_WINDOW_XLIB} // requires Xlib to compile and to work
215 { $define CASTLE_WINDOW_FORM} // looks native, requires LCL (from Lazarus) or FMX (from Delphi) to compile
216 { $define CASTLE_WINDOW_GTK_2}
217 { $define CASTLE_WINDOW_LIBRARY}
218 { $define CASTLE_WINDOW_TEMPLATE} // only useful for developers
219 {$else}
220 // various possible backends on traditional Unix (Linux, FreeBSD) desktop:
221 {$define CASTLE_WINDOW_GTK_2} // best (looks native and most functional), supports both OpenGL and OpenGLES
222 { $define CASTLE_WINDOW_XLIB} // supports both OpenGL and OpenGLES
223 { $define CASTLE_WINDOW_FORM}
224 { $define CASTLE_WINDOW_LIBRARY}
225 { $define CASTLE_WINDOW_TEMPLATE} // only useful for developers
226 {$endif}
227 {$endif} // end of UNIX possibilities
228
229 {$endif} // end of "not PasDoc"
230
231 {$endif}
232 {$endif}
233 {$endif}
234 {$endif}
235 {$endif}
236 {$endif}
237 {$endif}
238
239 { Configure some debugging options of CastleWindow ------------------------------- }
240
241 { Define CASTLE_WINDOW_CHECK_GL_ERRORS_AFTER_DRAW to check OpenGL errors
242 after TCastleWindow.EventRender (TCastleWindow.OnRender callback) calls.
243 This is done by DoRender, that is: when a backend initiates the drawing.
244 The check is done by CastleGLUtils.CheckGLErrors, checks glGetError
245 and eventually raises an exception. }
246 {$ifdef DEBUG}
247 {$define CASTLE_WINDOW_CHECK_GL_ERRORS_AFTER_DRAW}
248 {$endif}
249
250 { Configure internal things -------------------------------------------------- }
251
252 {$ifdef CASTLE_WINDOW_GTK_2} {$define CASTLE_WINDOW_GTK_ANY} {$endif}
253
254 { Sometimes GTK backend needs to call some X-specific things:
255 1. Implementing TCastleWindow.SetMousePosition.
256 Older GDK/GTK versions didn't have any function for this (see here
257 [http://mail.gnome.org/archives/gtk-list/2001-January/msg00035.html]),
258 although newer GDK has gdk_display_warp_pointer.
259 So we had to bypass GTK and use Xlib's XWarpPointer.
260 2. Screen resizing. We have to use for this XF86VidMode extension,
261 just like for CASTLE_WINDOW_XLIB backend. }
262 {$ifdef CASTLE_WINDOW_GTK_2}
263 {$ifdef UNIX}
264 {$define CASTLE_WINDOW_GTK_WITH_XLIB}
265 {$endif}
266 {$endif}
267
268 { Define EGL to use EGL, cross-platform library to initialize OpenGL or OpenGLES
269 context.
270 It can work with WinAPI, Xlib, GTK backends of CastleWindow.
271
272 By default, we define USE_EGL only when OpenGLES is defined.
273
274 With regular OpenGL (not ES), it's better to use glX (Unix) / wgl (Windows)
275 instead of EGL, that are practically guaranteed to be installed on Linux
276 (if it has OpenGL at all) or Windows.
277
278 - Unix: Though EGL is also practically almost guaranteed,
279 with both OpenGL and OpenGLES support.
280 - Windows, EGL can be found, but note: some implementations will
281 not support OpenGL, will only support OpenGLES.
282 Trying to use OpenGL will result in
283 EGLContextNotPossible exception with message like "EGL: Cannot bind OpenGL API...".
284
285 If you want, define below USE_EGL to always use EGL,
286 with OpenGL or OpenGLES. }
287 {.$define USE_EGL}
288 {$ifdef OpenGLES}
289 {$define USE_EGL}
290 {$endif}
291 // By default CASTLE_WINDOW_GTK_2 uses glX to initialize OpenGL context,
292 // but it's not available on Windows.
293 {$if defined(MSWINDOWS) and defined(CASTLE_WINDOW_GTK_2)}
294 {$define USE_EGL}
295 {$endif}
296
297 { Does backend implement TryVideoChange and VideoReset methods?
298 (if this will not be defined, we will use TryVideoChange that always
299 returns false and VideoReset that is NOOP). }
300 {$undef CASTLE_WINDOW_HAS_VIDEO_CHANGE}
301 {$ifdef CASTLE_WINDOW_WINAPI}
302 {$define CASTLE_WINDOW_HAS_VIDEO_CHANGE}
303 {$endif}
304 {$ifdef CASTLE_WINDOW_XLIB}
305 { Disable using XF86VMODE on macOS, because it seems that newer XQuarts
306 does not provide it. }
307 {$ifndef DARWIN}
308 {$define CASTLE_WINDOW_HAS_VIDEO_CHANGE}
309 {$define CASTLE_WINDOW_USE_XF86VMODE}
310 {$endif}
311 {$endif}
312 {$ifdef CASTLE_WINDOW_GTK_ANY}
313 {$ifdef UNIX}
314 { Hmm. This compiles and basically works, but the new screen is still
315 virtual. For now this is disabled. TODO. }
316 { $define CASTLE_WINDOW_HAS_VIDEO_CHANGE}
317 { $define CASTLE_WINDOW_USE_XF86VMODE}
318 {$endif}
319 {$endif}
320
321 { See castlewindow_private_modifiers_down.inc for description in what
322 situations you want to define CASTLE_WINDOW_USE_PRIVATE_MODIFIERS_DOWN. }
323 {$ifdef CASTLE_WINDOW_GTK_ANY} {$define CASTLE_WINDOW_USE_PRIVATE_MODIFIERS_DOWN} {$endif}
324 {$ifdef CASTLE_WINDOW_XLIB} {$define CASTLE_WINDOW_USE_PRIVATE_MODIFIERS_DOWN} {$endif}
325
326 {$ifdef CASTLE_WINDOW_COCOA}
327 {$modeswitch objectivec1}
328 {$modeswitch cblocks}
329 {$endif}
330
331 interface
332
333 uses {$define read_interface_uses}
334 {$I castlewindow_backend.inc}
335 {$undef read_interface_uses}
336 { FPC units }
337 SysUtils, Classes, Generics.Collections, CustApp, CTypes,
338 { Castle Game Engine units }
339 {$ifdef OpenGLES} CastleGLES, {$else} CastleGL, {$endif}
340 CastleVectors, CastleRectangles, CastleColors, CastleRenderOptions,
341 CastleUtils, CastleClassUtils, CastleGLUtils, CastleImages, CastleGLImages,
342 CastleKeysMouse, CastleStringUtils, CastleFilesUtils, CastleTimeUtils,
343 CastleFileFilters, CastleUIControls, CastleInternalContextBase,
344 CastleInternalPk3DConnexion, CastleParameters, CastleSoundEngine,
345 CastleApplicationProperties;
346
347 {$define read_interface}
348
349 const
350 { }
351 WindowPositionCenter = -1000000;
352 WindowDefaultSize = -1000000;
353
354 const
355 DefaultDepthBits = 24;
356 DepthBitsFallback = 16;
357
358 DefaultFpsCaptionUpdateDelay = 1.0;
359
360 DefaultLimitFPS = TCastleApplicationProperties.DefaultLimitFPS
361 deprecated 'use TCastleApplicationProperties.DefaultLimitFPS';
362
363 type
364 { Development notes:
365 When extending TAntiAliasing, remember to also
366 update ScreenEffectLibrary implementation to be able to handle them
367 (and screen_effect_library.glsl to handle them in GLSL). }
368 { Anti-aliasing values for TCastleWindow.AntiAliasing. }
369 TAntiAliasing = (aaNone,
370 aa2SamplesFaster, //< 2 samples, "don't care" hint.
371 aa2SamplesNicer, //< 2 samples, "nicest" hint (quincunx (5 taps) for NVidia).
372 aa4SamplesFaster, //< 4 samples, "don't care" hint.
373 aa4SamplesNicer, //< 4 samples, "nicest" hint (9 taps for NVidia).
374 aa8SamplesFaster, //< 8 samples, "don't care" hint.
375 aa8SamplesNicer, //< 8 samples, "nicest" hint.
376 aa16SamplesFaster, //< 16 samples, "don't care" hint.
377 aa16SamplesNicer //< 16 samples, "nicest" hint.
378 );
379
380 const
381 DefaultAntiAliasing = aaNone;
382
383 AntiAliasingNames: array [TAntiAliasing] of string =
384 ( 'None',
385 '2 samples (faster)',
386 '2 samples (nicer)',
387 '4 samples (faster)',
388 '4 samples (nicer)',
389 '8 samples (faster) (only latest GPUs)',
390 '8 samples (nicer) (only latest GPUs)',
391 '16 samples (faster) (only latest GPUs)',
392 '16 samples (nicer) (only latest GPUs)'
393 );
394
395 type
396 TCastleWindow = class;
397
398 { Expose TCastleContainer type from CastleWindow unit, since almost all code using
399 CastleWindow will need to use TCastleContainer type for callback parameter type. }
400
401 { }
402 TUIContainer = CastleUIControls.TCastleContainer deprecated 'use TCastleContainer';
403 TCastleContainer = CastleUIControls.TCastleContainer;
404
405 {$I castlewindowmenu.inc}
406
407 { Type of message box, for TCastleWindow.MessageOK and TCastleWindow.MessageYesNo. }
408 TWindowMessageType = (mtInfo, mtWarning, mtQuestion, mtError, mtOther);
409
410 TUpdateFunc = procedure;
411 TMenuClickFunc = procedure (Container: TCastleContainer; Item: TMenuItem);
412 TDropFilesFunc = procedure (Container: TCastleContainer; const FileNames: array of string);
413 TGLContextRetryOpenFunc = function (Window: TCastleWindow): boolean;
414
415 TResizeAllowed = (raNotAllowed, raOnlyAtOpen, raAllowed);
416
417 EGLContextNotPossible = class(Exception);
418
419 TCaptionPart = (cpPublic, cpFps);
420
421 { Container suitable to be used in TCastleWindow.
422 Never create instances of this, just create TCastleWindow,
423 and use container of it (in @link(TCastleWindow.Container)). }
424 TWindowContainer = class(TCastleContainer)
425 private
426 Parent: TCastleWindow;
427 public
428 constructor Create(AParent: TCastleWindow); reintroduce;
429
430 procedure Invalidate; override;
431 function GLInitialized: boolean; override;
432 function PixelsWidth: Integer; override;
433 function PixelsHeight: Integer; override;
434 function PixelsRect: TRectangle; override;
435 function GetMousePosition: TVector2; override;
436 procedure SetMousePosition(const Value: TVector2); override;
437 function Focused: boolean; override;
438 procedure SetInternalCursor(const Value: TMouseCursor); override;
439 function GetTouches(const Index: Integer): TTouch; override;
440 function TouchesCount: Integer; override;
441 function SaveScreen(const SaveRect: TRectangle): TRGBImage; overload; override;
442 function SettingMousePositionCausesMotion: Boolean; override;
443 end deprecated 'do not descend from this, instead use custom TCastleView descendants';
444
445 {$define read_interface_types}
446 {$I castlewindow_backend.inc}
447 {$undef read_interface_types}
448
449 { Window to render everything (3D or 2D) with Castle Game Engine.
450
451 You should use this with TCastleView, following https://castle-engine.io/views
452 and the rest of CGE manual.
453 All user interface creation and event handling should be inside some state.
454
455 By default, the window is filled with simple color from
456 @link(TCastleContainer.BackgroundColor Container.BackgroundColor).
457
458 If you're looking for an analogous Lazarus / Delphi component
459 (that can be placed on a Lazarus / Delphi form)
460 see @link(TCastleControl) component.
461 Note that you cannot use both TCastleControl and TCastleWindow
462 within the same application.
463 See https://castle-engine.io/control_on_form .
464
465 Deprecated functionality:
466 You can also add any user-interface controls to the @link(Controls) property.
467 User-interface controls are any @link(TCastleUserInterface) descendants,
468 like @link(TCastleImageControl) or @link(TCastleButton) or @link(TCastleViewport).
469 Use events like @link(OnPress) to react to events.
470 Use event @link(OnUpdate) to do something continuously. }
471 TCastleWindow = class(TComponent)
472
473 { Include CastleWindow-backend-specific parts of TCastleWindow class.
474 Remember to explicitly specify the scope
475 (usually "private") of things that you add to TCastleWindow class in backends,
476 this is safest. Some backends may expose some protected or even public
477 things that are specific for them. }
478
479 {$define read_window_interface}
480 {$I castlewindow_backend.inc}
481 {$undef read_window_interface}
482
483 protected
484 { Create a container class for this window.
485 Override this to use a custom container class, e.g. to override
486 some container methods. }
487 function CreateContainer: TWindowContainer; virtual; deprecated 'instead of custom TWindowContainer descendants, use custom TCastleView descendants';
488 private
489 FWidth, FHeight, FLeft, FTop: Integer;
490 { Window size reported last to DoResize,
491 and not clamped with some internal constaints like ResizeAllowed
492 of MaxWidth etc. }
493 FRealWidth, FRealHeight: Integer;
494 FOnCloseQuery: TContainerEvent;
495 FOnDropFiles: TDropFilesFunc;
496 { FFullScreenWanted is the value set by FullScreen property by the user.
497 FFullScreenBackend is the last value of FullScreen known to the backend
498 (GTK, WinAPI etc.) }
499 FFullScreenWanted, FFullScreenBackend: boolean;
500 FDoubleBuffer: boolean;
501 FDuringOpen: boolean;
502 FResizeAllowed: TResizeAllowed;
503 FFocused: boolean;
504 FMousePosition: TVector2;
505 FRedBits, FGreenBits, FBlueBits: Cardinal;
506 FAutoRedisplay: boolean;
507 FCaption: array [TCaptionPart] of string;
508 BeforeFullScreenGeometryKnown: boolean;
509 BeforeFullScreenLeft, BeforeFullScreenTop, BeforeFullScreenWidth, BeforeFullScreenHeight: Integer;
510 { Track if some Invalidate was called (and not realized yet by
511 DoRender call). Invalidate only sets this, leaving actually
512 calling of DoRender for later. Call DoRender only of Invalidated = @true.
513
514 Note: Xlib program should always wait for the first Expose event before
515 redrawing anything. Similar for WinAPI. }
516 Invalidated: boolean;
517
518 { FClosed = are we outside of Open..Close }
519 FClosed: boolean;
520
521 { EventOpenCalled = has OnOpen been called from Open? }
522 EventOpenCalled: boolean;
523
524 MenuUpdateInside: Cardinal;
525 MenuUpdateNeedsInitialize: boolean;
526 MenuInitialized: boolean;
527
528 FDepthBits: Cardinal;
529 FStencilBits: Cardinal;
530 FAlphaBits: Cardinal;
531 FMultiSampling: Cardinal;
532 FAntiAliasing: TAntiAliasing;
533 FGtkIconName: String;
534 FVisible: boolean;
535 FMinWidth: Integer;
536 FMinHeight: Integer;
537 FMaxWidth: Integer;
538 FMaxHeight: Integer;
539 // Using deprecated TWindowContainer - should be internal in the future
540 {$warnings off}
541 FContainer: TWindowContainer;
542 {$warnings on}
543 FCursor: TMouseCursor;
544 FTouches: TTouchList;
545 FNamedParameters: TCastleStringList;
546 { When Open, this says if the window actually has double-buffer. }
547 HasDoubleBuffer: Boolean;
548 { Ready TGLContextRequirements instance.
549 Call UpdateRequirements to initialize its fields correctly. }
550 FRequirements: TGLContextRequirements;
551 function GetColorBits: Cardinal;
552 procedure SetColorBits(const Value: Cardinal);
553 procedure SetAntiAliasing(const Value: TAntiAliasing);
554 procedure SetAutoRedisplay(const Value: boolean);
555 function GetPublicCaption: String;
556 procedure SetPublicCaption(const Value: String);
557 procedure SetCaption(const Part: TCaptionPart; const Value: String);
558 function GetWholeCaption: String;
559 procedure SetCursor(const Value: TMouseCursor);
560 function GetOnOpen: TContainerEvent;
561 procedure SetOnOpen(const Value: TContainerEvent);
562 function GetOnOpenObject: TContainerObjectEvent;
563 procedure SetOnOpenObject(const Value: TContainerObjectEvent);
564 function GetOnBeforeRender: TContainerEvent;
565 procedure SetOnBeforeRender(const Value: TContainerEvent);
566 function GetOnRender: TContainerEvent;
567 procedure SetOnRender(const Value: TContainerEvent);
568 function GetOnResize: TContainerEvent;
569 procedure SetOnResize(const Value: TContainerEvent);
570 function GetOnClose: TContainerEvent;
571 procedure SetOnClose(const Value: TContainerEvent);
572 function GetOnCloseObject: TContainerObjectEvent;
573 procedure SetOnCloseObject(const Value: TContainerObjectEvent);
574 function GetOnUpdate: TContainerEvent;
575 procedure SetOnUpdate(const Value: TContainerEvent);
576 function GetOnPress: TInputPressReleaseEvent;
577 procedure SetOnPress(const Value: TInputPressReleaseEvent);
578 function GetOnRelease: TInputPressReleaseEvent;
579 procedure SetOnRelease(const Value: TInputPressReleaseEvent);
580 function GetOnMotion: TInputMotionEvent;
581 procedure SetOnMotion(const Value: TInputMotionEvent);
582 function GetTouches(const Index: Integer): TTouch;
583 procedure SetWidth(const Value: Integer);
584 procedure SetHeight(const Value: Integer);
585 procedure SetLeft(const Value: Integer);
586 procedure SetTop(const Value: Integer);
587 procedure SetResizeAllowed(const Value: TResizeAllowed);
588
589 { Convert window position from the usual window system convention,
590 where (0,0) is left-top, and the window has size FRealWidth/FRealHeight,
591 to CGE convention where (0,0) is left-bottom. }
592 function LeftTopToCastle(const V: TVector2): TVector2; overload;
593 function LeftTopToCastle(const X, Y: Single): TVector2; overload;
594
595 { Convert window position from the CGE convention to window system
596 convention where (0,0) is left-top, also rounding it.
597 This reverses LeftTopToCastle, and rounds. }
598 function CastleToLeftTopInt(const V: TVector2): TVector2Integer;
599
600 { Update FFullScreenBackend to FFullScreenWanted by closing and reopening
601 the window (if needed, i.e. if FFullScreenBackend <> FFullScreenWanted). }
602 procedure SimpleUpdateFullScreenBackend;
603
604 { Set FFullScreenBackend to FFullScreenWanted.
605 Every backend must implement this. In the simplest case,
606 just call SimpleUpdateFullScreenBackend. }
607 procedure UpdateFullScreenBackend;
608
609 procedure SetMousePosition(const Value: TVector2);
610 procedure SetFullScreenWanted(const Value: Boolean);
611
612 { Used in particular backend, open OpenGL context and do
613 Application.OpenWindowsAdd(Self) there.
614
615 Properties that should be used in OpenBackend implementation to determine
616 the window:
617
618 - Width, Height, Left, Top
619 - Cursor,
620 - FullScreen
621 (Note that FFullScreenWanted and FFullScreenBackend are always
622 equal at this point, so you can read any of these fields.
623 You can also just read FullScreen property.)
624 - ResizeAllowed
625 (DoResize already implements appropriate
626 checks, but implementation should provide user with visual clues that
627 the window may / may not be resized)
628 - MainMenu (display MainMenu and provide way to call DoMenuClick)
629
630 OpenGL context must be initialized honouring these properties:
631
632 - DoubleBuffer,
633 - StencilBits,
634 - DepthBits,
635 - AlphaBits,
636 - MultiSampling }
637 procedure OpenBackend;
638
639 { Close OpenGL context, for particular backend.
640
641 No need to call OpenWindowsRemove here, it's done by universal Close already.
642 It's advised (although not totally required) that all errors during
643 CloseBackend should be caught and cause only WritelnWarning.
644 Reasoning: Close should, regardless of trouble, try to finalize as much
645 as possible. }
646 procedure CloseBackend;
647
648 { Make the OpenGL context of this window current (active for following
649 OpenGL commands). }
650 procedure BackendMakeCurrent;
651
652 { Swap OpenGL buffers.
653 Call this method only when DoubleBuffered and if you already did
654 MakeCurrent. (Implicit glFlush is guaranteed.) }
655 procedure SwapBuffers;
656
657 { BackendMenuInitialize should cause backend to build whole menu resources
658 for MainMenu, BackendMenuFinalize to free them.
659
660 BackendMenuFinalize is called before changing MainMenu structure
661 in arbitrary way, BackendMenuInitialize is called after.
662 Backend should just free / initialize resources related to menu.
663 BackendMenuInitialize may assume that BackendMenuFinalize was already called
664 (so no need to try to free in BackendMenuInitialize again).
665
666 They are never called directly: always call MenuInitialize / Finalize.
667 These make sure to care about eventual MenuUpdateBegin / MenuUpdateEnd
668 around, and make sure BackendMenuFinalize is called only when menu is
669 already initialized (by BackendMenuInitialize), and
670 BackendMenuInitialize is called only when menu is not initialized yet.
671
672 Implementation of these can assume that MainMenu <> nil now,
673 and that MainMenuVisible = @true.
674 Also it may assume that Closed = false.
675
676 Note: if backend wants, it may itself call these from
677 OpenBackend / CloseBackend. Of course, when you call them
678 yourself, you have to make sure on your own that all assumptions
679 are satisfied. In practice, BackendMenuFinalize should clear all the variables
680 to the state right after constructor (zero, nil etc.),
681 and BackendMenuInitialize expect them as such, and then everything will work Ok.
682
683 @groupBegin }
684 procedure BackendMenuInitialize;
685 procedure BackendMenuFinalize;
686 { @groupEnd }
687
688 { These call corresponding BackendMenuInitialize or BackendMenuFinalize,
689 unless we're inside MenuUpdateBegin / MenuUpdateEnd,
690 and take care to only initialize when finalized,
691 and finalize only when initialized.
692 They also take care of checking Closed and MainMenuVisible properties.
693 @groupBegin }
694 procedure MenuInitialize;
695 procedure MenuFinalize;
696 { @groupEnd }
697
698 { For optimization purposes, you may surround many menu changes
699 inside MenuUpdateBegin + MenuUpdateEnd calls.
700 Make sure window is not closed / opened between them.
701 @groupBegin }
702 procedure MenuUpdateBegin;
703 procedure MenuUpdateEnd;
704 { @groupEnd }
705
706 { Notification called immediately after menu entry properties changed.
707 This is called only when MainMenu <> nil and Entry is contained
708 inside our MainMenu. Also, this is called only when not Closed.
709
710 In case of MenuUpdateXxx calls: You can be sure that
711 only appropriate local Entry properties changed, no other menu entry
712 (even child menu entry for submenus) was changed.
713
714 Sloppy backend may simply do here MenuFinalize + MenuInitialize,
715 but a better backend may do something more efficient,
716 like updating only this specific Entry resources.
717
718 In case of MenuInsert: remember that this is called
719 after Entry was added to Parent. So if your MenuInsert simply
720 calls MenuFinalize + MenuInitialize, make sure your MenuFinalize
721 handles the case that some TMenuEntry may have uninitialized (zero)
722 TMenuEntry.Handle.
723
724 In case of MenuDelete: remember that this is called
725 after Entry was removed from Parent. So if your MenuDelete simply
726 calls MenuFinalize + MenuInitialize, make sure your MenuFinalize
727 finalizes (releases backend-specific resources) also for Entry
728 that isn't in the MainMenu hierarchy anymore.
729
730 Both MenuInsert and MenuDelete problems disappear if your
731 MenuFinalize doesn't look at MainMenu.Entries hierarchy, and releases
732 in one go whole backend-specific hierarchy under MainMenu.Handle.
733 Or if you implement MenuInsert and MenuDelete in a more optimal way,
734 without MenuFinalize + MenuInitialize.
735
736 @groupBegin }
737 procedure MenuUpdateCaption(Entry: TMenuEntryWithCaption);
738 procedure MenuUpdateEnabled(Entry: TMenuEntryWithCaption);
739 procedure MenuUpdateChecked(Entry: TMenuItemChecked);
740 procedure MenuInsert(const Parent: TMenu; const ParentPosition: Integer; const Entry: TMenuEntry);
741 procedure MenuDelete(const Parent: TMenu; const ParentPosition: Integer; const Entry: TMenuEntry);
742 function MenuUpdateCheckedFast: boolean;
743 { @groupEnd }
744
745 { Called from DoUpdate. Backends may fill this with code to be done
746 on each update, regardless of how update is performed,
747 e.g. this will be called also if something calls FOpenWindows.DoUpdate in
748 TCastleApplication. }
749 procedure BackendInsideUpdate;
750
751 procedure CreateBackend;
752
753 { Simulate that all the keys and mouse buttons were released.
754 For all keys that are down (Pressed[k]) calls DoKeyUp(k).
755 For all mouse buttons that are down (mb in MousePressed) calls DoMouseUp(mb).
756 If CASTLE_WINDOW_USE_PRIVATE_MODIFIERS_DOWN is defined,
757 this calls at the beginning SetPrivateModifiersDown(..., ..., false)
758 to say that all keys are up.
759
760 Useful when user somehow switches to another window / control
761 (e.g. when he opens our MainMenu), such that we are then unable to catch
762 following KeyUps and MouseUps. So user simply STOPS controlling our
763 program with mouse and keyboard, so we have to assume that he releases
764 all keys and mouse buttons.
765
766 Nie widze chwilowo zastosowania dla MousePressed[*] := false,
767 ale jest to konsekwentne. Z punktu widzenia programu w momencie wejscia
768 usera do menu user przestaje kontrolowac program (tzn. okienko OpenGLa)
769 przy pomocy myszy i klawiatury. }
770 procedure ReleaseAllKeysAndMouse;
771
772 { Should DoKeyDown be able to call DoMenuClick, that is should
773 we handle menu key shortcuts ourselves.
774
775 The implementation (usually just hardcoded true or false result)
776 is backend-specific.
777
778 - If @true, and in DoKeyDown we get some key event that specifies menu item,
779 then DoKeyDown calls DoMenuClick (and not calls EventKeyDown).
780
781 - If @false, then DoKeyDown doesn't check whether key corresponds to menu item.
782 It just calls EventKeyDown. }
783 function RedirectKeyDownToMenuClick: boolean;
784
785 { DoXxx methods ------------------------------------------------------------
786
787 DoXxx method should be called by CastleWindow backend when an event
788 Xxx happens. DoXxx methods take care of various backend-independent
789 stuff, and take care of calling EventXxx (that calls OnXxx in turn).
790 CastleWindow backend should never call EventXxx directly.
791 (And nothing should call OnXxx directly except EventXxx.)
792
793 Remember that no DoXxx may be called from CloseBackend.
794
795 Below is the detailed specification, but summing some things up
796 you don't have to worry about these things when you use DoXxx methods
797 (these things are fully handled by DoXxx methods):
798 - updating state of MousePressed
799 - updating state of Pressed (Pressed.Keys, Pressed.Characters etc.)
800 - updating state of MousePosition
801 - calling MakeCurrent before every EventXxx
802 - flushing gl commands (and swapping gl buffers when DoubleBuffer'ing)
803 - taking care of AutoRedisplay
804 - updating Width, Height (and updating it with accordance to
805 Min/MaxWidth/Height and ResizeAllowed)
806 - checking MainMenu.Enabled
807 }
808
809 { DoResize with FirstResizeAfterOpen = true is called only once
810 (and exactly once) from TCastleWindow.Open implementation.
811 So all CastleWindow-backend code should always
812 pass FirstResizeAfterOpen = false (EVEN if it may be called from
813 OpenBackend (that is called before DoResize in Open) !).
814
815 Some more notes about calling DoResize from OpenBackend:
816 in this case DoResize will NOT call EventResize (since the first callback
817 that should be called for a window is EventOpen). We will always after
818 EventOpen call DoResize(..., true), so this should not be a problem
819 anywhere. You can simply call DoResize from OpenBackend to tell us what
820 real Width/Height we have, and the real EventResize will be called
821 just at a later time.
822
823 You can pass here ANY AWidth, AHeight. It will be automatically clipped
824 here to fit in Min/MaxWidth/Height and to satisfy ResizeAllowed.
825
826 Also MakeCurrent + EventResize will be called (probably; sometimes
827 DoResize may decide to not call EventResize - e.g. when ResizeAllowed
828 =raNotAllowed and FirstTime = false then it's useless to call here
829 EventResize).
830
831 Remember: this function does not automatically call Invalidate.
832 You must make sure that soon after changing size of the window
833 you will call DoRender (e.g. you can call Invalidate after
834 calling DoResize; but usually (under WinAPI, Xlib, GTK)
835 it's not needed, i.e. WinAPI, Xlib, and GTK all take care of this
836 automatically). }
837 procedure DoResize(AWidth, AHeight: integer; FirstResizeAfterOpen: boolean);
838
839 { Called by a backend when user wants to close the window
840 (e.g. by pressing the special "close" button on the window manager border).
841 It is possible to ignore it (see OnCloseQuery docs).
842 This calls OnCloseQuery and then eventually Close
843 (and Close will execute OnClose, CloseBackend etc.).
844
845 Note that there is no "DoClose" method defined.
846 You should always call DoCloseQuery. }
847 procedure DoCloseQuery;
848
849 { Do MakeCurrent,
850 EventBeforeRender,
851 EventRender (inside Fps.InternalRenderBegin/End)
852 flush gl command pipeline (and swap gl buffers if DoubleBuffer)
853
854 - Take care of AutoRedisplay, like
855
856 @code(if AutoRedisplay then Invalidate;)
857
858 So specific CastleWindow backends need not to worry about
859 AutoRedisplay. They only have to call this when Invalidated = @true. }
860 procedure DoRender;
861
862 { DoKeyDown/Up: pass here key that is pressed down or released up.
863
864 Only DoKeyDown: pass also KeyString. Pass Key = keyNone if this is not
865 representable as TKey, pass KeyString = '' if this is not representable
866 as char. But never pass both Key = keyNone and KeyString = ''
867 (this would mean that nothing is pressed, at least nothing that can be represented
868 in CGE).
869
870 Only DoKeyUp: never pass Key = keyNone.
871
872 If you call DoKeyUp while (not Pressed[Key]) it will be ignored
873 (will not do any EventRelease etc. - just NOOP).
874
875 This will
876 update Pressed (Pressed.Keys, Pressed.Characters, etc.) accordingly,
877 DoKeyDown: may here call DoMenuClick
878 (and then it will NOT call MakeCurrent and EventKeyDown)
879 MakeCurrent,
880 EventKeyDown/Up.
881 }
882 procedure DoKeyDown(const Key: TKey; const KeyString: String);
883 procedure DoKeyUp(const key: TKey);
884 { Do MakeCurrent,
885 EventMotion,
886 update MousePosition }
887 procedure DoMotion(const Event: TInputMotion);
888 { DoMouseDown/Up:
889 update MousePosition (so that before EventPress/EventRelease position
890 of the mouse is set to the current, precise, position)
891 update MousePressed
892 MakeCurrent
893 EventPress/EventRelease }
894 procedure DoMouseDown(const Position: TVector2;
895 Button: TCastleMouseButton; const FingerIndex: TFingerIndex = 0);
896 procedure DoMouseUp(const Position: TVector2;
897 Button: TCastleMouseButton; const FingerIndex: TFingerIndex = 0;
898 const TrackReleased: boolean = true);
899 procedure DoMouseWheel(const Scroll: Single; const Vertical: boolean);
900 { Just call it when user presses some MenuItem.
901 This takes care of MainMenu.Enabled,
902 MakeCurrent,
903 Item.DoClick,
904 optional OnMenuClick or Container.EventKeyDown }
905 procedure DoMenuClick(Item: TMenuItem);
906
907 procedure DoDropFiles(const FileNames: array of string);
908 function MessageReceived(const Received: TCastleStringList;
909 const ReceivedStream: TMemoryStream): boolean;
910
911 { Just like FileDialog, but these always get and should set FileName,
912 not an URL. Also, for OpenDialog, we make sure that initial FileName
913 contains only a path (not the final file name), since this is
914 good behavior for users (even if some API allow to set proposed
915 file name). }
916 function BackendFileDialog(const Title: String; var FileName: String;
917 OpenDialog: boolean; FileFilters: TFileFilterList = nil): boolean; overload;
918
919 procedure OpenCore;
920 { Current OpenGL buffers configuration required.
921 Stuff like DoubleBuffer, AlphaBits, DepthBits,
922 StencilBits etc.
923 This simply returns a text description of these properties.
924
925 It does not describe the current OpenGL context parameters.
926 (It doesn't even need an OpenGL context open.)
927
928 Useful for constructing messages e.g. for EGLContextNotPossible exceptions. }
929 function RequestedBufferAttributes: String;
930
931 { Check do given OpenGL buffers configuration satisfies the
932 requested configuration.
933
934 So it checks does
935
936 @preformatted(
937 ProvidedStencilBits >= StencilBits and
938 ProvidedDepthBits >= DepthBits ...
939 )
940
941 and so on. If not, EGLContextNotPossible is raised with detailed
942 description (which buffer constraint is not satisfied -- e.g. maybe
943 the stencil buffer is not available).
944
945 Note that ProvidedMultiSampling is not checked if MultiSampling is <= 1.
946 In other words, if multisampling was not required, ProvidedMultiSampling
947 doesn't matter --- it's Ok even ProvidedMultiSampling = 0 and
948 MultiSampling = 1, which happens commonly (since our MultiSampling = 1 means
949 "no multisampling" and is default, but most backends returns num_samples
950 (or something equivalent) as = 0 when multisampling not supported). }
951 procedure CheckRequestedBufferAttributes(const ProviderName: String;
952 ProvidedStencilBits, ProvidedDepthBits, ProvidedAlphaBits,
953 ProvidedMultiSampling: Cardinal);
954
955 { Update FRequirements to reflect current window properties. }
956 procedure UpdateRequirements;
957 protected
958 procedure DoUpdate; virtual;
959 public
960 property Container: TWindowContainer read FContainer;
961
962 { Is it allowed to suspend (for an indefinite amount of time) waiting
963 for user input.
964
965 Allowing this is a good thing, as it means our process doesn't eat
966 your CPU when it simply waits, doing nothing, for user input.
967 On the other hand, you cannot allow this if you want to do some
968 things continuously, regardless of user input.
969
970 The default implementation plays it safe, and does not allow suspending
971 if we have OnUpdate callback defined. }
972 function AllowSuspendForInput: boolean; virtual;
973
974 { Size of the window OpenGL area. Together with frame and border
975 sizes, and eventually menu bar size, this determines the final
976 window size.
977
978 When the window is open, these are read-only (may only change
979 through internal methods, that is: we'll update @link(Width), @link(Height),
980 @link(Left), @link(Top) to reflect current size and position).
981
982 MinWidth / MaxWidth / MinHeight / MaxHeight place constraints
983 on these values (rigorously honored when window is open):
984 always @code(MinWidth <= Width <= MaxWidth) and
985 @code(MinHeight <= Height <= MaxHeight).
986
987 ResizeAllowed places constrains when window manager and user may change
988 window size. In particular, when ResizeAllowed <> raAllowed then
989 window sizes cannot change when window is open.
990
991 Note that for some window managers, we cannot always reliably
992 force the size constraints and block resizing on the desktop.
993 If you set rigorous size constraints, or ResizeAllowed <> raAllowed,
994 you may find that window manager still resizes the window.
995 In such cases, we may fake our size a little ---
996 @link(Width) and @link(Height) values may not correspond to actual
997 size as seen on the desktop. This is comfortable, as in such cases
998 you usually want to just ignore window managers limits and just
999 proceed as if your size requirements are satisfied.
1000
1001 Special WindowDefaultSize value of these properties
1002 means: at @link(Open), calculate and use some comfortable window size.
1003
1004 TODO: Make it possible to set these properties while the window is open.
1005
1006 @groupBegin }
1007 property Width: integer read FWidth write SetWidth default WindowDefaultSize;
1008 property Height: integer read FHeight write SetHeight default WindowDefaultSize;
1009 { @groupEnd }
1010
1011 { Rectangle representing the inside of this container.
1012 Always (Left,Bottom) are zero, and (Width,Height) correspond to window
1013 sizes. }
1014 function Rect: TRectangle;
1015
1016 { Window position on the screen. If one (or both) of them is equal
1017 to WindowPositionCenter at the initialization (Open) time,
1018 then it will be set to position the window at the screen center.
1019
1020 TODO: Make it possible to set these properties while the window is open.
1021
1022 @groupBegin }
1023 property Left: integer read FLeft write SetLeft default WindowPositionCenter;
1024 property Top :integer read FTop write SetTop default WindowPositionCenter;
1025 { @groupEnd }
1026
1027 { Is the window fullscreen.
1028
1029 A fullscreen window has @link(Width), @link(Height), @link(Left), @link(Top)
1030 set to fill the whole screen.
1031 The window style is also, if possible, borderless.
1032
1033 The window size constraints (like MinWidth, MaxWidth, MinHeight, MaxHeight
1034 and ResizeAllowed) are ignored, that is: we do not check whether
1035 screen size fits inside MinWidth and MaxWidth. If this is @true,
1036 the window is always fullscreen.
1037 However, the sizes visible to your application
1038 (exposed in properties @link(Width), @link(Height))
1039 are still constrained by MinWidth, MaxWidth, MinHeight, MaxHeight
1040 and ResizeAllowed.
1041
1042 It is best to adjust this property before the window is open,
1043 this way window will be immediately open in the full-screen size.
1044 In the standard case (see https://castle-engine.io/manual_cross_platform.php
1045 about a typical initialization) you should place
1046 @code(Window.FullScreen := true) inside the unit initialization section.
1047
1048 You can also change this property after the window is open.
1049 But note that:
1050
1051 @unorderedList(
1052 @item(Some backends require closing + reopening the window to make it
1053 fullscreen. So be prepared that changing FullScreen
1054 may result in OnClose + OnOpen events, and all OpenGL resources
1055 are reloaded. In most cases, engine takes care of everything
1056 automatically (all TCastleScene, TCastleUserInterface, TDrawableImage and other
1057 resources are automatically reloaded), just be aware that
1058 this operation may take a bit of time.
1059 )
1060
1061 @item(For safety (because of the above limitation), changing
1062 this property does not have an immediate effect on the window.
1063 The actual fullscreen change will happen a bit later, from the message loop.
1064 )
1065 )
1066 }
1067 property FullScreen: boolean
1068 read FFullScreenWanted write SetFullScreenWanted default false;
1069
1070 { Deprecated, instead just do @code(FullScreen := not FullScreen). }
1071 procedure SwapFullScreen; deprecated 'use "FullScreen := not FullScreen"';
1072
1073 { Should we request and use the double buffer.
1074 After every draw, we automatically swap buffers (if DoubleBuffer)
1075 or call glFlush (if not DoubleBuffer). }
1076 property DoubleBuffer: boolean read FDoubleBuffer write FDoubleBuffer default true;
1077
1078 { Required red / green / blue color buffer precision for this window.
1079 When 0, the default window system color precision will be used.
1080
1081 You can either set them by separate red / green / blue properties.
1082 Or you can use ColorBits that reads / writes all three channels bits.
1083 Reading ColorBits simply returns the sum of
1084 @code(RedBits + GreenBits + BlueBits).
1085 Writing ColorBits simply set RedBits and BlueBits to
1086 @code(ColorBits div 3), and sets GreenBits to the remainder.
1087 This way green channel has always the best resolution (as is usual,
1088 since it's perceived most), and the sum is always as requested.
1089 This way setting ColorBits to values like 16 or 24 works as expected.
1090
1091 Note that it's also possible to change color resolution by
1092 changing the whole screen settings.
1093 See TCastleApplication.VideoColorBits and TCastleApplication.VideoChange for this.
1094 These properties only request the color
1095 resolution for this window, which is less intrusive (you don't change
1096 the whole screen) but also may have a smaller chance of success.
1097
1098 @groupBegin }
1099 property RedBits: Cardinal read FRedBits write FRedBits default 0;
1100 property GreenBits: Cardinal read FGreenBits write FGreenBits default 0;
1101 property BlueBits: Cardinal read FBlueBits write FBlueBits default 0;
1102 property ColorBits: Cardinal read GetColorBits write SetColorBits stored false default 0;
1103 { @groupEnd }
1104
1105 { Current mouse position.
1106 In case of touch devices, this reports the last known position
1107 for FingerIndex = 0, and setting this has no effect.
1108
1109 See @link(TTouch.Position) for a documentaion how this is expressed.
1110
1111 In all situations the MousePosition is the latest known mouse position.
1112 The only exception is within EventMotion (and so, also in OnMotion
1113 callback): MousePosition is then the previous known mouse position,
1114 while new mouse position is provided as NewMousePosition argument to
1115 EventMotion (and OnMotion).
1116
1117 @italic(About setting the mouse position:)
1118
1119 @unorderedList(
1120 @item(There is no guarantee that the position was set
1121 exactly to what was requested. Various backends have their
1122 limitations, and position may be rounded, and almost everywhere
1123 position will be clamped to the current screen space.)
1124
1125 @item(It is undefined whether setting mouse position
1126 will generate an OnMotion event (just as if the
1127 user moved the mouse). Some backends do it, some don't,
1128 and there is no way to make it consistent (because
1129 backend may report the motion event with delay, so we really
1130 don't know whether user moved the mouse or was it caused
1131 by code).)
1132
1133 @item(Setting mouse position is always ignored when
1134 the window is closed.)
1135 ) }
1136 property MousePosition: TVector2
1137 read FMousePosition write SetMousePosition;
1138
1139 { Currently active touches on the screen.
1140 This tracks currently pressed fingers, in case of touch devices (mobile, like Android and iOS).
1141 In case of desktops, it tracks the current mouse position, regardless if any mouse button is
1142 currently pressed.
1143
1144 Indexed from 0 to TouchesCount - 1.
1145 @seealso TouchesCount
1146 @seealso TTouch }
1147 property Touches[const Index: Integer]: TTouch read GetTouches;
1148
1149 { Count of currently active touches (mouse or fingers pressed) on the screen.
1150 @seealso Touches }
1151 function TouchesCount: Integer;
1152
1153 { When (if at all) window size may be changed.
1154
1155 @unorderedList(
1156 @item(raNotAllowed
1157
1158 @link(Width) and @link(Height) can only change
1159 to honor MinWidth / MaxWidth / MinHeight / MaxHeight constraints.
1160 Absolutely nothing else may cause them to change,
1161 user cannot resize the window.
1162
1163 Note that setting the @link(FullScreen) property to @true
1164 works regardless of this. Just don't change @link(FullScreen) property
1165 if you don't want to. However, @link(Width) / @link(Height)
1166 values will be kept unchanged (they will not be updated to Application.ScreenWidth
1167 and Application.ScreenHeight), so from the point of view of you code
1168 the raNotAllowed works always.
1169
1170 You can be sure that EventResize (OnResize) will be called only
1171 once, when window is opened (right after initial EventOpen (OnOpen)).)
1172
1173 @item(raOnlyAtOpen
1174
1175 @link(Width) and @link(Height) may be adjusted when the window
1176 is opened, by @link(Open) call. For example window manager
1177 may decide that the size is too large for the current screen.
1178 Or when you request FullScreen window and window size has to be
1179 adjusted to match current screen size. Also they will always be
1180 adjusted to fit in MinWidth / MaxWidth / MinHeight / MaxHeight constraints.
1181
1182 After opening, window size cannot change anymore.
1183 In particular user cannot resize the window (by dragging border
1184 or such). After the first EventOpen (OnOpen) call,
1185 the window size becomes constant. From the first EventResize
1186 (OnResize) the window size is constant, as long as the window
1187 remains open.
1188
1189 You can be sure that EventResize (OnResize) will be called only
1190 once, when window is opened (right after initial EventOpen (OnOpen)).)
1191
1192 @item(raAllowed
1193
1194 @link(Width) and @link(Height) may be adjusted at open time,
1195 and later user can resize the window too.
1196 This is the default value, giving user and window manager
1197 the most flexibility.
1198
1199 You have to be prepared for this, handling OnResize and adjusting
1200 stuff like OpenGL viewport and projection matrix.)
1201 ) }
1202 property ResizeAllowed: TResizeAllowed
1203 read FResizeAllowed write FResizeAllowed default raAllowed;
1204
1205 { OpenGL context is created, initialize things that require OpenGL
1206 context. Often you do not need to use this callback (engine components will
1207 automatically create/release OpenGL resource when necessary).
1208 You usually will also want to implement Window.OnClose callback that
1209 should release stuff you create here.
1210
1211 Often, instead of using this callback, it's cleaner to derive new classes
1212 from TCastleUserInterface class or it's descendants,
1213 and override their GLContextOpen / GLContextClose methods to react to
1214 context being open/closed. Using such TCastleUserInterface classes
1215 is usually easier, as you add/remove them from controls whenever
1216 you want (e.g. you add them in
1217 @link(TCastleApplication.OnInitialize Application.OnInitialize)),
1218 and underneath they create/release/create again the OpenGL resources
1219 when necessary.
1220
1221 OnOpen is always called @bold(after)
1222 @link(TCastleApplication.OnInitialize Application.OnInitialize).
1223 In normal circumstances, for a typical standalone game, the OnOpen will
1224 happen only once. But for other targets, it may be necessary to close/reopen
1225 the OpenGL context many times, e.g. on mobile platforms it's normal
1226 that application may "loose" the OpenGL context and it may need
1227 to recreate OpenGL resources when it wakes up.
1228 Event called when OpenGL context is initialized.
1229
1230 It's guaranteed that every newly opened window will get
1231 EventOpen (OnOpen) first, and then EventResize (OnResize),
1232 and only then --- the other callbacks, as the user uses the window.
1233 This is consistent EventOpen (OnOpen)
1234 is always the first executed callback and OnClose
1235 is always the last. This allows you to cleanly initialize / finalize
1236 OpenGL resources.
1237
1238 During EventOpen (OnOpen) you already have valid
1239 Width / Height values, that is those values were already adjusted
1240 if ResizeAllowed <> raNotAllowed.
1241
1242 @bold(Be careful what you do in this callback if you want your game
1243 to work on Android or other non-standalone platforms.)
1244 On Android, OpenGL context may be closed and opened at any time,
1245 as user can switch from/to your application at any time.
1246 You should use
1247 @link(TCastleApplication.OnInitialize Application.OnInitialize)
1248 for a one-time initialization (it is executed right before
1249 the very first OnOpen would be executed).
1250 Use this callback only to create OpenGL resources
1251 (destroyed in OnClose).
1252
1253 @deprecated Instead of this, use TCastleUserInterface and TCastleView virtual
1254 method @link(TCastleUserInterface.GLContextOpen).
1255 Or use Application.OnInitialize for initialization.
1256 Or use ApplicationProperties.OnGLContextOpen to know when GL context is
1257 created.
1258
1259 @groupBegin }
1260 property OnOpen: TContainerEvent read GetOnOpen write SetOnOpen;
1261 {$ifdef FPC}deprecated 'instead of this, use TCastleUserInterface and TCastleView virtual method GLContextOpen; or use Application.OnInitialize for initialization; or use ApplicationProperties.OnGLContextOpen';{$endif}
1262 property OnOpenObject: TContainerObjectEvent read GetOnOpenObject write SetOnOpenObject;
1263 {$ifdef FPC}deprecated 'instead of this, use TCastleUserInterface and TCastleView virtual methods GLContextOpen; or use Application.OnInitialize for initialization; or use ApplicationProperties.OnGLContextOpenObject';{$endif}
1264 { @groupEnd }
1265
1266 { Minimum and maximum window sizes. Always
1267
1268 @preformatted(
1269 0 < MinWidth <= MaxWidth and
1270 0 < MinHeight <= MaxHeight
1271 )
1272
1273 We do not allow user to resize the window outside of these constraints.
1274
1275 We also fix window @link(Width) and @link(Height) to fit within
1276 these constraints when you @link(Open) the window. We do it regardless
1277 of ResizeAllowed (even when it's raNotAllowed).
1278
1279 In other words, these constraints have a higher priority than
1280 ResizeAllowed and your desired @link(Width) and @link(Height)
1281 and even @link(FullScreen) (setting @link(FullScreen) property
1282 will stil change the visible sizes, but your perceived sizes
1283 will be constrained by this min/max).
1284 So you can be sure that (as long as window
1285 is open) @link(Width) / @link(Height) will always fit in these constraints.
1286 @groupBegin }
1287 property MinWidth: Integer read FMinWidth write FMinWidth default 100;
1288 property MinHeight: Integer read FMinHeight write FMinHeight default 100;
1289 property MaxWidth: Integer read FMaxWidth write FMaxWidth default 4000;
1290 property MaxHeight: Integer read FMaxHeight write FMaxHeight default 4000;
1291 { @groupEnd }
1292
1293 { Required depth buffer precision. Zero means that we don't need
1294 depth buffer at all. We may get depth buffer with more precision
1295 than requested (we may even get depth buffer when we set
1296 DepthBits = 0), this all depends on graphic card.
1297
1298 Default value is @link(DefaultDepthBits),
1299 which is non-zero and a reasonable default for 3D programs
1300 that want to work with depth test enabled.
1301
1302 Note that we have a fallback mechanism in case @link(DepthBits)
1303 is too large: we fallback on @link(DepthBitsFallback) then.
1304
1305 @italic(Design notes:) Why default value is not 0?
1306
1307 @orderedList(
1308 @item(
1309 Most programs using OpenGL use 3D and so use depth testing.
1310 So many programs
1311 would have to call something like @code(Window.DepthBits := DefaultDepthBits).
1312 )
1313
1314 @item(
1315 Often graphic cards / window systems / OSes give you an OpenGL
1316 context with depth buffer @italic(even if you don't need depth buffer).
1317 This makes it easy to forget about setting DepthBits to something
1318 non-zero, because on @italic(your) system you may happen
1319 to always get some depth buffer.
1320 )
1321 )
1322
1323 If you are writing a program that does not need depth buffer
1324 you can set Window.DepthBits := 0, to inform OpenGL it doesn't need
1325 to allocate any depth buffer.
1326 }
1327 property DepthBits: Cardinal
1328 read FDepthBits write FDepthBits default DefaultDepthBits;
1329
1330 { Required stencil buffer precision, zero means that stencil buffer is
1331 not needed.
1332
1333 Just like with other XxxBits property, we may get more
1334 bits than we requested. But we will never get less --- if window system
1335 will not be able to provide GL context with requested number of bits,
1336 @link(Open) will raise an error.
1337
1338 Note that after initializing OpenGL context (when opening the window),
1339 StencilBits is @italic(not) updated to the current (provided)
1340 stencil buffer bit size. For example, if you requested StencilBits := 8,
1341 and you got 16-bits stencil buffer: StencilBits value will still remain 8.
1342 This is sensible in case you close the window, tweak some settings
1343 and try to open it again. Use @code(glGetInteger(GL_STENCIL_BITS))
1344 when window is open to query current (actual) buffer size. }
1345 property StencilBits: Cardinal
1346 read FStencilBits write FStencilBits default DefaultStencilBits;
1347
1348 { How many samples are required for multi-sampling (anti-aliasing).
1349
1350 Set @link(AntiAliasing) instead of this for more comfortable
1351 (higher-level) way to turn on multi-sampling (anti-aliasing).
1352 Setting @link(AntiAliasing) will also set this property.
1353
1354 1 means that no multi-sampling is required.
1355 Values larger than 1 mean that we require OpenGL context with
1356 multi-sampling capabilities. Various GPUs may support various
1357 values (it's a trade-off between quality and speed),
1358 try typical values 2 or 4.
1359
1360 You can enable/disable anti-aliasing in your program by code like
1361
1362 @longCode(#
1363 if GLFeatures.Multisample then glEnable(GL_MULTISAMPLE);
1364 if GLFeatures.Multisample then glDisable(GL_MULTISAMPLE);
1365 #)
1366
1367 But usually that's not needed, as it is "on" by default
1368 (GL_ARB_multisample spec says so) if you requested multi-sampling context
1369 (that is, if this property is > 1). See GL_ARB_multisample spec for details:
1370 [http://opengl.org/registry/specs/ARB/multisample.txt].
1371
1372 Just like with other XxxBits property, we may get more
1373 samples than we requested (e.g. if you request 3, you will most probably
1374 get 4). But we will never get less --- if window system
1375 will not be able to provide GL context with requested number of bits,
1376 @link(Open) will raise an error.
1377 TODO: actually, this may change to be similar to Lazarus
1378 TOpenGLControl.MultiSampling, and also be more comfortable --- to retry
1379 initialization with no multi-sampling. In this case this property will
1380 not be changed, to be nice.
1381
1382 You can always read OpenGL GL_SAMPLE_BUFFERS_ARB and GL_SAMPLES_ARB
1383 values after initializing OpenGL context, to know exactly
1384 how many samples did you actually get, and did you get multi-sampling at all.
1385 Actually, we already initialize global CastleGLUtils.GLCurrentMultiSampling
1386 for you, you can use this. }
1387 property MultiSampling: Cardinal
1388 read FMultiSampling write FMultiSampling default 1;
1389
1390 { Comfortably turn on/off anti-aliasing.
1391
1392 Setting this property automatically sets also the @link(MultiSampling)
1393 property. Although it's easy to request multi-sampling by using the
1394 @link(MultiSampling) property directly, using AntiAliasing is a little
1395 more comfortable. You don't have to wonder what are the sensible
1396 values of @link(MultiSampling) for common GPUs, and we also
1397 automatically use NV_multisample_filter_hint for nicer anti-aliasing
1398 when possible. }
1399 property AntiAliasing: TAntiAliasing
1400 read FAntiAliasing write SetAntiAliasing default DefaultAntiAliasing;
1401
1402 { Required number of bits in alpha channel of color buffer.
1403 Zero means that alpha channel is not needed.
1404
1405 Just like with other XxxBits property, we may get more
1406 bits than we requested. But we will never get less --- if window system
1407 will not be able to provide GL context with requested number of bits,
1408 @link(Open) will raise an error. }
1409 property AlphaBits: Cardinal
1410 read FAlphaBits write FAlphaBits default 0;
1411
1412 { Name of the icon for this window used by GTK 2 backend.
1413
1414 This is simply passed to @code(gtk_window_set_icon_name),
1415 see [http://library.gnome.org/devel/gtk/stable/GtkWindow.html#gtk-window-set-icon-name].
1416 This allows you to use an installed icon (in /usr/share/icons/
1417 or ~/.local/share/icons/) for your program. See
1418 [http://library.gnome.org/devel/integration-guide/stable/icons.html.en]
1419 for short information how and where to install your icons.
1420
1421 It's ignored on non-GTK 2 backends. }
1422 property GtkIconName: String read FGtkIconName write FGtkIconName;
1423
1424 (*Should this window be actually displayed on the desktop.
1425 In all normal programs you want to leave this as @true, as the
1426 main purpose of the window is to actually be visible and interactive
1427 on the desktop.
1428
1429 Setting this to @false allows you to get an OpenGL context without
1430 showing anything on the desktop. This can be used for rendering
1431 and capturing OpenGL stuff without showing it on the desktop.
1432 One example is the @--screenshot option of castle-model-viewer, see
1433 [https://castle-engine.io/castle-model-viewer].
1434
1435 If you implement such thing, remember that you should not render
1436 and capture the normal front or back buffer contents.
1437 OpenGL makes no guarantee that a hidden window will have any allocated
1438 memory, so capturing hidden window contents isn't useful (you may
1439 get something valid, or you may get random / blank screen, depending
1440 on OS and GPU). However, you can create Framebuffer Object
1441 on modern GPUs, and capture it's contents. An example code snippet:
1442
1443 @longCode(#
1444 { add CastleGLImages, CastleImages to your uses clause }
1445
1446 var
1447 ScreenshotRender: TGLRenderToTexture;
1448 Image: TRGBImage;
1449 begin
1450 ScreenshotRender := TGLRenderToTexture.Create(Width, Height);
1451 try
1452 ScreenshotRender.Buffer := tbNone;
1453 ScreenshotRender.GLContextOpen;
1454 ScreenshotRender.RenderBegin;
1455
1456 { render your stuff here }
1457
1458 { capture the screen }
1459 Image := SaveScreen_NoFlush(Rectangle(0, 0, Width, Height),
1460 ScreenshotRender.ColorBuffer);
1461 try
1462 SaveImage(Image, 'aaa.png');
1463 finally FreeAndNil(Image) end;
1464
1465 ScreenshotRender.RenderEnd;
1466 finally FreeAndNil(ScreenshotRender) end;
1467 end;
1468 #)
1469 *)
1470 property Visible: boolean read FVisible write FVisible default true;
1471
1472 { Caption of the window.
1473 By default it's initialized from ApplicationProperties.Caption or (if empty)
1474 ApplicationName.
1475 May be changed even when the window is already open. }
1476 property Caption: String read GetPublicCaption write SetPublicCaption;
1477
1478 { Render window contents here.
1479
1480 Called when window contents must be redrawn,
1481 e.g. after creating a window, after resizing a window, after uncovering
1482 the window etc. You can also request yourself a redraw of the window
1483 by the Invalidate method, which will cause this event to be called
1484 at nearest good time.
1485
1486 Note that calling Invalidate while in EventRender (OnRender) is not ignored.
1487 It instructs to call EventRender (OnRender) again, as soon as possible.
1488
1489 When you have some controls on the @link(Controls) list,
1490 the OnRender event is done @bold(last).
1491 So here you can draw on top of the existing controls.
1492 To draw something underneath the existing controls, create a new TCastleUserInterface
1493 and override it's @link(TCastleUserInterface.Render) and insert it to the controls
1494 using @code(Controls.InsertBack(MyBackgroundControl);).
1495
1496 @deprecated Instead of this, use TCastleUserInterface and TCastleView virtual method Render and OnRender event. }
1497 property OnRender: TContainerEvent read GetOnRender write SetOnRender;
1498 {$ifdef FPC}deprecated 'instead of this, use TCastleUserInterface and TCastleView virtual method Render or OnRender event';{$endif}
1499
1500 {$ifdef FPC}
1501 { @deprecated Deprecated name for OnRender. }
1502 property OnDraw: TContainerEvent read GetOnRender write SetOnRender; deprecated;
1503 {$endif}
1504
1505 { Always called right before EventRender (OnRender).
1506 These two events, EventBeforeRender (OnBeforeRender) and EventRender (OnRender),
1507 will be always called sequentially as a pair.
1508
1509 The only difference between these two events is that
1510 time spent in EventBeforeRender (OnBeforeRender)
1511 is NOT counted as "frame time"
1512 by Fps.OnlyRenderFps. This is useful when you have something that needs
1513 to be done from time to time right before OnRender and that is very
1514 time-consuming. It such cases it is not desirable to put such time-consuming
1515 task inside OnRender because this would cause a sudden big change in
1516 Fps.OnlyRenderFps value. So you can avoid this by putting
1517 this in OnBeforeRender.
1518
1519 @deprecated Instead of this, use TCastleUserInterface and TCastleView virtual
1520 method BeforeRender. Or just use virtual Render or OnRender event. }
1521 property OnBeforeRender: TContainerEvent read GetOnBeforeRender write SetOnBeforeRender;
1522 {$ifdef FPC}deprecated 'instead of this, use TCastleUserInterface and TCastleView virtual method BeforeRender; or use virtual Render or OnRender event';{$endif}
1523
1524 { Called when the window size (@link(Width), @link(Height)) changes.
1525 It's also guaranteed to be called during @link(Open),
1526 right after the EventOpen (OnOpen) event.
1527
1528 @deprecated Instead of this, use TCastleUserInterface and TCastleView virtual
1529 method Resize.
1530
1531 @seealso ResizeAllowed }
1532 property OnResize: TContainerEvent read GetOnResize write SetOnResize;
1533 {$ifdef FPC}deprecated 'instead of this, use TCastleUserInterface and TCastleView virtual method Resize';{$endif}
1534
1535 { Called when the window is closed, right before the OpenGL context
1536 is destroyed. This is your last chance to release OpenGL resources,
1537 like textures, shaders, display lists etc. This is a counterpart
1538 to OnOpen event.
1539
1540 @deprecated Instead of this, use TCastleUserInterface and TCastleView virtual
1541 method @link(TCastleUserInterface.GLContextClose).
1542 Or use ApplicationProperties.OnGLContextClose. }
1543 property OnClose: TContainerEvent read GetOnClose write SetOnClose;
1544 {$ifdef FPC}deprecated 'instead of this, use TCastleUserInterface and TCastleView virtual method GLContextClose; or use ApplicationProperties.OnGLContextClose';{$endif}
1545 property OnCloseObject: TContainerObjectEvent read GetOnCloseObject write SetOnCloseObject;
1546 {$ifdef FPC}deprecated 'instead of this, use TCastleUserInterface and TCastleView virtual method GLContextClose; or use ApplicationProperties.OnGLContextCloseObject';{$endif}
1547
1548 { Called when user presses a key or mouse button or moves mouse wheel.
1549
1550 @deprecated Instead of this, use TCastleUserInterface and TCastleView virtual
1551 method Press and OnPress event. }
1552 property OnPress: TInputPressReleaseEvent read GetOnPress write SetOnPress;
1553 {$ifdef FPC}deprecated 'instead of this, use TCastleUserInterface and TCastleView virtual method Press or OnPress event';{$endif}
1554
1555 { Called when user releases a pressed key or mouse button.
1556
1557 It's called right after @code(Pressed[Key]) changed from true to false.
1558
1559 The TInputPressRelease structure, passed as a parameter to this event,
1560 contains the exact information what was released.
1561
1562 Note that reporting characters for "key release" messages is not
1563 perfect, as various key combinations (sometimes more than one?) may lead
1564 to generating given character. We have some intelligent algorithm
1565 for this, used to make Characters table and to detect
1566 this C for OnRelease callback. The idea is that a character is released
1567 when the key that initially caused the press of this character is
1568 also released.
1569
1570 This solves in a determined way problems like
1571 "what happens if I press Shift, then X,
1572 then release Shift, then release X". (will "X" be correctly
1573 released as pressed and then released? yes.
1574 will small "x" be reported as released at the end? no, as it was never
1575 pressed.)
1576
1577 @deprecated Instead of this, use TCastleUserInterface and TCastleView virtual
1578 method Release and OnRelease event. }
1579 property OnRelease: TInputPressReleaseEvent read GetOnRelease write SetOnRelease;
1580 {$ifdef FPC}deprecated 'instead of this, use TCastleUserInterface and TCastleView virtual method Release or OnRelease event';{$endif}
1581
1582 { Called when user tries to close the window.
1583 This is called when you use window manager features to close the window,
1584 like clicking on the "close" icon on the window frame or using Alt+F4
1585 on most desktops. This is @italic(not) called when you explicitly
1586 close the window by calling the @link(Close) method.
1587
1588 When this callback is not assigned, we will
1589 just let the window be closed. When it's assigned,
1590 the window will not closed --- you should call here @link(Close)
1591 explicitly if you want to (for example, after asking user for
1592 confirmation "do you really want to quit?").
1593
1594 When handling this event, you must remember that user
1595 may try to close our window at any time.
1596 E.g. if you're implementing here somehing like showing user
1597 text "You cannot quit now" or asking user "Do you really want to quit"
1598 remember that while you display such message to user and you're
1599 processing events (e.g. looking for keypress "Yes" or "No"),
1600 user may try to close your window again.
1601
1602 CastleMessages unit offers some nice routines that you can safely
1603 use here, e.g. you can use it inside OnCloseQuery like
1604
1605 if MessageYesNo(Window, 'Are you sure you want to quit?') then
1606 Close;
1607
1608 Inside MessageYesNo, when we're processing events,
1609 and waiting for user's answer (yes or no),
1610 futher OnCloseQuery events will be ignored, so everything will work OK.
1611
1612 This event is also useful if you want to call Close(false)
1613 on closing the window (i.e. QuitWhenLastWindowClosed = false).
1614 By default, if this event is undefined, we call Close(true)
1615 when user tries to close the window. }
1616 property OnCloseQuery: TContainerEvent read FOnCloseQuery write FOnCloseQuery;
1617
1618 { Mouse or a finger on touch device moved.
1619
1620 For a mouse, remember you always have the currently
1621 pressed mouse buttons in MousePressed. When this is called,
1622 the MousePosition property records the @italic(previous)
1623 mouse position, while callback parameter NewMousePosition gives
1624 the @italic(new) mouse position.
1625
1626 @deprecated Instead of this, use TCastleUserInterface and TCastleView virtual
1627 method Motion and OnMotion event. }
1628 property OnMotion: TInputMotionEvent read GetOnMotion write SetOnMotion;
1629 {$ifdef FPC}deprecated 'instead of this, use TCastleUserInterface and TCastleView virtual method Motion or OnMotion event';{$endif}
1630
1631 { Send fake motion event, without actually moving the mouse through the backend.
1632 This is useful only for automatic tests.
1633 @exclude }
1634 procedure InternalFakeMotion(const Event: TInputMotion);
1635
1636 { Continuously occuring event, called for all open windows.
1637 This event is called at least as regularly as redraw,
1638 so it is continuously called even when your game
1639 is overwhelmed by messages (like mouse moves) and redraws.
1640
1641 This is called at the same time (right after or right before) when
1642 all callbacks on the list
1643 @link(TCastleApplicationProperties.OnUpdate ApplicationProperties.OnUpdate)
1644 are called.
1645
1646 @deprecated Instead of this, use TCastleUserInterface and TCastleView virtual
1647 method Update and OnUpdate event. }
1648 property OnUpdate: TContainerEvent read GetOnUpdate write SetOnUpdate;
1649 {$ifdef FPC}deprecated 'instead of this, use TCastleUserInterface and TCastleView virtual method Update or OnUpdate event';{$endif}
1650
1651 { Called when user drag and drops file(s) on the window.
1652 In case of macOS bundle, this is also called when user opens a document
1653 associated with our application by double-clicking.
1654
1655 Note: this is currently supported only by Form and Cocoa backends
1656 of TCastleWindow, see https://castle-engine.io/castlewindow_backends . }
1657 property OnDropFiles: TDropFilesFunc read FOnDropFiles write FOnDropFiles;
1658
1659 { Should we automatically redraw the window all the time,
1660 without the need for an @link(Invalidate) call.
1661 If @true (the default), EventRender (OnRender) will called constantly.
1662
1663 If your game may have a still screen (nothing animates),
1664 then this approach is a little unoptimal, as we use CPU and GPU
1665 for drawing, when it's not needed. In such case, you can set this
1666 property to @false, and make sure that you call
1667 @link(Invalidate) always when you need to redraw the screen.
1668 Note that the engine components always call @link(Invalidate) when
1669 necessary, so usually you should only call it yourself if you provide
1670 a custom @link(OnRender) implementation. }
1671 property AutoRedisplay: boolean read FAutoRedisplay write SetAutoRedisplay
1672 default true;
1673
1674 { -------------------------------------------------------------------------
1675 Menu things (menu may be modified at runtime, everything will be
1676 automatically properly redisplayed etc.) }
1677
1678 private
1679 FMainMenu: TMenu;
1680 FMainMenuVisible: boolean;
1681 FOwnsMainMenu: boolean;
1682 FOnMenuClick: TMenuClickFunc;
1683 FUserData: Pointer;
1684 procedure SetMainMenu(Value: TMenu);
1685 public
1686 { Menu bar of this window.
1687 When not assigned, we have no menu bar.
1688
1689 Note that MainMenu.Caption will be ignored.
1690
1691 You can change this freely while Closed.
1692
1693 You can change this almost freely while not Closed: you can use
1694 various properties of TMenuEntry descendants (adding, deleting items
1695 from TMenu, changing Caption, Key, KeyString, Checked properties --
1696 anything) and you can change value of MainMenu BUT you must not
1697 change MainMenu <> nil state when the window is not Closed.
1698 I.e. if you called Open with MainMenu = nil, then MainMenu must stay
1699 nil unit Close. If you called Open with MainMenu <> nil, then you
1700 can assign other MainMenu values while not Closed, but only values
1701 <>nil. I.e. you can't set MainMenu to nil if you called Open
1702 with MainMenu <> nil.
1703 See @code(examples/window/window_menu/)
1704 for demo of changing value of MainMenu while window is not Closed.
1705
1706 Note that MainMenu.Enabled is honoured (as well as Enabled
1707 for all menu items inside, of course).
1708 You can use this to disallow user from clicking on the whole
1709 menu. When MainMenu.Enabled = @false then
1710 no MenuItem.DoClick, no OnMenuClick
1711 will be called when user presses some menu item.
1712 When user presses some keyboard shortcut for some menu item,
1713 no MenuItem.DoClick and no OnMenuClick will be called,
1714 but instead normal EventPress (OnPress) will be called.
1715
1716 Disabling MainMenu is useful e.g. during modal dialog box, like @link(MessageOk).
1717 This way you can force use to interact with the modal box. }
1718 property MainMenu: TMenu read FMainMenu write SetMainMenu;
1719
1720 { Is MainMenu visible. @false means that we do not show main menu bar,
1721 but menu key shortcuts should still work.
1722 Right now, you can reliably change this only before window is open. }
1723 property MainMenuVisible: boolean
1724 read FMainMenuVisible write FMainMenuVisible default true;
1725
1726 { If true then the @link(MainMenu) will automatically freed when this
1727 TCastleWindow instance is freed. }
1728 property OwnsMainMenu: boolean read FOwnsMainMenu write FOwnsMainMenu default true;
1729
1730 { Called each time user chooses some menu item and it's not handled
1731 in TMenuItem.DoClick. By default, menu item handling is passed
1732 to TMenuItem.DoClick. Only when it return @false (not handled) then
1733 we call this window's event. }
1734 property OnMenuClick: TMenuClickFunc read FOnMenuClick write FOnMenuClick;
1735
1736 {$ifdef FPC}
1737 { Deprecated name for OnMenuClick. }
1738 property OnMenuCommand: TMenuClickFunc read FOnMenuClick write FOnMenuClick; deprecated;
1739 {$endif}
1740
1741 { @section(Mouse state) -------------------------------------------------- }
1742
1743 { Mouse buttons currently pressed.
1744 See @link(TCastleContainer.MousePressed) for details. }
1745 function MousePressed: TCastleMouseButtons;
1746
1747 { Is the window focused now, which means that keys/mouse events
1748 are directed to this window. }
1749 property Focused: boolean read FFocused;
1750
1751 { Place for your pointer, for any purposes.
1752 No code in this unit touches the value of this field.
1753 This is similar to TComponent.Tag property. }
1754 property UserData: Pointer read FUserData write FUserData;
1755
1756 property Closed: boolean read FClosed default true;
1757
1758 { Mouse cursor appearance over this window.
1759 See TMouseCursor for a list of possible values and their meanings.
1760
1761 Note that this is for internal usage in the engine. In your applications,
1762 you should set TCastleUserInterface.Cursor on any UI control (including on TCastleView),
1763 never set this property directly. }
1764 property InternalCursor: TMouseCursor read FCursor write SetCursor default mcDefault;
1765
1766 { List of user-interface controls currently active.
1767 See @link(TCastleContainer.Controls) for details. }
1768 function Controls: TInternalChildrenControls;
1769
1770 { Is the OpenGL context initialized. This is equivalent to @code(not Closed),
1771 which means we are between an @link(Open) and @link(Close) calls. }
1772 function GLInitialized: boolean;
1773
1774 { Create the window with associated rendering context and show it.
1775
1776 @unorderedList(
1777 @item(Create window with a rendering area, optionally with a menu bar.)
1778 @item(Create rendering context.)
1779 @item(Show the window.)
1780 @item(Call @link(GLInformationInitialize) to initialize @link(GLVersion), @link(GLFeatures),
1781 show them in log (https://castle-engine.io/manual_log.php).)
1782
1783 @item(Initial events called:
1784 @unorderedList(
1785 @itemSpacing Compact
1786 @item Call MakeCurrent, EventOpen (OnOpen)
1787 @item Call MakeCurrent, EventResize (OnResize)
1788 @item(Call MakeCurrent once again, to be sure that after Open
1789 active rendering context is the one associated with newly created
1790 window (in case you would change active rendering context inside
1791 EventResize (OnResize), which is allowed).)
1792 )
1793 )
1794 )
1795
1796 Call to this method is ignored if the window is already open
1797 (if @link(Closed) = @false).
1798
1799 @raises(EGLContextNotPossible
1800 If it's not possible to obtain
1801 OpenGL context with specified attributes.
1802 For example, maybe you set AlphaBits, DepthBits, StencilBits
1803 properties too high?
1804
1805 It's guaranteed that when EGLContextNotPossible
1806 is raised, the window remains in correct (closed) state.
1807 This means that you can catch EGLContextNotPossible
1808 and lower some OpenGL buffer requirements and try to open once again.
1809 Although it's usually more comfortable to use the overloaded
1810 version of @link(Open) with Retry callback for this purpose.
1811
1812 This parameterless version of Open automatically
1813 turns off multi-sampling (AntiAliasing and MultiSampling
1814 properties), and then we turn off
1815 stencil buffer (StencilBits), if OpenGL context cannot be initialized.
1816 But if it still cannot be initialized, we raise EGLContextNotPossible.
1817 You can use overloaded Open version with Retry callback to customize
1818 this fallback mechanism, to code which OpenGL context features
1819 may be turned off.)
1820 }
1821 procedure Open; overload;
1822
1823 { Open the window with OpenGL context, allowing you to lower
1824 the OpenGL context requirements and retry.
1825
1826 If the OpenGL context cannot be initialized,
1827 then @code(Retry) callback is called. Inside this callback you should
1828 either:
1829
1830 @unorderedList(
1831 @item(lower some context requirements (like set MultiSampling to 1
1832 if it was > 1) if possible, and return @true to retry, or)
1833 @item(do not change context requirements and return @false to give up.)
1834 )
1835
1836 Note that the parameterless version of @link(Open) method
1837 actually calls this version, with a default retry callback
1838 that turns off AntiAliasing and MultiSampling, and then StencilBits
1839 (since all our engine code should be ready that multi-sampling
1840 or stencil buffers may not be available).
1841 Using your own Retry callback, with this version,
1842 allows you to decide which context parameters may be lowered
1843 to allow creating a window.
1844
1845 @raises(EGLContextNotPossible If it's not possible to obtain
1846 requested OpenGL context, and the @code(Retry) callback
1847 returned @false.) }
1848 procedure Open(const Retry: TGLContextRetryOpenFunc); overload;
1849
1850 { Close window.
1851
1852 @unorderedList(
1853 @item(Calls OnClose.)
1854 @item(Hides window, destroys it.)
1855 @item(
1856 if this was the only open TCastleWindow window
1857 and QuitWhenLastWindowClosed = true then
1858 this calls Application.Terminate.)
1859 )
1860
1861 Note that often there's no need to call Close explicitly in your program,
1862 because in destructor of this object we call Close, to be sure
1863 that window is closed.
1864
1865 TODO: zrobic param boolean CloseFromDestroyQuitWhenLastWindowClosed?
1866 As for now Close from destructor is called always with
1867 QuitWhenLastWindowClosed = true.
1868
1869 Call to Close is ignored if window is already Closed. }
1870 procedure Close(const QuitWhenLastWindowClosed: boolean = true);
1871
1872 { @deprecated Deprecated name for @link(Invalidate). }
1873 procedure PostRedisplay; deprecated;
1874
1875 { See TCastleContainer.Invalidate. }
1876 procedure Invalidate;
1877
1878 { Make the OpenGL context of this window @italic(current). Following OpenGL
1879 commands will apply to this context, and the @link(CastleRenderContext.RenderContext RenderContext)
1880 will also refer to this.
1881 When the window is opened, and right
1882 before calling any window callback, we always automatically call
1883 this, so you should not need to call this method yourself
1884 in normal circumstances. }
1885 procedure MakeCurrent;
1886
1887 { Capture the current window contents to an image (file).
1888
1889 These functions take care of making a redraw before capturing screen
1890 contents. That's because you can only reliably capture the screen contents
1891 of the back buffer (before swap) using OpenGL. In theory, the single-buffer
1892 case could be optimized (do not redraw if not needed, that is:
1893 if not invalidated), but it's not worth the complication since noone uses
1894 single-buffer for normal applications... And also, there is no reliable
1895 way to capture screen contents in case of single-buffer.
1896
1897 Note that only capturing the double-buffered windows (the default)
1898 is reliable.
1899 @groupBegin }
1900 procedure SaveScreen(const Url: String); overload;
1901 function SaveScreen: TRGBImage; overload;
1902 function SaveScreen(const SaveRect: TRectangle): TRGBImage; overload;
1903 function SaveScreenToGL(const SmoothScaling: boolean = false): TDrawableImage; overload;
1904 function SaveScreenToGL(const SaveRect: TRectangle;
1905 const SmoothScaling: boolean = false): TDrawableImage; overload;
1906 { @groupEnd }
1907
1908 { Color buffer where we draw, and from which it makes sense to grab pixels.
1909 Use only if you save the screen using low-level SaveScreen_NoFlush function.
1910 Usually, you should save the screen using the simpler @link(SaveScreen) method,
1911 and then the @name is not useful. }
1912 function SaveScreenBuffer: TColorBuffer;
1913
1914 { Asks and saves current screenshot.
1915 Asks user where to save the file (using @link(FileDialog),
1916 as default URL taking ProposedUrl).
1917 If user accepts calls Window.SaveScreen.
1918 In case of problems with saving, shows a dialog (doesn't raise exception). }
1919 procedure SaveScreenDialog(ProposedUrl: String);
1920
1921 constructor Create(AOwner: TComponent); override;
1922 destructor Destroy; override;
1923
1924 public
1925 { Keys currently pressed. }
1926 function Pressed: TKeysPressed;
1927
1928 { Measures application speed. }
1929 function Fps: TFramesPerSecond;
1930
1931 { OpenAndRun stuff --------------------------------------------------------- }
1932
1933 { Do @link(Open) (initialize rendering context, show the window)
1934 followed by @link(TCastleApplication.Run Application.Run) (run the event loop). }
1935 procedure OpenAndRun;
1936
1937 { Parsing parameters ------------------------------------------------------- }
1938
1939 { Parse some command-line options and remove them from @link(Parameters)
1940 list. See https://castle-engine.io/opengl_options.php for
1941 documentaion what these options actually do from user's point of view.
1942
1943 @definitionList(
1944 @itemLabel @--fullscreen
1945 @item(Sets FullScreen to @true.)
1946
1947 @itemLabel @--window
1948 @item(Sets FullScreen to @false.)
1949
1950 @itemLabel @--geometry WIDTHxHEIGHT<sign>XOFF<sign>YOFF
1951 @item(Sets FullScreen to @false and sets window position and size:
1952 @link(Width), @link(Height), @link(Left), @link(Top).)
1953
1954 @itemLabel @--fullscreen-custom WIDTHxHEIGHT
1955 @item(Change desktop resolution by VideoChange and sets FullScreen to @true.
1956 Changing desktop resolution is not implemented on all platforms.)
1957
1958 @itemLabel @--pretend-touch-device
1959 @item(Set @link(TCastleApplicationProperties.TouchDevice
1960 ApplicationProperties.TouchDevice) to true.
1961 See @url(https://castle-engine.io/touch_input touch input documentation).)
1962 )
1963
1964 @raises(EInvalidParams When some of our options have invalid arguments.) }
1965 procedure ParseParameters;
1966
1967 { Help text for options handled by ParseParameters.
1968
1969 Returned string may be multiline, but it does not contain
1970 the trailing newline (newline char after the last line). }
1971 class function ParseParametersHelp: String;
1972
1973 { Select a file to open or save, using native (looks familiar on a given system) dialog box.
1974 Accepts and returns argument as an URL.
1975 Passing a filename as an URL is also allowed (as everywhere),
1976 it may be changed into an URL on return.
1977
1978 This dialog may also allow user for some typical file-management
1979 operations by the way (create some directories, rename some files etc.).
1980
1981 Returns @true and sets URL accordingly if user chooses some
1982 file and accepts it. Returns @false if user cancels.
1983
1984 @param(Title A dialog title.)
1985
1986 @param(URL Specifies default file as an URL (or simple filename).
1987
1988 In short, things are designed such that for normal file viewers,
1989 you can give here the URL of last opened file, or '' if none.
1990
1991 This URL can be absolute or relative, may include a path, may include a name.
1992 If you specify only a path (remember to end it with the slash),
1993 then it's the default path where to save the file.
1994 If you specify the name (component after final slash), then it's the
1995 proposed file name for saving (for OpenDialog, this proposed file name
1996 is ignored, since that's more natural for open dialogs).
1997
1998 Empty value ('') always means the same as "current directory", guaranteed.
1999 So it's equivalent to @code(URICurrentPath).
2000
2001 Note that the path must end with a slash. Otherwise '/tmp/blah' would be
2002 ambigous (it could mean either file name 'blah' in the dir '/tmp/' dir,
2003 or dir '/tmp/blah' without a proposed file name).)
2004
2005 @param(OpenDialog Is this an open (@true) or save (@false) file dialog.
2006
2007 @unorderedList(
2008 @item(
2009 If OpenDialog = @true: force the user to only choose existing
2010 (and readable) file. The intention is that you can open
2011 file indicated by URL, at least for reading. There is no guarantee
2012 about it though (it's not possible to guarantee it on a multi-process OS),
2013 the only 100% sure way to know that the file can be opened and read
2014 is to actually try to do it.
2015
2016 To directly read a file (as a stream) from the obtained URL
2017 you should usually use our CastleDownload.Download function.
2018 This way you get a readable stream and you
2019 automatically support loading data from the other protocols (http,
2020 data etc.) too.)
2021
2022 @item(
2023 If OpenDialog = @false: a save dialog.
2024 Allows user to select a non-existing file.
2025 If user chooses an existing file, some backends may show
2026 a warning like @italic("Are you sure you want to overwrite this file?").
2027
2028 The intention is that directory of the returned file should exist,
2029 and you should be able to write files there.
2030 But, again, there is no 100% guarantee about it.
2031 The only way to be sure whether you can save a file is to actually
2032 try to do it.
2033
2034 To directly write to a file (as a stream) to the obtained URL
2035 you should usually use our UrlSaveStream.)
2036 )
2037 )
2038
2039 @param(FileFilters A set of file filters to present to user.
2040 Pass @nil (default) if you do not want to use file file filters,
2041 so user will just always see everything. An overloaded version
2042 allows you to pass file filters encoded in a single string,
2043 this may be slightly more comfortable for call, see
2044 TFileFilterList.AddFiltersFromString
2045 for explanation how to encode filters in a string.)
2046
2047 As with all the model dialog methods here, like FileDialog,
2048 ColorDialog, MessageOK, MessageYesNo:
2049
2050 @unorderedList(
2051 @item(
2052 The events of this TCastleWindow will not happen
2053 while we are inside a modal dialog box.
2054
2055 We have a special code that disables all TCastleWindow
2056 callbacks (like TCastleWindow.OnUpdate) and temporarily
2057 disables all UI controls on the @link(Controls) list
2058 (so your TCastleUserInterface, TCastleTransform, TCastleView etc.
2059 instances will @italic(not) have their methods,
2060 like @code(Update), called).
2061 )
2062
2063 @item(
2064 The events of @link(Application) and (in case you have multiple
2065 windows open) the events of other TCastleWindow @italic(may)
2066 (but do not have to) happen, while the dialog box is open.
2067
2068 So be prepared there to handle the situation that this window may be "stuck"
2069 in a modal dialog box.
2070 )
2071 )
2072
2073 @groupBegin }
2074 function FileDialog(const Title: String; var Url: String;
2075 OpenDialog: boolean; FileFilters: TFileFilterList = nil): boolean; overload;
2076 function FileDialog(const Title: String; var Url: String;
2077 OpenDialog: boolean; const FileFilters: String): boolean; overload;
2078 { @groupEnd }
2079
2080 { Choose a color, using native (looks familiar on a given system) dialog box.
2081
2082 Initial value of Color specifies initial color proposed to the user.
2083 If user accepts, we return true and set Color accordingly, else
2084 we return false (and do not modify Color).
2085
2086 Overloaded version with TCastleColor specifies a color with alpha.
2087 But note that only some backends actually allow user to adjust alpha
2088 (others leave alpha unchanged).
2089 Backends that allow alpha editing now are: Cocoa, Xlib.
2090
2091 @groupBegin }
2092 function ColorDialog(var Color: TCastleColor): Boolean; overload;
2093 function ColorDialog(var Color: TCastleColorRGB): Boolean; overload;
2094 function ColorDialog(var Color: TVector3Byte): Boolean; overload;
2095 { @groupEnd }
2096
2097 { Show some information and just ask to press "OK",
2098 using native (looks familiar on a given system) dialog box. }
2099 procedure MessageOK(const S: String; const MessageType: TWindowMessageType);
2100
2101 { Ask a yes/no question, using native (looks familiar on a given system) dialog box. }
2102 function MessageYesNo(const S: String;
2103 const MessageType: TWindowMessageType = mtQuestion): boolean;
2104
2105 { Named parameters used to initialize this window.
2106 Right now not used (were used by NPAPI plugin, may be useful to new web target). }
2107 property NamedParameters: TCastleStringList read FNamedParameters;
2108 private
2109 LastFpsOutputTime: TTimerResult;
2110 FFpsShowOnCaption: boolean;
2111 FSwapFullScreen_Key: TKey;
2112 FClose_KeyString: String;
2113 FFpsCaptionUpdateDelay: Single;
2114 public
2115 { Show current frames per second on window caption.
2116 You can modify this property only @italic(before calling @link(Open).) }
2117 property FpsShowOnCaption: boolean
2118 read FFpsShowOnCaption write FFpsShowOnCaption default false;
2119
2120 { Key to use to switch between FullScreen and not FullScreen.
2121 Set to keyNone (default) to disable this functionality.
2122 Suggested value to enable this functionality is keyF11, this is consistent
2123 will fullscreen key in other programs.
2124 You can freely modify it at any time, even after calling @link(Open).
2125
2126 The fullscreen is switched by closing it, changing @link(FullScreen)
2127 property and opening it again. So be sure to have good OnOpen / OnClose
2128 implementations: you have to be able to recreate in OnOpen everything
2129 that was released in OnClose. }
2130 property SwapFullScreen_Key: TKey
2131 read FSwapFullScreen_Key write FSwapFullScreen_Key default keyNone;
2132
2133 { Key to use to close the window.
2134 Set to '' (default) to disable this functionality.
2135 Suggested value to enable this functionality is CharEscape.
2136 You can freely modify it at any time, even after calling @link(Open). }
2137 property Close_KeyString: String
2138 read FClose_KeyString write FClose_KeyString;
2139
2140 { The amount of time (in seconds) between updating Caption
2141 with current FPS value. Used when FpsShowOnCaption.
2142
2143 You probably don't want to change this -- the default value
2144 is synchronized with how often the @link(TFramesPerSecond) actually
2145 change. So there's no point in making this smaller (you may cause
2146 slowdowns, and you will not see anything better). }
2147 property FpsCaptionUpdateDelay: Single
2148 read FFpsCaptionUpdateDelay write FFpsCaptionUpdateDelay
2149 {$ifdef FPC}default DefaultFpsCaptionUpdateDelay{$endif};
2150
2151 { Configure some options typically used by "demo" applications. }
2152 procedure SetDemoOptions(const ASwapFullScreen_Key: TKey;
2153 AClose_KeyString: String;
2154 const AFpsShowOnCaption: boolean);
2155 end;
2156
2157 TCastleWindowCustom = TCastleWindow deprecated 'use TCastleWindow';
2158 TCastleWindowBase = TCastleWindow deprecated 'use TCastleWindow';
2159
2160 TWindowList = class({$ifdef FPC}specialize{$endif} TObjectList<TCastleWindow>)
2161 private
2162 { Call OnUpdate for all windows on this list. }
2163 procedure DoUpdate;
2164 public
2165 { Simply calls Invalidate on all items. }
2166 procedure Invalidate;
2167 end;
2168
2169 TCastleWindowClass = class of TCastleWindow;
2170
2171 { Application, managing all open TCastleWindow (OpenGL windows).
2172 This tracks all open instances of TCastleWindow
2173 and implements message loop. It also handles some global tasks
2174 like managing the screen (changing current screen resolution and/or
2175 bit depth etc.)
2176
2177 The only instance of this class should be in @link(Application) variable.
2178 Don't create any other instances of class TCastleApplication, there's no
2179 point in doing that. }
2180 TCastleApplication = class(TCustomApplication)
2181
2182 { Include CastleWindow-backend-specific parts of
2183 TCastleApplication class. Rules and comments that apply here are
2184 the same as in analogous place at TCastleWindow class,
2185 when read_window_interface is defined. }
2186
2187 {$define read_application_interface}
2188 {$I castlewindow_backend.inc}
2189 {$undef read_application_interface}
2190
2191 private
2192 FOnInitialize{, FOnInitializeJavaActivity}: TProcedure;
2193 FOnInitializeEvent: TNotifyEvent;
2194 Initialized, InitializedJavaActivity: boolean;
2195 FVideoColorBits: integer;
2196 FVideoFrequency: Cardinal;
2197 { Current window with OpenGL context active.
2198 Update in TCastleWindow.MakeCurrent, also TCastleWindow.Close. }
2199 Current: TCastleWindow;
2200 LastLimitFPSTime: TTimerResult;
2201 FMainWindow: TCastleWindow;
2202 //FUserAgent: String;
2203
2204 FOpenWindows: TWindowList;
2205 function GetOpenWindows(Index: integer): TCastleWindow;
2206 { Run @link(OnInitialize) and
2207 @link(TCastleApplicationProperties.OnInitializeJavaActivity) callbacks,
2208 if not run yet.
2209
2210 Called CastleEngineInitialize, not just @code(Initialize),
2211 because this is something entirely different from inherited
2212 TCustomApplication.Initialize. In particular, this should not
2213 be ever called by user code --- TCastleWindow implementation
2214 takes care to call it automatically. }
2215 procedure CastleEngineInitialize;
2216
2217 { Use MainWindow, or a guessed window supposed to be the main. }
2218 function GuessedMainWindow: TCastleWindow;
2219
2220 { Add new item to OpenWindows.
2221 Windows must not be already on OpenWindows list. }
2222 procedure OpenWindowsAdd(Window: TCastleWindow);
2223
2224 { Delete window from OpenWindows.
2225
2226 Given Window doesn't have to be on the OpenWindows list. If it is not, this
2227 method is NOOP. This is useful when this is called from TCastleWindow.Close
2228 because TCastleWindow.Close should work even for partially constructed
2229 Windows.
2230
2231 If Window was present on OpenWindows and after removing Window
2232 OpenWindowsCount = 0 and QuitWhenLastWindowClosed then it calls Quit. }
2233 procedure OpenWindowsRemove(Window: TCastleWindow; QuitWhenLastWindowClosed: boolean);
2234
2235 { Find window on the OpenWindows list. Returns index, or -1 if not found. }
2236 function FindWindow(Window: TCastleWindow): integer;
2237
2238 procedure CreateBackend;
2239 procedure DestroyBackend;
2240
2241 { Make sure that event loop exits as soon as possible.
2242
2243 At this point, we already set "Terminated" (from ancestor
2244 TCustomApplication) to @true. And your methods like "ProcessMessage"
2245 should check it, so no need to do anything special in BackendTerminate
2246 to make them exit.
2247
2248 However, some backends execute some native code to run a loop,
2249 like CASTLE_WINDOW_FORM may run FormApplication.Run
2250 or CASTLE_WINDOW_GTK may run (though doesn't now) gtk_main.
2251 You need to break these loops in this method. }
2252 procedure BackendTerminate;
2253
2254 { Call OnUpdate on all open windows,
2255 call ApplicationProperties.OnUpdate,
2256 and call OnRender on all necessary windows.
2257 This allows some backends to easily do everything that typically needs
2258 to be done continuosly (without the need for any message from the outside). }
2259 procedure UpdateAndRenderEverything(out WasAnyRendering: boolean); overload;
2260 procedure UpdateAndRenderEverything; overload;
2261
2262 procedure MarkSleeping;
2263
2264 { Can we wait (hang) for next message.
2265 See TCastleWindow.AllowSuspendForInput, this is similar but for
2266 the whole Application. Returns @true only if all open
2267 windows allow it and we don't have any
2268 @link(TCastleApplicationProperties.OnUpdate ApplicationProperties.OnUpdate). }
2269 function AllowSuspendForInput: boolean;
2270
2271 procedure DoLimitFPS;
2272 procedure SetMainWindow(const Value: TCastleWindow);
2273
2274 { Close all open windows, make ProcessMessage return @false,
2275 finish the @link(Run) method (if working), and thus finish the
2276 application work. }
2277 procedure CloseAllOpenWindows;
2278
2279 {$ifdef FPC}
2280 function GetVersion: String;
2281 procedure SetVersion(const Value: String);
2282 function GetTouchDevice: boolean;
2283 procedure SetTouchDevice(const Value: boolean);
2284 function GetLimitFPS: Single;
2285 procedure SetLimitFPS(const Value: Single);
2286 {$endif}
2287 function GetMainContainer: TCastleContainer;
2288 protected
2289 { Override TCustomApplication to pass TCustomApplication.Log
2290 to CastleLog logger. }
2291 procedure DoLog(EventType: TEventType; const Msg: String); override;
2292 { Every backend must override this. TCustomApplication will
2293 automatically catch exceptions occuring inside DoRun. }
2294 procedure DoRun; override;
2295 public
2296 { If VideoResize, then next VideoChange call will
2297 try to resize the screen to given VideoResizeWidth /
2298 VideoResizeHeight. Otherwise, next TryVideoChange and VideoChange will
2299 use default screen size.
2300 @groupBegin }
2301 VideoResize: Boolean;
2302 VideoResizeWidth,
2303 VideoResizeHeight: Integer;
2304 { @groupEnd }
2305
2306 procedure Notification(AComponent: TComponent; Operation: TOperation); override;
2307
2308 { Color bits per pixel that will be set by next VideoChange call,
2309 and that are tried to be used at TCastleWindow.Open.
2310 Zero means that system default is used. }
2311 property VideoColorBits: integer read FVideoColorBits write FVideoColorBits default 0;
2312
2313 { Video frequency to set in next VideoChange call.
2314 Leave as 0 to use system default. }
2315 property VideoFrequency: Cardinal read FVideoFrequency write FVideoFrequency default 0;
2316
2317 { Describe the changes recorded in variables VideoXxx,
2318 used by VideoChange and TryVideoChange.
2319 This is a multiline string, each line is indented by 2 spaces,
2320 always ends with CastleUtils.NL. }
2321 function VideoSettingsDescribe: String;
2322
2323 (*Change the screen size, color bits and such, following the directions
2324 you set in VideoColorBits, VideoResize,
2325 VideoResizeWidth / VideoResizeHeight, and VideoFrequency variables.
2326 Returns @true if success.
2327
2328 See example code
2329 @code(examples/user_interface/screen_resolution_change) for a working
2330 example.
2331
2332 Simple example usage:
2333
2334 @longCode(#
2335 unit GameChangeVideoResolution;
2336
2337 interface
2338
2339 var
2340 // TODO: Allow user to configure it somehow
2341 UserWantsToChangeScreenResolution: Boolean = true;
2342
2343 { Change screen resolution, if desired by UserWantsToChangeScreenResolution. }
2344 procedure ChangeResolution;
2345
2346 implementation
2347
2348 uses CastleWindow, CastleLog, CastleConfig;
2349
2350 procedure ChangeResolution;
2351 begin
2352 if UserWantsToChangeScreenResolution then
2353 begin
2354 Application.VideoResize := true;
2355 // TODO: Allow user to choose the desired resolution
2356 Application.VideoResizeWidth := 1024;
2357 Application.VideoResizeHeight := 768;
2358 if not Application.TryVideoChange then
2359 WritelnWarning('Cannot change screen resolution, continuing with current settings');
2360 end;
2361 end;
2362
2363 initialization
2364 UserWantsToChangeScreenResolution := UserConfig.GetValue('video/change_resolution', false);
2365 ChangeResolution;
2366 finalization
2367 Application.VideoReset;
2368 end.
2369 #)
2370
2371 TODO: Expose methods like EnumeratePossibleVideoConfigurations to predict
2372 what video settings are possible.
2373
2374 TODO: Prefix "Video" for the family of these functions is not clear.
2375 Something like "Screen" would be better.
2376 *)
2377 function TryVideoChange: boolean;
2378
2379 { Change the screen size, color bits and such, following the directions
2380 you set in VideoColorBits, VideoResize,
2381 VideoResizeWidth / VideoResizeHeight, and VideoFrequency variables.
2382 This actually just calls TryVideoChange and checks the result.
2383
2384 If not success: if OnErrorWarnUserAndContinue then we'll display
2385 a warning and continue. If not OnErrorWarnUserAndContinue then
2386 we'll raise an Exception.
2387
2388 @raises(Exception If video mode change failed,
2389 and OnErrorWarnUserAndContinue = false.) }
2390 procedure VideoChange(OnErrorWarnUserAndContinue: boolean);
2391
2392 { Return default screen video mode.
2393 If you never called TryVideoChange (with success), then this does nothing.
2394 This is automatically called in Application.Destroy,
2395 so at finalization of this unit. This way your game nicely restores
2396 screen resolution for user. }
2397 procedure VideoReset;
2398
2399 function ScreenHeight: integer;
2400 function ScreenWidth: integer;
2401
2402 { List of all open windows.
2403 @groupBegin }
2404 function OpenWindowsCount: integer;
2405 property OpenWindows[Index: integer]: TCastleWindow read GetOpenWindows;
2406 { @groupEnd }
2407
2408 { The application and CastleWindow backend is initialized.
2409 Called only once, at the very beginning
2410 of the game, when we're ready to load everything
2411 and the first OpenGL context is initialized (right before
2412 calling TCastleWindow.OnOpen).
2413
2414 For targets like Android or iOS,
2415 you should not do anything (even reading files) before this callback occurs.
2416 Only when this occurs, we know that external process told us
2417 "Ok, you're ready".
2418 So you should put all the game initialization in an Application.OnInitialize
2419 callback. It will be automatically called by CastleWindow backend
2420 when we're really ready (actually, a little later ---
2421 when OpenGL context is active, to allow you to display progress
2422 bars etc. when loading). }
2423 property OnInitialize: TProcedure read FOnInitialize write FOnInitialize;
2424 property OnInitializeEvent: TNotifyEvent read FOnInitializeEvent write FOnInitializeEvent;
2425
2426 { Used on platforms that can only show a single window (TCastleWindow) at a time,
2427 like mobile or web applications.
2428
2429 In other exceptional situations when we need a single window
2430 (e.g. to display CGE uncaught exception) we may also use this window,
2431 if set (otherwise we may use the 1st currently open window). }
2432 property MainWindow: TCastleWindow read FMainWindow write SetMainWindow;
2433
2434 { User agent string, when running inside a browser.
2435 TODO: Right now never set (was used by NPAPI plugin, may be useful to new web target). }
2436 //property UserAgent: String read FUserAgent;
2437
2438 { Process messages from the window system.
2439 You have to call this repeatedly to process key presses,
2440 mouse events, redraws and everything else.
2441 Messages are processed and appropriate window callbacks are called,
2442 like TCastleWindow.OnRender,
2443 TCastleWindow.OnUpdate,
2444 TCastleWindow.OnKeyPress and many others.
2445
2446 For simple programs calling the @link(Run) method is usually
2447 the best solution, @link(Run) just calls ProcessMessage in a loop.
2448 Manually using the ProcessMessage method allows you to implement
2449 modal dialog boxes (generally any kind of "display something
2450 until something happens" behavior). Make your own event loop like this:
2451
2452 @longCode(#
2453 while not SomethingHappened do
2454 Application.ProcessMessages(...);
2455 #)
2456
2457 This can used to implement routines that wait until a modal dialog box
2458 returns, like @link(MessageOK) or @link(MessageYesNo).
2459
2460 For comfort, returns @code(not Terminated).
2461 So it returns @true if we should continue, that is
2462 if @code(Terminate) method was not called (directly or by closing
2463 the last window). If you want to check it (if you
2464 allow the user at all to close the application during modal box or such)
2465 you can do:
2466
2467 @longCode(#
2468 while not SomethingHappened do
2469 if not Application.ProcessMessage(...) then
2470 Break;
2471 #)
2472
2473 Do not assume too much about message processing internals.
2474 For example, not all ProcessMessage calls cause redraw, even if redraw
2475 is requested by Invalidate. When we have messages to process,
2476 we generally don't call redraw or even OnUpdate.
2477
2478 @param(WaitForMessage If @true (and some other conditions are met,
2479 for example we do not have to call OnUpdate continuosly)
2480 then we can block, waiting for an event to process.
2481
2482 Set this to @true whenever you can, that is whenever your program
2483 only responds to user inputs (as opposed to making some operations,
2484 like animation or loading or ray-tracing something).
2485 Generally, when @code(SomethingHappened) from the example pseudo-code
2486 above can only be changed by user events (e.g. user has to click
2487 something; nothing happens if user doesn't click for 5 minutes or 5 hours).
2488 This allows to let OS and CPU have some rest, and spend time
2489 on other applications, or just sleep and conserve laptop battery power.
2490 )
2491
2492 @param(WaitToLimitFPS If @true, then we have backup mechanism for
2493 limiting CPU usage. When WaitForMessage mechanism cannot be used
2494 (becasue WaitForMessage is @false or some other conditions disallow it),
2495 and user doesn't throw events at us (we don't want to sleep when user
2496 produces many events e.g. by mouse move),
2497 then we can do a small sleep to stabilize number of ProcessMessage
2498 calls at LimitFPS per second.
2499
2500 Set this to @true whenever you can, that is whenever you don't need
2501 ProcessMessage to return as fast as it can. For example,
2502 when you're displaying some animation, then displaying LimitFPS frames
2503 should be enough. OTOH, if you really do something that should be done
2504 as fast as possible (like loading some file or ray-tracing) you probably
2505 have to set this to @false.
2506 )
2507 }
2508 function ProcessMessage(WaitForMessage, WaitToLimitFPS: boolean): boolean;
2509
2510 { Processes @italic(all) pending messages. Do not wait for anything.
2511
2512 Contrast this with ProcessMessage method, that processes only a single
2513 event. Or no event at all (when no events were pending and
2514 AllowSuspend = @false). This means that after calling ProcessMessage
2515 once, you may have many messages left in the queue (especially
2516 mouse move together with key presses typically makes a lot of
2517 events). So it's not good to use if you want to react timely to
2518 some user requests, e.g. when you do something time-consuming
2519 and allow user to break the task with Escape key.
2520
2521 ProcessAllMessages is like
2522 calling in a loop ProcessMessage(false, false), ends when
2523 ProcessMessage(false, false) didn't process any message
2524 or when quit was called (or last window closed).
2525
2526 So ProcessAllMessages makes sure we have processed all pending events,
2527 thus we are up-to-date with window system requests. }
2528 function ProcessAllMessages: boolean;
2529
2530 procedure Terminate; override;
2531
2532 { Run the program using TCastleWindow, by doing the event loop.
2533 Think of it as just a shortcut for "while ProcessMessage do ;".
2534
2535 Note that this does nothing if OpenWindowsCount = 0, that is there
2536 are no open windows. Besides the obvious reason (you didn't call
2537 TCastleWindow.Open on any window...) this may also happen if you called
2538 Close (or Application.Terminate) from your window OnOpen / OnResize callback.
2539 In such case no event would probably reach
2540 our program, and user would have no chance to quit, so Run just refuses
2541 to work and exits immediately without any error. }
2542 procedure Run;
2543
2544 function BackendName: String;
2545
2546 constructor Create(AOwner: TComponent); override;
2547 destructor Destroy; override;
2548
2549 procedure HandleException(Sender: TObject); override;
2550
2551 { Parse some command-line options and remove them from @link(Parameters)
2552 list. These are standard command-line parameters of Castle Game Engine programs.
2553
2554 See TCastleWindow.ParseParameters for more options specific to each window.
2555
2556 @definitionList(
2557 @itemLabel -h / @--help
2558 @item(Output help, exit.)
2559
2560 @itemLabel -v / @--version
2561 @item(Output version, exit,
2562 Uses @link(TCastleApplicationProperties.Version ApplicationProperties.Version).)
2563
2564 @itemLabel @--log-file FILE-NAME
2565 @item(Force log to given file, sets @link(LogFileName).)
2566
2567 @itemLabel @--display X-DISPLAY-NAME
2568 @item(Sets Application.XDisplayName under Unix.)
2569
2570 @itemLabel -psvn_x_xxx
2571 @item(
2572 (Only relevant on macOS.) A special parameter -psvn_x_xxx will be found
2573 and removed from the @link(Parameters) list. See
2574 http://forums.macrumors.com/showthread.php?t=207344 and
2575 http://stackoverflow.com/questions/10242115/os-x-strange-psn-command-line-parameter-when-launched-from-finder .
2576 )
2577
2578 @itemLabel @--no-limit-fps
2579 @item(Allows to disable
2580 @link(TCastleApplicationProperties.LimitFps ApplicationProperties.LimitFps),
2581 to allows to observe maximum FPS, see
2582 http://castle-engine.io/manual_optimization.php )
2583
2584 @itemLabel @--capabilities automatic|force-fixed-function|force-modern
2585 @item(Force OpenGL context to have specific capabilities, to test rendering on modern or ancient GPUs.)
2586 )
2587
2588 Moreover this also handles parameters from @link(TCastleWindow.ParseParameters),
2589 if @link(MainWindow) is set already.
2590 But note that our templates do not set @link(MainWindow) so early.
2591 We recommend to explicitly set window size / Window.FullScreen from code and call
2592 @link(TCastleWindow.ParseParameters) right after, to allow user to override.
2593
2594 Moreover this also handles parameters from @link(TSoundEngine.ParseParameters).
2595 }
2596 procedure ParseStandardParameters;
2597 function ParseStandardParametersHelp: String;
2598
2599 { Are we using OpenGLES for rendering. }
2600 function OpenGLES: Boolean;
2601
2602 {$ifdef FPC}
2603 property LimitFPS: Single read GetLimitFPS write SetLimitFPS;
2604 deprecated 'use ApplicationProperties.LimitFps';
2605 property Version: String read GetVersion write SetVersion;
2606 deprecated 'use ApplicationProperties.Version';
2607 property TouchDevice: boolean read GetTouchDevice write SetTouchDevice;
2608 deprecated 'use ApplicationProperties.TouchDevice';
2609 {$endif FPC}
2610 end;
2611
2612 { @deprecated Deprecated name for TCastleApplication. }
2613 TGLApplication = TCastleApplication deprecated;
2614
2615 { Single global instance of TCastleApplication.
2616 Automatically created / destroyed by CastleWindow unit. }
2617 function Application: TCastleApplication;
2618
2619 { Describe given key. Key is given as combination of character (UTF-8 character as String, may be '')
2620 and Key code (may be keyNone), and additional required @code(Modifiers)
2621 (although some modifiers may be already implied by KeyString, e.g. when it is CtrlA).
2622 See @link(TMenuItem.Key) and @link(TMenuItem.KeyString) and @link(TMenuItem.Modifiers).
2623
2624 Only when Key = keyNone and KeyString = ''
2625 then this combination doesn't describe any key, and we return @false.
2626 Otherwise we return @true and set S. }
2627 function KeyToString(const KeyString: String; const Key: TKey; const Modifiers: TModifierKeys;
2628 out S: String): boolean;
2629 function KeyString(const AKeyString: String; const Key: TKey; const Modifiers: TModifierKeys;
2630 out S: String): boolean; deprecated 'use KeyToString';
2631
2632 {$undef read_interface}
2633
2634 {$define read_global_interface}
2635 {$I castlewindow_backend.inc}
2636 {$undef read_global_interface}
2637
2638 {$define read_interface_2}
2639 {$i castlewindowmenu.inc}
2640 {$undef read_interface_2}
2641
2642 implementation
2643
2644 uses
2645 CastleLog, CastleGLVersion, CastleUriUtils, CastleControls, CastleMessaging,
2646 CastleRenderContext, CastleInternalGLUtils,
2647 {$define read_implementation_uses}
2648 {$I castlewindow_backend.inc}
2649 {$undef read_implementation_uses}
2650 Math;
2651
2652 {$define read_implementation}
2653
2654 var
2655 UnitFinalization: Boolean;
2656
2657 {$I castlewindowmenu.inc}
2658 {$I castlewindow_backend.inc}
2659
2660 { TWindowContainer ----------------------------------------------------------- }
2661
2662 constructor TWindowContainer.Create(AParent: TCastleWindow);
2663 begin
2664 inherited Create(nil);
2665 Parent := AParent;
2666 end;
2667
2668 procedure TWindowContainer.Invalidate;
2669 begin
2670 Parent.Invalidate;
2671 end;
2672
2673 function TWindowContainer.GLInitialized: boolean;
2674 begin
2675 Result := Parent.GLInitialized;
2676 end;
2677
2678 function TWindowContainer.PixelsWidth: Integer;
2679 begin
2680 Result := Parent.Width;
2681 end;
2682
2683 function TWindowContainer.PixelsHeight: Integer;
2684 begin
2685 Result := Parent.Height;
2686 end;
2687
2688 function TWindowContainer.PixelsRect: TRectangle;
2689 begin
2690 Result := Parent.Rect;
2691 end;
2692
2693 function TWindowContainer.GetMousePosition: TVector2;
2694 begin
2695 Result := Parent.MousePosition;
2696 end;
2697
2698 procedure TWindowContainer.SetMousePosition(const Value: TVector2);
2699 begin
2700 Parent.MousePosition := Value;
2701 end;
2702
2703 function TWindowContainer.Focused: boolean;
2704 begin
2705 Result := Parent.Focused;
2706 end;
2707
2708 procedure TWindowContainer.SetInternalCursor(const Value: TMouseCursor);
2709 begin
2710 Parent.InternalCursor := Value;
2711 end;
2712
2713 function TWindowContainer.GetTouches(const Index: Integer): TTouch;
2714 begin
2715 Result := Parent.Touches[Index];
2716 end;
2717
2718 function TWindowContainer.TouchesCount: Integer;
2719 begin
2720 Result := Parent.TouchesCount;
2721 end;
2722
2723 function TWindowContainer.SaveScreen(const SaveRect: TRectangle): TRGBImage;
2724 begin
2725 { In theory, the single-buffer
2726 case could be optimized (do not redraw if not needed, that is:
2727 if not invalidated), but it's not worth the complication since noone uses
2728 single-buffer for normal applications... And also, there is no reliable
2729 way to capture screen contents in case of single-buffer. }
2730
2731 EventBeforeRender;
2732 EventRender;
2733 Result := SaveScreen_NoFlush(SaveRect, Parent.SaveScreenBuffer);
2734 end;
2735
2736 { TCastleWindow ---------------------------------------------------------- }
2737
2738 constructor TCastleWindow.Create(AOwner: TComponent);
2739 begin
2740 inherited;
2741 FClosed := true;
2742 FWidth := WindowDefaultSize;
2743 FHeight := WindowDefaultSize;
2744 FLeft := WindowPositionCenter;
2745 FTop := WindowPositionCenter;
2746 FDoubleBuffer := true;
2747 if ApplicationProperties.Caption <> '' then
2748 FCaption[cpPublic] := ApplicationProperties.Caption
2749 else
2750 FCaption[cpPublic] := ApplicationName;
2751 FResizeAllowed := raAllowed;
2752 minWidth := 100; maxWidth := 4000;
2753 minHeight := 100; maxHeight := 4000;
2754 DepthBits := DefaultDepthBits;
2755 StencilBits := DefaultStencilBits;
2756 FCursor := mcDefault;
2757 FMultiSampling := 1;
2758 FVisible := true;
2759 FAutoRedisplay := true;
2760 OwnsMainMenu := true;
2761 FMousePosition := Vector2(-1, -1);
2762 FMainMenuVisible := true;
2763 // Using deprecated CreateContainer - should be internal in the future
2764 {$warnings off}
2765 FContainer := CreateContainer;
2766 {$warnings on}
2767 Close_KeyString := '';
2768 SwapFullScreen_Key := keyNone;
2769 FpsShowOnCaption := false;
2770 FFpsCaptionUpdateDelay := DefaultFpsCaptionUpdateDelay;
2771 FTouches := TTouchList.Create;
2772 FFocused := true;
2773 FNamedParameters := TCastleStringList.Create;
2774 FRequirements := TGLContextRequirements.Create(nil);
2775
2776 CreateBackend;
2777
2778 if Messaging <> nil then
2779 Messaging.OnReceive.Add({$ifdef FPC}@{$endif} MessageReceived);
2780 end;
2781
2782 destructor TCastleWindow.Destroy;
2783 begin
2784 Close; { <- This will be ignored if already Closed }
2785
2786 if OwnsMainMenu then
2787 FreeAndNil(FMainMenu) else
2788 if FMainMenu <> nil then
2789 begin
2790 FMainMenu.ParentWindow := nil; { clear Self from FMainMenu.ParentWindow }
2791 FMainMenu := nil;
2792 end;
2793
2794 if Messaging <> nil then
2795 Messaging.OnReceive.Remove({$ifdef FPC}@{$endif} MessageReceived);
2796
2797 FreeAndNil(FContainer);
2798 FreeAndNil(FTouches);
2799 FreeAndNil(FNamedParameters);
2800 FreeAndNil(FRequirements);
2801 inherited;
2802 end;
2803
2804 function TCastleWindow.CreateContainer: TWindowContainer;
2805 begin
2806 // Using deprecated CreateContainer - should be internal in the future
2807 {$warnings off}
2808 Result := TWindowContainer.Create(Self);
2809 {$warnings on}
2810 end;
2811
2812 procedure TCastleWindow.OpenCore;
2813
2814 procedure RenderLoadingBackground;
2815 var
2816 WindowRect, TextRect: TRectangle;
2817 UIScale: Single;
2818 begin
2819 WindowRect := Rect;
2820
2821 RenderContext.Viewport := WindowRect;
2822 OrthoProjection(FloatRectangle(WindowRect));
2823
2824 { Not only is RenderContext.Clear faster than DrawRectangle(WindowRect,...).
2825 In this case, it is also more reliable: in case of Android immersive
2826 mode, we may not have yet our desired size (our width or height is smaller
2827 than device screen). For some reason, RenderContext.Clear manages to clear
2828 the whole screen area anyway. }
2829 RenderContext.Clear([cbColor], Theme.LoadingBackgroundColor);
2830
2831 UIScale := TCastleContainer.InternalCalculateUIScale(
2832 Theme.LoadingUIScaling, Theme.LoadingUIReferenceWidth, Theme.LoadingUIReferenceHeight, Theme.LoadingUIExplicitScale,
2833 Container.Dpi, FRealWidth, FRealHeight);
2834 TextRect := Theme.ImagesPersistent[tiLoading].Image.Rect.
2835 ScaleAroundCenter(UIScale).
2836 Align(hpMiddle, WindowRect, hpMiddle).
2837 Align(vpMiddle, WindowRect, vpMiddle);
2838 Theme.Draw(TextRect, tiLoading, UIScale, Theme.LoadingColor);
2839
2840 // just like TCastleWindow.DoRender
2841 if HasDoubleBuffer then SwapBuffers else glFlush;
2842
2843 {$IFDEF android}
2844 { Workaround an ARM64 Android-specific bug which manifests on some devices
2845 (reproduced on Xiaomi MI 9 SE) that creates a dangling EInvalidOp after calling Theme.Draw.
2846 It doesn't seem to interfere with normal porgram workflow,
2847 neither it causes any visible graphic glitches in the image rendered by Theme.Draw,
2848 but causes ClearExceptions(true) to raise unrelated dangling exceptions,
2849 which in turn makes e.g. CastleScript misbehave.
2850 Also seems to be reproduced outside of Castle Game Engine:
2851 https://forum.lazarus.freepascal.org/index.php/topic,42933.msg318965.html?#msg318965
2852 It seems that clearing them once per app run is perfectly enough,
2853 all subsequent calls to Theme.Draw do not raise the exception. }
2854 ClearExceptions(false);
2855 {$ENDIF}
2856 end;
2857
2858 { Do the job of OpenCore, do not protect from possible exceptions raised inside. }
2859 procedure OpenUnprotected;
2860 begin
2861 { Once context is initialized, then Android activity is initialized,
2862 or iOS called CGEApp_Initialize -> so it's safe to access files. }
2863 ApplicationProperties._FileAccessSafe := true;
2864
2865 { Adjust Left/Top/Width/Height as needed.
2866
2867 Note: calculations below try to correct window geometry but they
2868 can fail to foresee some things. In particular, they do not take
2869 into account a potential menu bar that may be visible when MainMenu <> nil.
2870 E.g., when MainMenu <> nil and implementation supports MainMenu as
2871 menu bar (GTK and WINAPI implementations) and FullScreen then
2872 the actual OpenGL window size will NOT match ScreenWidth/Height,
2873 it will be slightly smaller (menu bar takes some space). }
2874 if Width = WindowDefaultSize then FWidth := Application.ScreenWidth * 4 div 5;
2875 if Height = WindowDefaultSize then FHeight := Application.ScreenHeight * 4 div 5;
2876 ClampVar(FWidth , MinWidth , MaxWidth);
2877 ClampVar(FHeight, MinHeight, MaxHeight);
2878 if Left = WindowPositionCenter then FLeft := (Application.ScreenWidth - Width ) div 2;
2879 if Top = WindowPositionCenter then FTop := (Application.ScreenHeight - Height) div 2;
2880 FRealWidth := FWidth;
2881 FRealHeight := FHeight;
2882
2883 { reset some window state variables }
2884 Pressed.Clear;
2885 Container.MousePressed := [];
2886 EventOpenCalled := false;
2887
2888 { Set Closed to false. Before OpenBackend and EventOpen + EventResize,
2889 since they can raise exceptions, and in reaction to it we will cleanly
2890 Close the window. }
2891 FClosed := false;
2892 Invalidated := false;
2893
2894 UpdateRequirements; // OpenBackend may use it
2895
2896 // initialize HasDoubleBuffer
2897 HasDoubleBuffer := DoubleBuffer;
2898 Assert(HasDoubleBuffer = FRequirements.DoubleBuffer);
2899
2900 { Call OpenBackend. Note that OpenBackend can call DoResize,
2901 it will still be correctly understood. }
2902 OpenBackend;
2903
2904 { Do MakeCurrent before setting RenderContext.Viewport and EventOpen. }
2905 MakeCurrent;
2906
2907 GLInformationInitialize;
2908
2909 if GLVersion.BuggyDepth32 and
2910 (glGetInteger(GL_DEPTH_BITS) >= 32) and
2911 (StencilBits = 0) then
2912 begin
2913 WritelnLog('Rendering Context Initialization',
2914 'Got >= 32-bit depth buffer, unfortunately it is known to be buggy on this OpenGL implementation. We will try to force 24-bit depth buffer by forcing stencil buffer.');
2915 { Close the window, increase StencilBits to try to force 24-bit
2916 depth buffer, and call ourselves again.
2917 Checking "StencilBits = 0" above prevents from getting into
2918 an infinite loop here. }
2919 Close({ QuitWhenLastWindowClosed } false);
2920 StencilBits := 8;
2921 OpenCore;
2922 Exit;
2923 end;
2924
2925 { synchronize RenderContext.Viewport with our Width/Height (note that, because
2926 of ResizeAllowed and MinWidth etc. that can be different than actual window
2927 sizes). }
2928 RenderContext.Viewport := Rect;
2929
2930 {$ifndef OpenGLES}
2931 if ( (AntiAliasing = aa2SamplesNicer) or
2932 (AntiAliasing = aa4SamplesNicer) ) and
2933 GLFeatures.NV_multisample_filter_hint then
2934 glHint(GL_MULTISAMPLE_FILTER_HINT_NV, GL_NICEST);
2935 {$endif}
2936
2937 try
2938 { Make ApplicationProperties.IsGLContextOpen true now, to allow creating
2939 TDrawableImage from Application.OnInitialize work Ok. }
2940 ApplicationProperties._GLContextEarlyOpen;
2941
2942 RenderLoadingBackground;
2943
2944 Application.CastleEngineInitialize;
2945 if Closed then Exit;
2946
2947 { Call first EventOpen and then EventResize.
2948 Note that DoOpen and DoResize must be done after the OpenGL context
2949 is initialized and everything is ready.
2950 Even the 1st OnOpen / OnResize event may call Application.ProcessMessages,
2951 e.g. because user calls CastleMessages.MessageOk. }
2952 EventOpenCalled := true;
2953 Container.EventOpen(Application.OpenWindowsCount);
2954
2955 { Check Closed here, in case OnOpen closed the window
2956 (by calling Application.Terminate (that calls Close on all windows) or direct Close
2957 on this window). Note that Close calls
2958 CloseBackend and generally has *immediate* effect --- that's why
2959 doing anything more with window now (like MakeCurrent) would be wrong. }
2960 if Closed then Exit;
2961
2962 DoResize(FRealWidth, FRealHeight, true);
2963 except
2964 { capture exceptions from Application.OnInitialize, Window.OnOpen, Window.OnResize }
2965 Application.HandleException(Self);
2966 end;
2967
2968 { Check Closed here, in case OnResize closed the window. }
2969 if Closed then Exit;
2970
2971 { to be SURE that current window's gl context is active,
2972 even if someone in EventOpen changed current gl context }
2973 MakeCurrent;
2974
2975 UpdateFullScreenBackend;
2976 end;
2977
2978 begin
2979 if not FClosed then Exit;
2980
2981 FDuringOpen := true;
2982 try
2983 try
2984 OpenUnprotected;
2985 except
2986 Close; raise;
2987 end;
2988 finally FDuringOpen := false end;
2989 end;
2990
2991 procedure TCastleWindow.Open(const Retry: TGLContextRetryOpenFunc);
2992 begin
2993 try
2994 OpenCore;
2995 except
2996 on E: EGLContextNotPossible do
2997 begin
2998 if Retry(Self) then
2999 Open(Retry) { recursive call } else
3000 raise;
3001 end;
3002 end;
3003 end;
3004
3005 { Try to lower
3006 - anti-aliasing (multi-sampling)
3007 - shadows (stencil buffer)
3008 - depth size
3009 requirements and initialize worse GL context. }
3010 function DefaultRetryOpen(Window: TCastleWindow): boolean;
3011 begin
3012 if Window.AntiAliasing <> aaNone then
3013 begin
3014 Window.AntiAliasing := aaNone;
3015 WritelnLog('OpenGL context', 'OpenGL context cannot be initialized. Multi-sampling (anti-aliasing) turned off, trying to initialize once again.');
3016 Result := true;
3017 end else
3018 if Window.StencilBits > 0 then
3019 begin
3020 Window.StencilBits := 0;
3021 WritelnLog('OpenGL context', 'OpenGL context cannot be initialized. Stencil buffer (shadow volumes) turned off, trying to initialize once again.');
3022 Result := true;
3023 end else
3024 if Window.DepthBits > DepthBitsFallback then
3025 begin
3026 Window.DepthBits := DepthBitsFallback;
3027 WritelnLog('OpenGL context', 'OpenGL context cannot be initialized. Depth bits decreased to %d, trying to initialize once again.', [
3028 DepthBitsFallback
3029 ]);
3030 Result := true;
3031 end else
3032 Result := false;
3033 end;
3034
3035 procedure TCastleWindow.Open;
3036 begin
3037 Open(@DefaultRetryOpen);
3038 end;
3039
3040 procedure TCastleWindow.Close(const QuitWhenLastWindowClosed: boolean);
3041 begin
3042 if FClosed then Exit;
3043
3044 try
3045 if EventOpenCalled then
3046 begin
3047 MakeCurrent;
3048 Container.EventClose(Application.OpenWindowsCount);
3049 end;
3050 finally
3051 CloseBackend;
3052
3053 FClosed := true;
3054
3055 Application.Current := nil;
3056
3057 { Note: it is important here that OpenWindowsRemove will not raise any error
3058 if Self is not on OpenWindows list. This is useful if the window
3059 was partially constructed.
3060
3061 E.g. when StencilBits was too high and OpenBackend
3062 method raised an exception EGLContextNotPossible. Then this method, Close,
3063 is called, but Self is not on OpenWindows list. And this fact should not be
3064 reported as an error -- error is EGLContextNotPossible ! }
3065 Application.OpenWindowsRemove(Self, QuitWhenLastWindowClosed);
3066 end;
3067 end;
3068
3069 procedure TCastleWindow.MakeCurrent;
3070 begin
3071 { Calling BackendMakeCurrent is done very often (before every event,
3072 so a couple of times for every frame). And usually it's useless,
3073 as most games have only 1 open window. }
3074 if Application.Current <> Self then
3075 begin
3076 BackendMakeCurrent;
3077 RenderContext := Container.Context;
3078 Application.Current := Self;
3079 end;
3080 end;
3081
3082 procedure TCastleWindow.SetAutoRedisplay(const Value: boolean);
3083 begin
3084 FAutoRedisplay := value;
3085 if Value then Invalidate;
3086 end;
3087
3088 procedure TCastleWindow.ReleaseAllKeysAndMouse;
3089 var
3090 Key: TKey;
3091 MouseButton: TCastleMouseButton;
3092 {$ifdef CASTLE_WINDOW_USE_PRIVATE_MODIFIERS_DOWN}
3093 ModKey: TModifierKey;
3094 B: boolean;
3095 {$endif}
3096 begin
3097 {$ifdef CASTLE_WINDOW_USE_PRIVATE_MODIFIERS_DOWN}
3098 { When CASTLE_WINDOW_USE_PRIVATE_MODIFIERS_DOWN, I *HAVE* to use below
3099 SetPrivateModifiersDown. It would be an error to do DoKeyUp(keyCtrl)
3100 directly when CASTLE_WINDOW_USE_PRIVATE_MODIFIERS_DOWN, instead we have to
3101 use SetPrivateModifiersDown(mkCtrl, ...).
3102 This is the only way to make values in PrivateModifiersDown[]
3103 and Pressed[] arrays consistent. }
3104 for ModKey := Low(ModKey) to High(ModKey) do
3105 for B := Low(B) to High(B) do
3106 SetPrivateModifiersDown(ModKey, B, false);
3107 {$endif CASTLE_WINDOW_USE_PRIVATE_MODIFIERS_DOWN}
3108
3109 { Since we do DoKeyUp, this should also take care of releasing Characters. }
3110 for Key := Low(Key) to High(Key) do
3111 if Pressed[Key] then
3112 DoKeyUp(Key);
3113
3114 for MouseButton := Low(MouseButton) to High(MouseButton) do
3115 if MouseButton in MousePressed then
3116 DoMouseUp(MousePosition, MouseButton);
3117
3118 Container.MouseLookIgnoreNextMotion;
3119 end;
3120
3121 function TCastleWindow.GetColorBits: Cardinal;
3122 begin
3123 Result := RedBits + GreenBits + BlueBits;
3124 end;
3125
3126 procedure TCastleWindow.SetColorBits(const Value: Cardinal);
3127 begin
3128 RedBits := Value div 3;
3129 BlueBits := Value div 3;
3130 GreenBits := Value - RedBits - BlueBits;
3131 Assert(Value = ColorBits);
3132 end;
3133
3134 procedure TCastleWindow.SetAntiAliasing(const Value: TAntiAliasing);
3135 const
3136 AntiAliasingToMultiSampling: array [TAntiAliasing] of Cardinal =
3137 ( 1,
3138 2, 2,
3139 4, 4,
3140 8, 8,
3141 16, 16 );
3142 { Note: when new GPUs appear that support more samples,
3143 - extend the TAntiAliasing type and related arrays (just recompile to see
3144 where you need to change),
3145 - extend the src/x3d/opengl/glsl/source/screen_effect_library.glsl
3146 - extend the check for samples in ScreenEffectLibrary in CastleScreenEffects
3147 (this must be synchronized with screen_effect_library.glsl implementation).
3148 }
3149 begin
3150 FAntiAliasing := Value;
3151 MultiSampling := AntiAliasingToMultiSampling[Value];
3152 end;
3153
3154 { ----------------------------------------------------------------------------
3155
3156 TCastleWindow events DoXxx methods,
3157 implementations independent from the backend.
3158 Backends should always call DoXxx, never call directly EventXxx or OnXxx. }
3159
3160 procedure TCastleWindow.DoResize(AWidth, AHeight: integer; FirstResizeAfterOpen: boolean);
3161 begin
3162 { Set FRealWidth/Height unconditionally to AWidth/AHeight. }
3163 FRealWidth := AWidth;
3164 FRealHeight := AHeight;
3165
3166 { When setting FWidth/FHeight (which is used to report size to user,
3167 and to create OpenGL area size) we make sure some constaints are honored:
3168
3169 - You should not be able to resize the window when ResizeAllowed <> raAllowed.
3170 When ResizeAllowed = raNotAllowed, we want to guarantee that
3171 FWidth and FHeight stay constant, just as developer set them.
3172
3173 And some backends do not allow to express,
3174 or do not reliably honour, all possible ResizeAllowed values.
3175 E.g. Windows will always resize the window to fit on desktop.
3176 Window Manager on X can also do this.
3177 So we need to "forcefully" apply the ResizeAllowed logic here:
3178
3179 * raNotAllowed: FWidth and FHeight cannot change
3180
3181 * raOnlyAtOpen: FWidth and FHeight can change only at first EventResize
3182 (with FirstResizeAfterOpen = true), at least from the point of view of outside.
3183 Internally, every call to DoResize upto and including FirstResizeAfterOpen call
3184 changes FWidth and FHeight. This allows to accumulate e.g. size changes
3185 caused by FullScreen=true, in case OpenBackend does them by explicitly
3186 calling DoResize, like unix/castlewindow_xlib.inc .
3187
3188 * raAllowed: FWidth and FHeight can change freely
3189
3190 - Same thing for Min/MaxWidth/Height.
3191
3192 BTW, always MinWidth > 0 and MinHeight > 0,
3193 so the Clamp below will also make sure FWidth and FHeight are > 0.
3194
3195 We also secure from calls with FirstResizeAfterOpen=false
3196 from OpenBackend, which may happen from e.g. WinAPI and GTK backends.
3197 }
3198 if (ResizeAllowed = raAllowed) or
3199 ((ResizeAllowed = raOnlyAtOpen) and
3200 (FirstResizeAfterOpen or not EventOpenCalled)) then
3201 begin
3202 FWidth := Clamped(AWidth, MinWidth, MaxWidth);
3203 FHeight := Clamped(AHeight, MinHeight, MaxHeight);
3204 end;
3205
3206 { do not call EventResize before EventOpen (this check is needed
3207 because OpenBackend is allowed to call DoResize) }
3208 if not EventOpenCalled then Exit;
3209
3210 { jezeli ResizeAllowed <> raAllowed to nie powinnismy wywolywac EventResize
3211 poza pierwszym razem (gdy FirstResizeAfterOpen).
3212 Kazdy nastepny raz i tak bylby pozbawiony
3213 znaczenia, bo przeciez Width i Height i tak nie ulegly zmianie. }
3214 if (not FirstResizeAfterOpen) and (ResizeAllowed <> raAllowed) then Exit;
3215
3216 MakeCurrent;
3217 Container.EventResize;
3218 end;
3219
3220 procedure TCastleWindow.DoCloseQuery;
3221 begin
3222 MakeCurrent;
3223 if Assigned(OnCloseQuery) then
3224 OnCloseQuery(Container) else
3225 Close;
3226 end;
3227
3228 procedure TCastleWindow.DoRender;
3229 begin
3230 FrameProfiler.Start(fmBeforeRender);
3231 { We set Invalidated := false before EventRender (that calls OnRender),
3232 because we guarantee that calling Invalidate within OnRender will
3233 cause the redraw in next frame. }
3234 Invalidated := false;
3235 MakeCurrent;
3236 Container.EventBeforeRender;
3237 FrameProfiler.Stop(fmBeforeRender);
3238
3239 if Closed then Exit; { check, in case window got closed in the event }
3240
3241 FrameProfiler.Start(fmRender);
3242 Fps.InternalRenderBegin;
3243 try
3244 Container.EventRender;
3245 if Closed then Exit; { check, in case window got closed in the event }
3246
3247 if GLVersion.BuggySwapNonStandardViewport then
3248 RenderContext.Viewport := Rect;
3249
3250 FrameProfiler.Start(fmRenderSwapFlush);
3251 if HasDoubleBuffer then SwapBuffers else glFlush;
3252
3253 { Keep this check inside fmRenderSwapFlush measurement.
3254
3255 Naive explanation (seems wrong, see below):
3256 On Windows, SwapBuffers may execute immediately,
3257 but then the next OpenGL call actually waits for it to finish
3258 (see https://www.freelists.org/post/visionegg/swap-buffers-returns-immediately-for-2D-Textures-in-OpenGL-20,1 ).
3259 So if this is outside fmRenderSwapFlush, fmRenderSwapFlush would be usually
3260 zero, and most of the frame time would not be covered by anything we measure
3261 in FrameProfiler.
3262
3263 The above explanation is however proven wrong by:
3264
3265 in -dRELEASE builds, without CheckGLErrors call at all,
3266 fmRenderSwapFlush times are OK, nicely non-zero reasonable.
3267 I.e. we don't have the problem of fmRenderSwapFlush = zero in -dRELEASE
3268 builds, and we should -> if the above explanation was all that happens.
3269 If the above explanation was right, then we should also measure
3270 the next GL command (like RenderContext.Clear at the start
3271 of TCastleContainer.EventRender), but we don't need to.
3272
3273 Tested (both debug and release observations above) on
3274 Version string: 4.6.0 NVIDIA 425.46
3275 Vendor: NVIDIA Corporation
3276 Renderer: GeForce GTX 1050 Ti/PCIe/SSE2
3277 }
3278 {$ifdef CASTLE_WINDOW_CHECK_GL_ERRORS_AFTER_DRAW}
3279 CheckGLErrors('End of TCastleWindow.DoRender');
3280 {$endif}
3281
3282 FrameProfiler.Stop(fmRenderSwapFlush);
3283
3284 if AutoRedisplay then Invalidate;
3285 finally
3286 Fps.InternalRenderEnd;
3287 FrameProfiler.Stop(fmRender);
3288 end;
3289 end;
3290
3291 procedure TCastleWindow.DoKeyDown(const Key: TKey; const KeyString: String);
3292 var
3293 Event: TInputPressRelease;
3294
3295 function SeekMatchingMenuItem: TMenuItem;
3296
3297 function SeekMe(Entry: TMenuEntry): TMenuItem;
3298 var
3299 i: Integer;
3300 begin
3301 Result := nil;
3302 if Entry is TMenu then
3303 begin
3304 for i := 0 to TMenu(Entry).Count - 1 do
3305 begin
3306 Result := SeekMe(TMenu(Entry).Entries[i]);
3307 if Result <> nil then Break;
3308 end;
3309 end else
3310 if (Entry is TMenuItem) and
3311 TMenuItem(Entry).KeyMatches(Key, Event.KeyString, Pressed.Modifiers) then
3312 Result := TMenuItem(Entry);
3313 end;
3314
3315 begin
3316 if MainMenu <> nil then
3317 Result := SeekMe(MainMenu) else
3318 Result := nil;
3319 end;
3320
3321 var
3322 MatchingMI: TMenuItem;
3323 KeyRepeated: boolean;
3324 begin
3325 Event := InputKey(MousePosition, Key, KeyString, ModifiersDown(Container.Pressed));
3326
3327 KeyRepeated :=
3328 // Key or KeyString non-empty
3329 ((Key <> keyNone) or (KeyString <> '')) and
3330 // Key already pressed
3331 ((Key = keyNone) or Pressed.Keys[Key]) and
3332 // KeyString already pressed
3333 ((KeyString = '') or Pressed.Strings[KeyString]);
3334
3335 Pressed.KeyDown(Key, KeyString);
3336
3337 { This implementation guarantees that
3338
3339 A. we call some menu item
3340 B. *or* we call Container.EventPress.
3341
3342 There is *no* situation possible in which we don't handle key
3343 (because it matches menu item) but we also don't pass it to DoMenuClick.
3344 This also avoids some inconsistencies between SeekMatchingMenuItem
3345 and what GUI toolkit actually does, in case RedirectKeyDownToMenuClick = false
3346 (like on GTK): e.g. we had situation when SeekMatchingMenuItem was finding a menu
3347 item (for Key=keyNumPad7, KeyString='7') but for GTK it didn't match corresponding
3348 menu item.
3349
3350 It also means it is undefined (backend-specific) whether Container.EventPress
3351 *does* receive keys that triggered some menu items,
3352 when RedirectKeyDownToMenuClick = false.
3353 Some backends may hide such keys, some don't, and in case of
3354 RedirectKeyDownToMenuClick = false we dont' control it at all.
3355
3356 Only when RedirectKeyDownToMenuClick = true we guarantee that only *one*
3357 of A or B fires.
3358
3359 So:
3360 - We always guarantee that A or B occurs.
3361 - Only when RedirectKeyDownToMenuClick = true we guarantee that exactly one
3362 of A or B occurs.
3363 }
3364
3365 MatchingMI := nil;
3366 if (RedirectKeyDownToMenuClick or (not MainMenuVisible)) and
3367 (MainMenu <> nil) and
3368 MainMenu.Enabled then
3369 MatchingMI := SeekMatchingMenuItem;
3370 if MatchingMI <> nil then
3371 begin
3372 DoMenuClick(MatchingMI);
3373 end else
3374 begin
3375 MakeCurrent;
3376 Event.KeyRepeated := KeyRepeated;
3377 Container.EventPress(Event);
3378
3379 if Event.IsKey(Close_KeyString) then
3380 Close
3381 else
3382 if Event.IsKey(SwapFullScreen_Key) then
3383 FullScreen := not FullScreen;
3384 end;
3385 end;
3386
3387 procedure TCastleWindow.DoKeyUp(const key: TKey);
3388 var
3389 KeyString: String;
3390 begin
3391 if Pressed[Key] then
3392 begin
3393 { keyNone key is never pressed, DoKeyDown guarantees this }
3394 Assert(Key <> keyNone);
3395 Pressed.KeyUp(Key, KeyString);
3396 MakeCurrent;
3397 Container.EventRelease(InputKey(MousePosition, Key, KeyString, ModifiersDown(Container.Pressed)));
3398 end;
3399 end;
3400
3401 procedure TCastleWindow.InternalFakeMotion(const Event: TInputMotion);
3402 begin
3403 DoMotion(Event);
3404 end;
3405
3406 procedure TCastleWindow.DoMotion(const Event: TInputMotion);
3407 begin
3408 MakeCurrent;
3409 Container.EventMotion(Event);
3410 if Event.FingerIndex = 0 then
3411 { change FMousePosition *after* EventMotion, callbacks may depend on it }
3412 FMousePosition := Event.Position;
3413 FTouches.FingerIndexPosition[Event.FingerIndex] := Event.Position;
3414 end;
3415
3416 procedure TCastleWindow.DoMouseDown(const Position: TVector2;
3417 Button: TCastleMouseButton; const FingerIndex: TFingerIndex);
3418 var
3419 Event: TInputPressRelease;
3420 begin
3421 if FingerIndex = 0 then
3422 begin
3423 FMousePosition := Position;
3424 Container.MousePressed := Container.MousePressed + [Button];
3425 end;
3426 MakeCurrent;
3427 Event := InputMouseButton(Position, Button, FingerIndex,
3428 ModifiersDown(Container.Pressed));
3429 Container.EventPress(Event);
3430 FTouches.FingerIndexPosition[Event.FingerIndex] := Event.Position;
3431 end;
3432
3433 procedure TCastleWindow.DoMouseUp(const Position: TVector2;
3434 Button: TCastleMouseButton; const FingerIndex: TFingerIndex;
3435 const TrackReleased: boolean);
3436 var
3437 Event: TInputPressRelease;
3438 begin
3439 if FingerIndex = 0 then
3440 begin
3441 FMousePosition := Position;
3442 Container.MousePressed := Container.MousePressed - [Button];
3443 end;
3444 MakeCurrent;
3445 Event := InputMouseButton(Position, Button, FingerIndex,
3446 ModifiersDown(Container.Pressed));
3447 Container.EventRelease(Event);
3448 if TrackReleased then
3449 { for desktops, when the mouse is used, we track the position of the mouse
3450 even after "mouse up" event. }
3451 FTouches.FingerIndexPosition[Event.FingerIndex] := Event.Position
3452 else
3453 { for touch devices, it does not make sense to track the position when the finger
3454 is not pressing. }
3455 FTouches.RemoveFingerIndex(Event.FingerIndex);
3456 end;
3457
3458 procedure TCastleWindow.DoMouseWheel(const Scroll: Single; const Vertical: boolean);
3459 begin
3460 MakeCurrent;
3461 Container.EventPress(InputMouseWheel(MousePosition, Scroll, Vertical,
3462 ModifiersDown(Container.Pressed)));
3463 end;
3464
3465 procedure TCastleWindow.DoUpdate;
3466 begin
3467 FrameProfiler.StartFrame;
3468 FrameProfiler.Start(fmUpdate);
3469
3470 BackendInsideUpdate;
3471
3472 MakeCurrent;
3473 Container.EventUpdate;
3474
3475 { show FPS on caption once FpsCaptionUpdateDelay passed }
3476 if FpsShowOnCaption and
3477 (TimerSeconds(Timer, LastFpsOutputTime) >= FpsCaptionUpdateDelay) then
3478 begin
3479 LastFpsOutputTime := Timer;
3480 SetCaption(cpFps, ' - FPS: ' + Fps.ToString);
3481 end;
3482
3483 UpdateFullScreenBackend;
3484
3485 FrameProfiler.Stop(fmUpdate);
3486 end;
3487
3488 procedure TCastleWindow.DoMenuClick(Item: TMenuItem);
3489 begin
3490 if (MainMenu <> nil) and (not MainMenu.Enabled) then Exit;
3491
3492 MakeCurrent;
3493 if Item.DoClick then Exit;
3494
3495 { Maybe Item.DoClick changed current OpenGL context and returned false?
3496 We want to be safe, so we do here MakeCurrent again. }
3497 MakeCurrent;
3498 if Assigned(OnMenuClick) then
3499 OnMenuClick(Container, Item);
3500 end;
3501
3502 procedure TCastleWindow.DoDropFiles(const FileNames: array of string);
3503 begin
3504 MakeCurrent;
3505 if Assigned(OnDropFiles) then
3506 OnDropFiles(Container, FileNames);
3507 end;
3508
3509 function TCastleWindow.MessageReceived(const Received: TCastleStringList;
3510 const ReceivedStream: TMemoryStream): boolean;
3511 var
3512 Url: String;
3513 begin
3514 Result := false;
3515 if (Received.Count = 2) and
3516 (Received[0] = 'open-associated-url') then
3517 begin
3518 Url := Received[1];
3519 DoDropFiles([Url]);
3520 Result := true;
3521 end;
3522 end;
3523
3524 function TCastleWindow.AllowSuspendForInput: boolean;
3525 begin
3526 {$warnings off} // keep deprecated working - OnUpdate
3527 Result := Container.AllowSuspendForInput and
3528 not (Invalidated or Assigned(OnUpdate) or FpsShowOnCaption);
3529 {$warnings on}
3530 end;
3531
3532 { Menu things ------------------------------------------------------------ }
3533
3534 procedure TCastleWindow.SetMainMenu(Value: TMenu);
3535 begin
3536 if MainMenu <> Value then
3537 begin
3538 if (not Closed) and ((MainMenu <> nil) <> (Value <> nil)) then
3539 raise EInternalError.Create('While TCastleWindow is not Closed, '+
3540 'you can''t set MainMenu from nil to non-nil or from non-nil to nil');
3541
3542 if FMainMenu <> nil then
3543 begin
3544 MenuFinalize;
3545 FMainMenu.ParentWindow := nil;
3546 end;
3547
3548 FMainMenu := Value;
3549
3550 if FMainMenu <> nil then
3551 begin
3552 FMainMenu.ParentWindow := Self;
3553 MenuInitialize;
3554 end;
3555 end;
3556 end;
3557
3558 { SaveScreenXxx --------------------------------------------------------------- }
3559
3560 function TCastleWindow.SaveScreenBuffer: TColorBuffer;
3561 begin
3562 if HasDoubleBuffer then
3563 Result := cbBack
3564 else
3565 Result := cbFront;
3566 end;
3567
3568 procedure TCastleWindow.SaveScreen(const Url: String);
3569 begin
3570 Container.SaveScreen(Url);
3571 end;
3572
3573 function TCastleWindow.SaveScreen: TRGBImage;
3574 begin
3575 if Closed then
3576 raise Exception.Create('Cannot save the screen when the TCastleWindow is closed');
3577 Result := Container.SaveScreen;
3578 end;
3579
3580 function TCastleWindow.SaveScreen(const SaveRect: TRectangle): TRGBImage;
3581 begin
3582 if Closed then
3583 raise Exception.Create('Cannot save the screen when the TCastleWindow is closed');
3584 Result := Container.SaveScreen(SaveRect);
3585 end;
3586
3587 function TCastleWindow.SaveScreenToGL(const SmoothScaling: boolean): TDrawableImage;
3588 begin
3589 Result := SaveScreenToGL(Rect, SmoothScaling);
3590 end;
3591
3592 function TCastleWindow.SaveScreenToGL(
3593 const SaveRect: TRectangle;
3594 const SmoothScaling: boolean): TDrawableImage;
3595 begin
3596 if Closed then
3597 raise Exception.Create('Cannot save the screen when the TCastleWindow is closed');
3598 Container.EventBeforeRender;
3599 Container.EventRender;
3600 Result := SaveScreenToGL_NoFlush(SaveRect, SaveScreenBuffer, SmoothScaling);
3601 end;
3602
3603 procedure TCastleWindow.SaveScreenDialog(ProposedUrl: String);
3604 begin
3605 if FileDialog('Save screen to file', ProposedUrl, false, SaveImage_FileFilters) then
3606 try
3607 SaveScreen(ProposedUrl);
3608 except
3609 on E: Exception do MessageOK('Unable to save screen: ' + E.Message, mtError);
3610 end;
3611 end;
3612
3613 function TCastleWindow.FileDialog(const Title: String; var Url: String;
3614 OpenDialog: boolean; FileFilters: TFileFilterList = nil): boolean;
3615 var
3616 FileName: String;
3617 begin
3618 { calculate FileName from URL }
3619 FileName := UriToFilenameSafe(Url);
3620 if OpenDialog then
3621 FileName := ExtractFilePath(FileName);
3622 Result := BackendFileDialog(Title, FileName, OpenDialog, FileFilters);
3623 if Result then
3624 Url := FilenameToUriSafe(FileName);
3625 end;
3626
3627 function TCastleWindow.FileDialog(const Title: String; var Url: String;
3628 OpenDialog: boolean; const FileFilters: String): boolean;
3629 var
3630 FFList: TFileFilterList;
3631 begin
3632 FFList := TFileFilterList.Create(true);
3633 try
3634 FFList.AddFiltersFromString(FileFilters);
3635 Result := FileDialog(Title, Url, OpenDialog, FFList);
3636 finally FreeAndNil(FFList) end;
3637 end;
3638
3639 function TCastleWindow.ColorDialog(var Color: TCastleColorRGB): boolean;
3640 var
3641 Color4: TCastleColor;
3642 begin
3643 Color4 := Vector4(Color, 1);
3644 Result := ColorDialog(Color4);
3645 if Result then
3646 Color := Color4.RGB;
3647 end;
3648
3649 function TCastleWindow.ColorDialog(var Color: TVector3Byte): boolean;
3650 var
3651 ColorSingle: TVector4;
3652 begin
3653 ColorSingle.X := Color.X / High(Byte);
3654 ColorSingle.Y := Color.Y / High(Byte);
3655 ColorSingle.Z := Color.Z / High(Byte);
3656 ColorSingle.W := 1;
3657 Result := ColorDialog(ColorSingle);
3658 if Result then
3659 Color := Vector3Byte(ColorSingle.XYZ);
3660 end;
3661
3662 { OpenAndRun ----------------------------------------------------------------- }
3663
3664 procedure TCastleWindow.OpenAndRun;
3665 begin
3666 Open;
3667 Application.Run;
3668 end;
3669
3670 { TCastleWindow ParseParameters -------------------------------------------------- }
3671
3672 procedure WindowOptionProc(OptionNum: Integer; HasArgument: boolean;
3673 const Argument: String; const SeparateArgs: TSeparateArgs; Data: Pointer);
3674 var
3675 Window: TCastleWindow absolute Data;
3676
3677 procedure ApplyGeometryParam(const geom: String);
3678 var
3679 p: integer;
3680 parWidth, parHeight, parXoff, parYoff: integer;
3681 xoffPlus, yoffPlus, sizeSpecified, positionSpecified: boolean;
3682 { p to znak w stringu geom ktory teraz chcemy czytac.
3683 parWidth i parHeight sa valid tylko o ile sizeSpecified.
3684 parXoff, parYoff, xoffPlus, yoffPlus sa valid tylko o ile positionSpecified.
3685 }
3686
3687 procedure ParseSize;
3688 { parsuje width i height }
3689 var startp: integer;
3690 begin
3691 sizeSpecified := true;
3692
3693 {width}
3694 startp := p;
3695 while SCharIs(geom, p, ['0'..'9']) do Inc(p);
3696 parWidth := StrToInt(CopyPos(geom, startp, p-1));
3697
3698 {height}
3699 if not SCharIs(geom, p, ['x','X']) then
3700 raise EInvalidParams.Create(
3701 'Invalid --geometry parameter : expected "x" between WIDTH and HEIGHT');
3702 Inc(p);
3703 startp := p;
3704 while SCharIs(geom, p, ['0'..'9']) do Inc(p);
3705 parHeight := StrToInt(CopyPos(geom, startp, p-1));
3706 end;
3707
3708 procedure ParsePosition;
3709 { parsuje xoff, yoff i koniec stringa. }
3710 var startp: integer;
3711 begin
3712 positionSpecified := true;
3713
3714 {xoff}
3715 if not SCharIs(geom, p, ['-','+']) then
3716 raise EInvalidParams.Create(
3717 'Invalid --geometry parameter : expected "-" or "+" before XOFF');
3718 xoffPlus := geom[p] = '+';
3719 Inc(p);
3720 startp := p;
3721 if SCharIs(geom, p, ['-','+']) then Inc(p);
3722 while SCharIs(geom, p, ['0'..'9']) do Inc(p);
3723 parXoff := StrToInt(CopyPos(geom, startp, p-1));
3724
3725 {yoff}
3726 if not SCharIs(geom, p, ['-','+']) then
3727 raise EInvalidParams.Create(
3728 'Invalid --geometry parameter : expected "-" or "+" before YOFF');
3729 yoffPlus := geom[p] = '+';
3730 Inc(p);
3731 startp := p;
3732 if SCharIs(geom, p, ['-','+']) then Inc(p);
3733 while SCharIs(geom, p, ['0'..'9']) do Inc(p);
3734 parYoff := StrToInt(CopyPos(geom, startp, p-1));
3735
3736 {end of string}
3737 if not (p = Length(geom)+1) then
3738 raise EInvalidParams.Create(
3739 'Invalid --geometry parameter : expected end of parameter');
3740 end;
3741
3742 begin
3743 Window.FullScreen := false;
3744 try
3745 sizeSpecified := false;
3746 positionSpecified := false;
3747 p := 1;
3748
3749 if SCharIs(geom, p,['+','-']) then
3750 ParsePosition else
3751 begin
3752 ParseSize;
3753 if p <= Length(geom) then ParsePosition;
3754 end;
3755
3756 {ok, now we can apply what we have}
3757 if sizeSpecified then
3758 begin
3759 Window.Width := parWidth;
3760 Window.Height := parHeight;
3761 end;
3762 if positionSpecified then
3763 begin
3764 if xoffPlus then
3765 Window.Left := parXoff else
3766 Window.Left := Application.ScreenWidth-parXoff-parWidth;
3767 if yoffPlus then
3768 Window.Top := parYoff else
3769 Window.Top := Application.ScreenHeight-parYoff-parHeight;
3770 end;
3771
3772 except
3773 on E: EConvertError do
3774 raise EInvalidParams.Create('Invalid --geometry parameter : '+E.Message);
3775 end;
3776 end;
3777
3778 procedure ApplyFullScreenCustomParam(const option: String);
3779 var p: integer;
3780 begin
3781 Window.FullScreen := true;
3782 try
3783 p := CharsPos(['x','X'], option);
3784 if p = 0 then
3785 raise EInvalidParams.Create(
3786 'Invalid --fullscreen-custom parameter - format is not WIDTHxHEIGHT');
3787 Application.VideoResizeWidth := StrToInt(Copy(option, 1, p-1));
3788 Application.VideoResizeHeight := StrToInt(SEnding(option, p+1));
3789 Application.VideoResize := true;
3790 Application.VideoChange(true);
3791 except
3792 on E: EConvertError do
3793 raise EInvalidParams.Create('Invalid --fullscreen-custom parameter : '+E.Message);
3794 end;
3795 end;
3796
3797 begin
3798 case OptionNum of
3799 0: Window.FullScreen := true;
3800 1: Window.FullScreen := false;
3801 2: ApplyGeometryParam(Argument);
3802 3: ApplyFullScreenCustomParam(Argument);
3803 4: ApplicationProperties.TouchDevice := true;
3804 else raise EInternalError.CreateFmt('WindowOptionProc: unhandled OptionNum %d', [OptionNum]);
3805 end;
3806 end;
3807
3808 procedure TCastleWindow.ParseParameters;
3809 const
3810 Options: array [0..4] of TOption = (
3811 (Short: #0; Long: 'fullscreen'; Argument: oaNone),
3812 (Short: #0; Long: 'window'; Argument: oaNone),
3813 (short: #0; Long: 'geometry'; Argument: oaRequired),
3814 (Short: #0; Long: 'fullscreen-custom'; Argument: oaRequired),
3815 (Short: #0; Long: 'pretend-touch-device'; Argument: oaNone)
3816 );
3817 begin
3818 Parameters.Parse(Options, {$ifdef FPC}@{$endif} WindowOptionProc, Self, true);
3819 end;
3820
3821 class function TCastleWindow.ParseParametersHelp: String;
3822 begin
3823 Result :=
3824 OptionDescription('--fullscreen', 'Set window to full-screen (cover whole screen).') + NL +
3825 OptionDescription('--window', 'Set window to not be full-screen.') + NL +
3826 OptionDescription('--geometry WIDTHxHEIGHT<sign>XOFF<sign>YOFF', 'Set window to not be full-screen, and set initial size and/or position.') + NL +
3827 OptionDescription('--fullscreen-custom WIDTHxHEIGHT', 'Change desktop resolution and set window to full-screen.') + NL +
3828 OptionDescription('--pretend-touch-device', 'Pretend this is a device with a touch screen, for debugging purposes.');
3829 end;
3830
3831 { TCastleWindow miscellaneous -------------------------------------------- }
3832
3833 procedure TCastleWindow.UpdateRequirements;
3834 begin
3835 FRequirements.DoubleBuffer := DoubleBuffer;
3836 FRequirements.ColorBits := ColorBits;
3837 FRequirements.RedBits := RedBits;
3838 FRequirements.GreenBits := GreenBits;
3839 FRequirements.BlueBits := BlueBits;
3840 FRequirements.DepthBits := DepthBits;
3841 FRequirements.AlphaBits := AlphaBits;
3842 FRequirements.StencilBits := StencilBits;
3843 FRequirements.MultiSampling := MultiSampling;
3844 end;
3845
3846 function TCastleWindow.RequestedBufferAttributes: String;
3847 begin
3848 UpdateRequirements;
3849 Result := FRequirements.RequestedBufferAttributes;
3850 end;
3851
3852 procedure TCastleWindow.CheckRequestedBufferAttributes(
3853 const ProviderName: String;
3854 ProvidedStencilBits, ProvidedDepthBits, ProvidedAlphaBits,
3855 ProvidedMultiSampling: Cardinal);
3856 begin
3857 UpdateRequirements;
3858 FRequirements.CheckRequestedBufferAttributes(ProviderName,
3859 ProvidedStencilBits, ProvidedDepthBits, ProvidedAlphaBits,
3860 ProvidedMultiSampling);
3861 end;
3862
3863 procedure TCastleWindow.MenuUpdateBegin;
3864 begin
3865 { MenuUpdateNeedsInitialize = false always when MenuUpdateInside = 0. }
3866 Assert((MenuUpdateInside <> 0) or (not MenuUpdateNeedsInitialize));
3867
3868 Inc(MenuUpdateInside);
3869 end;
3870
3871 procedure TCastleWindow.MenuUpdateEnd;
3872 begin
3873 Dec(MenuUpdateInside);
3874 if (MenuUpdateInside = 0) and MenuUpdateNeedsInitialize then
3875 begin
3876 MenuUpdateNeedsInitialize := false;
3877 { We could also manually call BackendMenuInitialize now,
3878 as we know MenuUpdateInside = 0. But MenuInitialize takes
3879 care also about some checks and updating MenuInitialized variable. }
3880 MenuInitialize;
3881 end;
3882 end;
3883
3884 procedure TCastleWindow.MenuInitialize;
3885 begin
3886 if MenuUpdateInside = 0 then
3887 begin
3888 if (not MenuInitialized) and (not Closed) and MainMenuVisible then
3889 begin
3890 BackendMenuInitialize;
3891 MenuInitialized := true;
3892 end;
3893 end else
3894 MenuUpdateNeedsInitialize := true;
3895 end;
3896
3897 procedure TCastleWindow.MenuFinalize;
3898 begin
3899 { MenuFinalize ignores MenuUpdateInside state, not needed. }
3900 if MenuInitialized and (not Closed) and MainMenuVisible then
3901 begin
3902 MenuInitialized := false;
3903 BackendMenuFinalize;
3904 end;
3905 end;
3906
3907 procedure TCastleWindow.SetWidth(const Value: Integer);
3908 begin
3909 if FWidth <> Value then
3910 begin
3911 FWidth := Value;
3912 if not Closed then
3913 WritelnWarning('Window', 'Changing TCastleWindow.Width when the window is open is not supported now');
3914 end;
3915 end;
3916
3917 procedure TCastleWindow.SetHeight(const Value: Integer);
3918 begin
3919 if FHeight <> Value then
3920 begin
3921 FHeight := Value;
3922 if not Closed then
3923 WritelnWarning('Window', 'Changing TCastleWindow.Height when the window is open is not supported now');
3924 end;
3925 end;
3926
3927 procedure TCastleWindow.SetLeft(const Value: Integer);
3928 begin
3929 if FLeft <> Value then
3930 begin
3931 FLeft := Value;
3932 if not Closed then
3933 WritelnWarning('Window', 'Changing TCastleWindow.Left when the window is open is not supported now');
3934 end;
3935 end;
3936
3937 procedure TCastleWindow.SetTop(const Value: Integer);
3938 begin
3939 if FTop <> Value then
3940 begin
3941 FTop := Value;
3942 if not Closed then
3943 WritelnWarning('Window', 'Changing TCastleWindow.Top when the window is open is not supported now');
3944 end;
3945 end;
3946
3947 procedure TCastleWindow.SetResizeAllowed(const Value: TResizeAllowed);
3948 begin
3949 if FResizeAllowed <> Value then
3950 begin
3951 FResizeAllowed := Value;
3952 if not Closed then
3953 WritelnWarning('Window', 'Changing TCastleWindow.ResizeAllowed when the window is open is not supported now');
3954 end;
3955 end;
3956
3957 procedure TCastleWindow.SetFullScreenWanted(const Value: Boolean);
3958 begin
3959 if FFullScreenWanted <> Value then
3960 begin
3961 FFullScreenWanted := Value;
3962
3963 if FDuringOpen and Value then
3964 WriteLnWarning('Window', 'TCastleWindow.FullScreen is changed during the initial Application.OnInitialize / OnOpen / OnResize events. This works, but is unoptimal (the window will start non-fullscreen and will only change to fullscreen later). ' + 'Usually you should rather initialize "Window.FullScreen" in the main unit "initialization" section.');
3965
3966 { When the window is Closed, updating FFullScreenBackend is trivial
3967 and can be done automatically. Otherwise, it is delated
3968 to UpdateFullScreenBackend call. }
3969 if Closed then
3970 FFullScreenBackend := Value;
3971 end;
3972 end;
3973
3974 procedure TCastleWindow.SimpleUpdateFullScreenBackend;
3975 begin
3976 if FFullScreenBackend <> FFullScreenWanted then
3977 begin
3978 FFullScreenBackend := FFullScreenWanted;
3979 if not Closed then
3980 begin
3981 Close(false);
3982 if FFullScreenBackend then
3983 begin
3984 { FFullScreenBackend is true, so we changed it from false to true.
3985 Save BeforeFullScreen* now. }
3986 BeforeFullScreenGeometryKnown := true;
3987 BeforeFullScreenLeft := Left;
3988 BeforeFullScreenTop := Top;
3989 BeforeFullScreenWidth := Width;
3990 BeforeFullScreenHeight := Height;
3991 end else
3992 begin
3993 { We change FFullScreenBackend from true to false.
3994 Set window geometry. Note that BeforeFullScreenGeometryKnown may be false,
3995 if the window was initially opened in FullScreen mode, in which case
3996 we just set default sensible geometry. }
3997 if BeforeFullScreenGeometryKnown then
3998 begin
3999 Left := BeforeFullScreenLeft;
4000 Top := BeforeFullScreenTop;
4001 Width := BeforeFullScreenWidth;
4002 Height := BeforeFullScreenHeight;
4003 end else
4004 begin
4005 Left := WindowPositionCenter;
4006 Top := WindowPositionCenter;
4007 Width := WindowDefaultSize;
4008 Height := WindowDefaultSize;
4009 end;
4010 end;
4011 Open;
4012 end;
4013 end;
4014 end;
4015
4016 procedure TCastleWindow.SwapFullScreen;
4017 begin
4018 FullScreen := not FullScreen;
4019 end;
4020
4021 function TCastleWindow.GetPublicCaption: String;
4022 begin
4023 Result := FCaption[cpPublic];
4024 end;
4025
4026 procedure TCastleWindow.SetPublicCaption(const Value: String);
4027 begin
4028 SetCaption(cpPublic, Value);
4029 end;
4030
4031 function TCastleWindow.GetWholeCaption: String;
4032 begin
4033 Result := FCaption[cpPublic] + FCaption[cpFps];
4034 end;
4035
4036 function TCastleWindow.Rect: TRectangle;
4037 begin
4038 if Closed then
4039 Result := TRectangle.Empty else
4040 Result := Rectangle(0, 0, Width, Height);
4041 end;
4042
4043 function TCastleWindow.GLInitialized: boolean;
4044 begin
4045 Result := not Closed;
4046 end;
4047
4048 procedure TCastleWindow.PostRedisplay;
4049 begin
4050 Invalidate;
4051 end;
4052
4053 {$ifndef CASTLE_WINDOW_LIBRARY}
4054 {$ifndef CASTLE_WINDOW_FORM}
4055 procedure TCastleWindow.Invalidate;
4056 begin
4057 if not Closed then
4058 Invalidated := true;
4059 end;
4060 {$endif}
4061 {$endif}
4062
4063 function TCastleWindow.Controls: TInternalChildrenControls;
4064 begin
4065 Result := Container.Controls;
4066 end;
4067
4068 function TCastleWindow.GetOnOpen: TContainerEvent;
4069 begin
4070 Result := Container.OnOpen;
4071 end;
4072
4073 procedure TCastleWindow.SetOnOpen(const Value: TContainerEvent);
4074 begin
4075 Container.OnOpen := Value;
4076 end;
4077
4078 function TCastleWindow.GetOnOpenObject: TContainerObjectEvent;
4079 begin
4080 Result := Container.OnOpenObject;
4081 end;
4082
4083 procedure TCastleWindow.SetOnOpenObject(const Value: TContainerObjectEvent);
4084 begin
4085 Container.OnOpenObject := Value;
4086 end;
4087
4088 function TCastleWindow.GetOnBeforeRender: TContainerEvent;
4089 begin
4090 Result := Container.OnBeforeRender;
4091 end;
4092
4093 procedure TCastleWindow.SetOnBeforeRender(const Value: TContainerEvent);
4094 begin
4095 Container.OnBeforeRender := Value;
4096 end;
4097
4098 function TCastleWindow.GetOnRender: TContainerEvent;
4099 begin
4100 Result := Container.OnRender;
4101 end;
4102
4103 procedure TCastleWindow.SetOnRender(const Value: TContainerEvent);
4104 begin
4105 Container.OnRender := Value;
4106 end;
4107
4108 function TCastleWindow.GetOnResize: TContainerEvent;
4109 begin
4110 Result := Container.OnResize;
4111 end;
4112
4113 procedure TCastleWindow.SetOnResize(const Value: TContainerEvent);
4114 begin
4115 Container.OnResize := Value;
4116 end;
4117
4118 function TCastleWindow.GetOnClose: TContainerEvent;
4119 begin
4120 Result := Container.OnClose;
4121 end;
4122
4123 procedure TCastleWindow.SetOnClose(const Value: TContainerEvent);
4124 begin
4125 Container.OnClose := Value;
4126 end;
4127
4128 function TCastleWindow.GetOnCloseObject: TContainerObjectEvent;
4129 begin
4130 Result := Container.OnCloseObject;
4131 end;
4132
4133 procedure TCastleWindow.SetOnCloseObject(const Value: TContainerObjectEvent);
4134 begin
4135 Container.OnCloseObject := Value;
4136 end;
4137
4138 function TCastleWindow.GetOnUpdate: TContainerEvent;
4139 begin
4140 Result := Container.OnUpdate;
4141 end;
4142
4143 procedure TCastleWindow.SetOnUpdate(const Value: TContainerEvent);
4144 begin
4145 Container.OnUpdate := Value;
4146 end;
4147
4148 function TCastleWindow.GetOnPress: TInputPressReleaseEvent;
4149 begin
4150 Result := Container.OnPress;
4151 end;
4152
4153 procedure TCastleWindow.SetOnPress(const Value: TInputPressReleaseEvent);
4154 begin
4155 Container.OnPress := Value;
4156 end;
4157
4158 function TCastleWindow.GetOnRelease: TInputPressReleaseEvent;
4159 begin
4160 Result := Container.OnRelease;
4161 end;
4162
4163 procedure TCastleWindow.SetOnRelease(const Value: TInputPressReleaseEvent);
4164 begin
4165 Container.OnRelease := Value;
4166 end;
4167
4168 function TCastleWindow.GetOnMotion: TInputMotionEvent;
4169 begin
4170 Result := Container.OnMotion;
4171 end;
4172
4173 procedure TCastleWindow.SetOnMotion(const Value: TInputMotionEvent);
4174 begin
4175 Container.OnMotion := Value;
4176 end;
4177
4178 procedure TCastleWindow.SetDemoOptions(const ASwapFullScreen_Key: TKey;
4179 AClose_KeyString: String;
4180 const AFpsShowOnCaption: boolean);
4181 begin
4182 // only for backward compatibility (when this parameter was Char) convert #0 to ''
4183 if AClose_KeyString = #0 then
4184 AClose_KeyString := '';
4185
4186 SwapFullScreen_Key := ASwapFullScreen_Key;
4187 Close_KeyString := AClose_KeyString;
4188 FpsShowOnCaption := AFpsShowOnCaption;
4189 end;
4190
4191 function TCastleWindow.GetTouches(const Index: Integer): TTouch;
4192 begin
4193 Result := FTouches[Index];
4194 end;
4195
4196 function TCastleWindow.TouchesCount: Integer;
4197 begin
4198 Result := FTouches.Count;
4199 end;
4200
4201 function TCastleWindow.MousePressed: TCastleMouseButtons;
4202 begin
4203 Result := Container.MousePressed;
4204 end;
4205
4206 function TCastleWindow.Pressed: TKeysPressed;
4207 begin
4208 Result := Container.Pressed;
4209 end;
4210
4211 function TCastleWindow.Fps: TFramesPerSecond;
4212 begin
4213 Result := Container.Fps;
4214 end;
4215
4216 function TCastleWindow.LeftTopToCastle(const V: TVector2): TVector2;
4217 begin
4218 Result := LeftTopToCastle(V.X, V.Y);
4219 end;
4220
4221 function TCastleWindow.LeftTopToCastle(const X, Y: Single): TVector2;
4222 begin
4223 Result.X := X;
4224 Result.Y := FRealHeight - 1 - Y;
4225 end;
4226
4227 function TCastleWindow.CastleToLeftTopInt(const V: TVector2): TVector2Integer;
4228 begin
4229 Result.X := Floor(V.X);
4230 Result.Y := FRealHeight - 1 - Floor(V.Y);
4231 end;
4232
4233 { TWindowList ------------------------------------------------------------ }
4234
4235 procedure TWindowList.Invalidate;
4236 var
4237 i: Integer;
4238 begin
4239 for i := 0 to Count - 1 do Items[i].Invalidate;
4240 end;
4241
4242 procedure TWindowList.DoUpdate;
4243 var
4244 i: integer;
4245 begin
4246 for i := 0 to Count - 1 do Items[i].DoUpdate;
4247 end;
4248
4249 { --------------------------------------------------------------------------
4250 Generic part of implementation of TCastleApplication,
4251 that does not depend what CASTLE_WINDOW_xxx backend you want. }
4252
4253 var
4254 FApplication: TCastleApplication;
4255
4256 constructor TCastleApplication.Create(AOwner: TComponent);
4257 begin
4258 inherited;
4259 FOpenWindows := TWindowList.Create(false);
4260 CreateBackend;
4261 OnMainContainer := {$ifdef FPC}@{$endif}GetMainContainer;
4262 end;
4263
4264 destructor TCastleApplication.Destroy;
4265 begin
4266 OnMainContainer := nil;
4267
4268 { Close any windows possibly open now.
4269 This is necessary --- after destroying Application there would be really
4270 no way for them to close properly (that is, TCastleWindow.CloseBackend
4271 may, and usually will, fail with very strange errors when called
4272 after freeing central Application). }
4273 CloseAllOpenWindows;
4274
4275 { unregister free notification from these objects }
4276 MainWindow := nil;
4277
4278 { nil now the Application variable. For reasoning, see this units
4279 finalization. }
4280 FApplication := nil;
4281
4282 VideoReset;
4283 DestroyBackend;
4284 FreeAndNil(FOpenWindows);
4285 inherited;
4286 end;
4287
4288 function TCastleApplication.GetMainContainer: TCastleContainer;
4289 begin
4290 if MainWindow <> nil then
4291 Result := MainWindow.Container
4292 else
4293 Result := nil;
4294 end;
4295
4296 procedure TCastleApplication.CastleEngineInitialize;
4297 var
4298 TimeStart, TimeStart2: TCastleProfilerTime;
4299 begin
4300 if Initialized and not InitializedJavaActivity then
4301 WritelnLog('Android', 'Android Java activity was killed (and now got created from stratch), but native thread survived. Calling only OnInitializeJavaActivity.');
4302
4303 if not InitializedJavaActivity then
4304 begin
4305 InitializedJavaActivity := true;
4306 {if Assigned(OnInitializeJavaActivity) then
4307 OnInitializeJavaActivity();}
4308 ApplicationProperties._InitializeJavaActivity;
4309 end;
4310
4311 if not Initialized then
4312 begin
4313 Initialized := true;
4314
4315 // Call OnInitialize and OnInitializeEvent, watched by Profiler
4316
4317 if Assigned(OnInitialize) or Assigned(OnInitializeEvent) then
4318 begin
4319 TimeStart := Profiler.Start('TCastleApplication Initialization');
4320 try
4321 if Assigned(OnInitialize) then
4322 begin
4323 TimeStart2 := Profiler.Start('TCastleApplication.OnInitialize');
4324 try
4325 OnInitialize();
4326 finally Profiler.Stop(TimeStart2) end;
4327 end;
4328
4329 if Assigned(OnInitializeEvent) then
4330 begin
4331 TimeStart2 := Profiler.Start('TCastleApplication.OnInitializeEvent');
4332 try
4333 OnInitializeEvent(Self);
4334 finally Profiler.Stop(TimeStart2) end;
4335 end;
4336 finally Profiler.Stop(TimeStart, true) end;
4337 end;
4338 end;
4339 end;
4340
4341 procedure TCastleApplication.SetMainWindow(const Value: TCastleWindow);
4342 begin
4343 if FMainWindow <> Value then
4344 begin
4345 if FMainWindow <> nil then
4346 FMainWindow.RemoveFreeNotification(Self);
4347 FMainWindow := Value;
4348 if FMainWindow <> nil then
4349 FMainWindow.FreeNotification(Self);
4350 end;
4351 end;
4352
4353 procedure TCastleApplication.Notification(AComponent: TComponent; Operation: TOperation);
4354 begin
4355 inherited;
4356 if (Operation = opRemove) and (AComponent = MainWindow) then
4357 MainWindow := nil;
4358 end;
4359
4360 function TCastleApplication.GetOpenWindows(Index: integer): TCastleWindow;
4361 begin
4362 result := FOpenWindows[Index];
4363 end;
4364
4365 function TCastleApplication.OpenWindowsCount: integer;
4366 begin
4367 result := FOpenWindows.Count;
4368 end;
4369
4370 procedure TCastleApplication.OpenWindowsAdd(Window: TCastleWindow);
4371 begin
4372 FOpenWindows.Add(Window);
4373 end;
4374
4375 procedure TCastleApplication.OpenWindowsRemove(Window: TCastleWindow;
4376 QuitWhenLastWindowClosed: boolean);
4377 begin
4378 if (FOpenWindows.Remove(Window) <> -1) and
4379 (OpenWindowsCount = 0) and
4380 QuitWhenLastWindowClosed then
4381 CloseAllOpenWindows;
4382 end;
4383
4384 function TCastleApplication.FindWindow(Window: TCastleWindow): integer;
4385 begin
4386 for result := 0 to OpenWindowsCount-1 do
4387 if OpenWindows[result] = Window then exit;
4388 result := -1;
4389 end;
4390
4391 {$ifdef CASTLE_NINTENDO_SWITCH}
4392 procedure CgeNxApplicationTerminate; cdecl; external;
4393 {$endif}
4394
4395 procedure TCastleApplication.Terminate;
4396 begin
4397 inherited;
4398
4399 {$ifdef CASTLE_NINTENDO_SWITCH}
4400 CgeNxApplicationTerminate;
4401 {$endif}
4402
4403 BackendTerminate;
4404 end;
4405
4406 procedure TCastleApplication.CloseAllOpenWindows;
4407 var
4408 OldOpenWindowsCount: Integer;
4409 begin
4410 { We're calling here Close(false) so we will not cause infinite recursive
4411 Quit calls.
4412
4413 Remember that calling Close actually calls Application.OpenWindowsRemove.
4414 In fact, it's guaranteed that calling Close on open
4415 window will remove it from OpenWindows list (we even check it by assert,
4416 otherwise our "while" could never finish).
4417 So the number of open windows will drop during while
4418 (that's why "for I := 0 to OpenWindowsCount - 1 do ..." would be stupid
4419 code here, but "while OpenWindowsCount > 0 ..." is Ok). }
4420
4421 while OpenWindowsCount > 0 do
4422 begin
4423 OldOpenWindowsCount := OpenWindowsCount;
4424 OpenWindows[0].Close(false);
4425 Assert(OpenWindowsCount = OldOpenWindowsCount - 1);
4426 end;
4427
4428 Terminate;
4429 end;
4430
4431 procedure TCastleApplication.UpdateAndRenderEverything(out WasAnyRendering: boolean);
4432 var
4433 I: integer;
4434 Window: TCastleWindow;
4435 begin
4436 WasAnyRendering := false;
4437
4438 { We call ApplicationProperties._Update *right before rendering*, because:
4439
4440 - This makes ApplicationProperties.OnUpdate callbacks have similar frequency
4441 as calls to window's OnRender callbacks, when the application
4442 is under a lot of stress (many messages).
4443
4444 Otherwise, if we would move this call outside of
4445 "if .. not CheckMessage then ..." in castlewindow_winsystem.inc,
4446 then doing something
4447 that generates a lot of events (like moving the mouse)
4448 would make us generate a lot OnUpdate events,
4449 without many OnRender between. Which isn't actually prohibited...
4450 but it seems useless.
4451
4452 - Calling OnUpdate later, only if "not WasAnyRendering", would
4453 also be bad, because then intensive redrawing (e.g. if you redraw
4454 every frame, with AutoRedisplay) would make OnUpdate called less
4455 often.
4456
4457 In effect, we like to have OnUpdate called roughly as often as OnRender,
4458 even if we don't really guarantee it. }
4459 ApplicationProperties._Update;
4460 if Terminated then Exit;
4461
4462 { Redraw some windows, and call window's OnUpdate.
4463
4464 Gathering OnUpdate and OnRender of the same window together,
4465 we minimize the amount of needed MakeContextCurrent calls in case
4466 of applications with multiple windows.
4467
4468 Remember that every callback may close the window, which also modifies
4469 the OpenWindows and OpenWindowsCount. The code below secures from
4470 all such changes, e.g. by copying "OpenWindows[I]" at the beginning,
4471 and checking "Window.Closed" all the time. }
4472 I := 0;
4473 while I < OpenWindowsCount do
4474 begin
4475 Window := OpenWindows[I];
4476 Window.DoUpdate;
4477 if Window.Closed then Continue {don't Inc(I)};
4478 if Terminated then Exit;
4479 Inc(I);
4480 end;
4481
4482 ApplicationProperties._UpdateEnd;
4483 if Terminated then Exit;
4484
4485 I := 0;
4486 while I < OpenWindowsCount do
4487 begin
4488 Window := OpenWindows[I];
4489 if Window.Invalidated then
4490 begin
4491 WasAnyRendering := true;
4492 Window.DoRender;
4493 if Window.Closed then Continue {don't Inc(I)};
4494 if Terminated then Exit;
4495 end else
4496 Window.Fps.InternalSleeping;
4497
4498 Inc(I);
4499 end;
4500 end;
4501
4502 procedure TCastleApplication.UpdateAndRenderEverything;
4503 var
4504 IgnoreWasAnyRendering: boolean;
4505 begin
4506 UpdateAndRenderEverything(IgnoreWasAnyRendering);
4507 end;
4508
4509 procedure TCastleApplication.MarkSleeping;
4510 var
4511 I: Integer;
4512 begin
4513 for I := 0 to OpenWindowsCount - 1 do
4514 OpenWindows[I].Fps.InternalSleeping;
4515 end;
4516
4517 function TCastleApplication.AllowSuspendForInput: boolean;
4518 var
4519 I: Integer;
4520 begin
4521 Result := ApplicationProperties.OnUpdate.Count = 0;
4522 if not Result then Exit;
4523
4524 for I := 0 to OpenWindowsCount - 1 do
4525 begin
4526 Result := OpenWindows[I].AllowSuspendForInput;
4527 if not Result then Exit;
4528 end;
4529 end;
4530
4531 { TCastleApplication.Video* things ---------------------------------------- }
4532
4533 {$ifndef CASTLE_WINDOW_HAS_VIDEO_CHANGE}
4534 function TCastleApplication.TryVideoChange: boolean;
4535 begin
4536 Result := false;
4537 end;
4538
4539 procedure TCastleApplication.VideoReset;
4540 begin
4541 end;
4542 {$endif not CASTLE_WINDOW_HAS_VIDEO_CHANGE}
4543
4544 function TCastleApplication.VideoSettingsDescribe: String;
4545 begin
4546 Result := '';
4547 if VideoResize then
4548 Result := Result + Format(' Screen size : %dx%d', [VideoResizeWidth, VideoResizeHeight]) + nl;
4549 if VideoColorBits <> 0 then
4550 Result := Result + Format(' Color bits per pixel : %d', [VideoColorBits]) + nl;
4551 if VideoFrequency <> 0 then
4552 Result := Result + Format(' Display frequency : %d', [VideoFrequency]) + nl;
4553
4554 if Result = '' then
4555 Result := ' No display settings change' + nl;
4556 end;
4557
4558 procedure TCastleApplication.VideoChange(OnErrorWarnUserAndContinue: boolean);
4559 var s: String;
4560 begin
4561 if not TryVideoChange then
4562 begin
4563 s := 'Can''t change display settings to : ' + nl + VideoSettingsDescribe;
4564
4565 {$ifndef CASTLE_WINDOW_HAS_VIDEO_CHANGE}
4566 S := S + ' (changing Video properties not implemented when CastleWindow is '+
4567 'made on top of ' + BackendName + ')';
4568 {$endif}
4569
4570 if OnErrorWarnUserAndContinue then
4571 WarningWrite(s+'. Trying to continue anyway.') else
4572 raise Exception.Create(s);
4573 end;
4574 end;
4575
4576 procedure TCastleApplication.DoLimitFPS;
4577 var
4578 NowTime: TTimerResult;
4579 TimeRemainingFloat: Single;
4580 begin
4581 if ApplicationProperties.LimitFPS > 0 then
4582 begin
4583 NowTime := Timer;
4584
4585 { When this is run for the 1st time, LastLimitFPSTime is zero,
4586 so NowTime - LastLimitFPSTime is huge, so we will not do any Sleep
4587 and only update LastLimitFPSTime.
4588
4589 For the same reason, it is not a problem if you do not call DoLimitFPS
4590 often enough (for example, you do a couple of ProcessMessage calls
4591 without DoLimitFPS for some reason), or when user temporarily sets
4592 LimitFPS to zero and then back to 100.0.
4593 In every case, NowTime - LastLimitFPSTime will be large, and no sleep
4594 will happen. IOW, in the worst case --- we will not limit FPS,
4595 but we will *never* slow down the program when it's not really necessary. }
4596
4597 TimeRemainingFloat :=
4598 { how long we should wait between _LimitFPS calls }
4599 1 / ApplicationProperties.LimitFPS -
4600 { how long we actually waited between _LimitFPS calls }
4601 TimerSeconds(NowTime, LastLimitFPSTime);
4602 { Don't do Sleep with too small values.
4603 It's better to have larger FPS values than limit,
4604 than to have them too small. }
4605 if TimeRemainingFloat > 0.001 then
4606 begin
4607 Sleep(Round(1000 * TimeRemainingFloat));
4608 LastLimitFPSTime := Timer;
4609 end else
4610 LastLimitFPSTime := NowTime;
4611 end;
4612 end;
4613
4614 function TCastleApplication.GuessedMainWindow: TCastleWindow;
4615 begin
4616 if MainWindow <> nil then
4617 Result := MainWindow else
4618 if OpenWindowsCount = 1 then
4619 Result := OpenWindows[0] else
4620 Result := nil; // no open window, or unknown which window is the main one
4621 end;
4622
4623 { Similar to TCustomApplication.HandleException, but not entirely.
4624
4625 - We don't want to fallback on SysUtils.ShowException, that is rather
4626 useless because when IsConsole, it shows only a summary of exception,
4627 without any stacktrace.
4628
4629 - Also we prefer our own ExceptMessage.
4630
4631 - If we cannot show the exception, we prefer to simply reraise it,
4632 closing the program, with default FPC exception handler (that shows
4633 the stacktrace). }
4634 procedure TCastleApplication.HandleException(Sender: TObject);
4635
4636 {$ifndef FPC}
4637 function ExceptionBackTrace(const E: TObject): String;
4638 begin
4639 if E is Exception then
4640 Result := Exception(E).StackTrace
4641 else
4642 Result := '';
4643 end;
4644 {$endif}
4645
4646 procedure DefaultShowException(ExceptObject: TObject; ExceptAddr: Pointer);
4647 var
4648 OriginalObj: TObject;
4649 OriginalAddr: Pointer;
4650 {$ifdef FPC}
4651 OriginalFrameCount: Longint;
4652 OriginalFrame: Pointer;
4653 {$endif}
4654 ErrMessage: String;
4655 ContinueApp: Boolean;
4656 begin
4657 ErrMessage := ExceptMessage(ExceptObject) + NL + NL +
4658 {$ifdef FPC} DumpExceptionBackTraceToString
4659 {$else} ExceptionBackTrace(ExceptObject)
4660 {$endif};
4661 { in case the following code, trying to handle the exception with nice GUI,
4662 will fail and crash horribly -- make sure to log the exception. }
4663 WritelnLog('Exception', ErrMessage);
4664
4665 if (GuessedMainWindow <> nil) and
4666 (not GuessedMainWindow.Closed) and
4667 { for some weird reason (even though we try to protect from it in code)
4668 handling of GuessedMainWindow.MessageOK causes another exception
4669 that resulted in recursive call to HandleException.
4670 Prevent the loop with just crash in this case. }
4671 (not Theme.InternalMessageFallbackLook) then
4672 begin
4673 OriginalObj := ExceptObject;
4674 OriginalAddr := ExceptAddr;
4675 {$ifdef FPC}
4676 OriginalFrameCount := ExceptFrameCount;
4677 OriginalFrame := ExceptFrames;
4678 {$endif}
4679 ContinueApp := false; // initialize, in case MessageYesNo will make exception
4680 try
4681 Theme.InternalMessageFallbackLook := true;
4682 ContinueApp := GuessedMainWindow.MessageYesNo(
4683 'An error occurred. Try to continue the application?' + NL + NL +
4684 'Error details:' + NL + ErrMessage, mtError);
4685 Theme.InternalMessageFallbackLook := false;
4686 except
4687 on E: TObject do
4688 begin
4689 WritelnWarning('Exception', 'Exception ' + E.ClassName + ' occurred in the error handler itself. This means we cannot report the exception by a nice dialog box. The *original* exception report follows.');
4690 // TODO: ExceptProc on Delphi:
4691 {$ifdef FPC}
4692 ExceptProc(OriginalObj, OriginalAddr {$ifdef FPC}, OriginalFrameCount, OriginalFrame{$endif});
4693 WritelnWarning('Exception', 'And below is a report about the exception within exception handler.');
4694 ExceptProc(SysUtils.ExceptObject, SysUtils.ExceptAddr, SysUtils.ExceptFrameCount, SysUtils.ExceptFrames);
4695 { Setting ErrorAddr avoids HeapTrc outputting looong useless output
4696 (since memory leaks are normal when you exit with Halt(...)
4697 and no finalization blocks are run). }
4698 {$endif}
4699 ErrorAddr := OriginalAddr;
4700 Halt(1);
4701 end;
4702 end;
4703
4704 if not ContinueApp then
4705 begin
4706 { Setting ErrorAddr avoids HeapTrc outputting looong useless output
4707 (since memory leaks are normal when you exit with Halt(...)
4708 and no finalization blocks are run). }
4709 ErrorAddr := OriginalAddr;
4710 Halt(1);
4711 end;
4712 end else
4713 begin
4714 { reraise, causing the app to exit with default FPC messsage and stacktrace }
4715 { not nice, as the stacktrace becomes overridden by this line in CastleWindow.pas:
4716 raise Exception.Create('Unhandled exception ' + ExceptMessage(ExceptObject, ExceptAddr));
4717 }
4718 { not correct, causes errors probably because ExceptObject is already freed:
4719 raise ExceptObject at ExceptAddr;
4720 }
4721 { this works best: }
4722 // TODO: ExceptProc
4723 {$ifdef FPC}
4724 ExceptProc(ExceptObject, ExceptAddr, ExceptFrameCount, ExceptFrames);
4725 {$endif}
4726 Halt(1);
4727 end;
4728 end;
4729
4730 begin
4731 if (not (ExceptObject is Exception)) or
4732 (not Assigned(OnException)) then
4733 DefaultShowException(ExceptObject, ExceptAddr)
4734 else
4735 OnException(Sender, Exception(ExceptObject));
4736
4737 if StopOnException then
4738 Terminate;
4739 end;
4740
4741 procedure TCastleApplication.DoLog(EventType : TEventType; const Msg : String);
4742 begin
4743 WritelnLog('CastleWindow', Msg);
4744 end;
4745
4746 procedure TCastleApplication.DoRun;
4747 begin
4748 ProcessMessage(true, true);
4749 end;
4750
4751 function TCastleApplication.ParseStandardParametersHelp: String;
4752 begin
4753 Result :=
4754 OptionDescription('-h / --help', 'Print this help message and exit.') + NL +
4755 OptionDescription('-v / --version', 'Print the version number and exit.') + NL +
4756 OptionDescription('--log-file FILE-NAME', 'Write log to given file.') + NL +
4757 OptionDescription('--display X-DISPLAY-NAME', '(Unix) Display window on given X display.') + NL +
4758 OptionDescription('--no-limit-fps', 'Disable FPS limit. (We cap FPS by default, to save CPU and laptop battery.) Use this along with disabled V-Sync to see the maximum possible FPS.') + NL +
4759 OptionDescription('--capabilities automatic|force-fixed-function|force-modern', 'Force OpenGL context to have specific capabilities, to test rendering on modern or ancient GPUs.');
4760 end;
4761
4762 // TODO: why this doesn't work as static TCastleApplication.OptionProc ?
4763 procedure ApplicationOptionProc(OptionNum: Integer; HasArgument: boolean;
4764 const Argument: String; const SeparateArgs: TSeparateArgs; Data: Pointer);
4765 var
4766 HelpString: String;
4767 begin
4768 case OptionNum of
4769 0: begin
4770 HelpString :=
4771 ApplicationName + NL+
4772 NL+
4773 'Available command-line options:' + NL +
4774 Application.ParseStandardParametersHelp + NL +
4775 SoundEngine.ParseParametersHelp + NL+
4776 // do this regardless of MainWindow <> nil, as MainWindow may be assigned later
4777 TCastleWindow.ParseParametersHelp + NL +
4778 NL +
4779 'TCastleWindow backend: ' + Application.BackendName + '.' + NL +
4780 NL +
4781 ApplicationProperties.Description;
4782 InfoWrite(HelpString);
4783 Halt;
4784 end;
4785 1: begin
4786 // include ApplicationName in --version output, this is good for help2man
4787 Writeln(ApplicationName + ' ' + ApplicationProperties.Version);
4788 Halt;
4789 end;
4790 2: LogFileName := Argument;
4791 3: begin
4792 {$ifdef CASTLE_WINDOW_XLIB}
4793 if Application.FOpenWindows.Count <> 0 then
4794 WarningWrite(ApplicationName + ': some windows are already open ' +
4795 'so --display option is ignored.') else
4796 Application.XDisplayName := Argument;
4797 {$else}
4798 {$ifdef CASTLE_WINDOW_GTK_2}
4799 Application.XDisplayName := Argument;
4800 {$else}
4801 WarningWrite(ApplicationName + ': warning: --display option is ignored ' +
4802 'when we don''t use directly Xlib');
4803 {$endif}
4804 {$endif}
4805 end;
4806 4: ApplicationProperties.LimitFps := 0;
4807 5: TGLFeatures.RequestCapabilities := StrToCapabilities(Argument);
4808 else raise EInternalError.Create('ApplicationOptionProc: unhandled OptionNum');
4809 end;
4810 end;
4811
4812 procedure TCastleApplication.ParseStandardParameters;
4813 const
4814 Options: array [0..5] of TOption =
4815 (
4816 (Short: 'h'; Long: 'help'; Argument: oaNone),
4817 (Short: 'v'; Long: 'version'; Argument: oaNone),
4818 (Short: #0 ; Long: 'log-file'; Argument: oaRequired),
4819 (Short: #0 ; Long: 'display'; Argument: oaRequired),
4820 (Short: #0 ; Long: 'no-limit-fps'; Argument: oaNone),
4821 (Short: #0 ; Long: 'capabilities'; Argument: oaRequired)
4822 );
4823
4824 {$ifdef DARWIN}
4825 procedure RemoveMacOsProcessSerialNumber;
4826 var
4827 I: Integer;
4828 begin
4829 for I := 1 to Parameters.Count - 1 do
4830 if IsPrefix('-psn_', Parameters[I], false) then
4831 begin
4832 Parameters.Delete(I);
4833 Exit;
4834 end;
4835 end;
4836 {$endif}
4837
4838 begin
4839 {$ifndef FPC}
4840 try
4841 {$endif}
4842
4843 {$ifdef DARWIN}
4844 RemoveMacOsProcessSerialNumber;
4845 {$endif}
4846
4847 SoundEngine.ParseParameters;
4848
4849 if MainWindow <> nil then
4850 MainWindow.ParseParameters;
4851
4852 Parameters.Parse(Options, @ApplicationOptionProc, Self, true);
4853
4854 { With FPC, if something here raises an exception,
4855 we just let it be unhandled and stop the application.
4856 FPC makes by default a nice error box, on Windows too.
4857 However Delphi crashes with SEGFAULT on Windows,
4858 testcase:
4859
4860 - cd examples/research_special_rendering_methods/test_rendering_opengl_capabilities
4861 - ./test_rendering_opengl_capabilities_standalone.exe --capabilities=something-invalid
4862 - or
4863 ./test_rendering_opengl_capabilities_standalone.exe --no-sound=excessive-argument
4864 - reproducible also in Delphi debugger, however without any useful backtrace.
4865
4866 Workaround for now is just to capture exception here,
4867 and display a nice error box ourselves. }
4868
4869 {$ifndef FPC}
4870 except
4871 on E: TObject do
4872 begin
4873 ErrorWrite(ExceptMessage(E));
4874 Halt(1);
4875 end;
4876 end;
4877 {$endif}
4878 end;
4879
4880 function TCastleApplication.OpenGLES: Boolean;
4881 begin
4882 (* Note that CGE own code can just use
4883 {$ifdef OpenGLES}
4884 instead of runtime check
4885 if Application.OpenGLES
4886
4887 However, for user code, we don't want to expose this as a define.
4888 - Because user code can be compiled in various ways.
4889 Our build tool can define some CGE-specific defines,
4890 but user can also compile without our build tool.
4891 - Some day, renderer selection may be possible at runtime.
4892
4893 So user code must use
4894 if Application.OpenGLES
4895 (or test with $ifdefs for specific platforms, like ANDROID or CASTLE_IOS.)
4896 *)
4897
4898 Result := {$ifdef OpenGLES} true {$else} false {$endif};
4899 end;
4900
4901 {$ifdef FPC}
4902
4903 function TCastleApplication.GetLimitFPS: Single;
4904 begin
4905 Result := ApplicationProperties.LimitFPS;
4906 end;
4907
4908 procedure TCastleApplication.SetLimitFPS(const Value: Single);
4909 begin
4910 ApplicationProperties.LimitFPS := Value;
4911 end;
4912
4913 function TCastleApplication.GetVersion: String;
4914 begin
4915 Result := ApplicationProperties.Version;
4916 end;
4917
4918 procedure TCastleApplication.SetVersion(const Value: String);
4919 begin
4920 ApplicationProperties.Version := Value;
4921 end;
4922
4923 function TCastleApplication.GetTouchDevice: boolean;
4924 begin
4925 Result := ApplicationProperties.TouchDevice;
4926 end;
4927
4928 procedure TCastleApplication.SetTouchDevice(const Value: boolean);
4929 begin
4930 ApplicationProperties.TouchDevice := Value;
4931 end;
4932
4933 {$endif}
4934
4935 { global --------------------------------------------------------------------- }
4936
4937 function KeyToString(const KeyString: String; const Key: TKey;
4938 const Modifiers: TModifierKeys; out S: String): boolean;
4939 const
4940 {$ifdef CASTLE_WINDOW_FORM}
4941 {$ifdef LCLCarbon}
4942 {$define CASTLE_CtrlIsCommand}
4943 {$endif}
4944 {$endif}
4945 // Our Cocoa backend always reports Command modifier as Ctrl.
4946 {$ifdef CASTLE_WINDOW_COCOA}
4947 {$define CASTLE_CtrlIsCommand}
4948 {$endif}
4949 CtrlIsCommand = {$ifdef CASTLE_CtrlIsCommand} true {$else} false {$endif};
4950 begin
4951 if KeyString <> '' then
4952 begin
4953 S := KeyStringToNiceStr(KeyString, Modifiers, false, CtrlIsCommand);
4954 Result := true;
4955 end else
4956 if Key <> keyNone then
4957 begin
4958 S := KeyToStr(Key, Modifiers, CtrlIsCommand);
4959 Result := true;
4960 end else
4961 Result := false;
4962 end;
4963
4964 function KeyString(const AKeyString: String; const Key: TKey; const Modifiers: TModifierKeys;
4965 out S: String): boolean;
4966 begin
4967 Result := KeyToString(AKeyString, Key, Modifiers, S);
4968 end;
4969
4970 function Application: TCastleApplication;
4971 begin
4972 { In case of UnitFinalization,
4973 return nil (and acccessing it should cause an error),
4974 since we wouldn't free it if we create a new one. }
4975 if (FApplication = nil) and not UnitFinalization then
4976 FApplication := TCastleApplication.Create(nil);
4977 Result := FApplication;
4978 end;
4979
4980 { init/fini --------------------------------------------------------------- }
4981
4982 initialization
4983 ApplicationProperties._FileAccessSafe := false;
4984 finalization
4985 UnitFinalization := true;
4986
4987 { Instead of using FreeAndNil, just call Free.
4988 In our destructor we take care of setting Application variable to @nil,
4989 when it becomes really useless.
4990
4991 Otherwise FreeAndNil first nils, then frees Application, and we really
4992 want to keep Application during first stage of TCastleApplication destruction:
4993 when calling Quit, which may close windows, which may use Application
4994 variable in their Close or CloseBackend implementations. }
4995 Application.Free;
4996 Assert(Application = nil);
4997
4998 { Order is important: we free MenuItems, which are needed
4999 by TMenu destructor. And some TCastleWindow instances may be freed
5000 only by Application destructor (when they are owned by Application). }
5001 FreeAndNil(FMenuItems);
5002 end.