Debian Codegraph @

src/lcl/castlecontrol.pas

raw
1 {
2 Copyright 2008-2023 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 { Component with OpenGL context suitable for 2D and 3D rendering
17 of "Castle Game Engine". }
18 unit CastleControl;
19
20 {$I castleconf.inc}
21
22 interface
23
24 uses
25 Classes, SysUtils,
26 StdCtrls, OpenGLContext, Controls, Forms, LCLVersion, LCLType, CustomTimer,
27 CastleRectangles, CastleVectors, CastleKeysMouse, CastleUtils, CastleTimeUtils,
28 CastleUIControls, CastleRenderOptions,
29 CastleImages, CastleGLVersion, CastleLCLUtils,
30 CastleGLImages, CastleApplicationProperties;
31
32 { Define this for new Lazarus that has Options (with ocoRenderAtDesignTime)
33 (see issue https://bugs.freepascal.org/view.php?id=32026 ). }
34 {$ifdef PASDOC}
35 {$define HAS_RENDER_AT_DESIGN_TIME}
36 {$else}
37 {$if LCL_FULLVERSION >= 1090000}
38 {$define HAS_RENDER_AT_DESIGN_TIME}
39 {$endif}
40 {$endif}
41
42 { Define to use a timer (with Interval = 1) to update the control.
43 If not defined, we will use Application.AddOnIdleHandler.
44 Unfortunately there's no perfect solution:
45
46 - Using Application.AddOnIdleHandler means that we need to install
47 idle handler that always sets "Done := false" (to prevent Lazarus
48 TApplication.Idle from doing WidgetSet.AppWaitMessage
49 in lazarus/lcl/include/application.inc ).
50
51 Disadvantages:
52
53 This approach blocks events registered later by Application.AddOnIdleHandler
54 from working. (because the first idle event with "Done := false" breaks
55 execution of idle events.)
56 This hurts in case you have other components using
57 LCL Application.AddOnIdleHandler.
58
59 We also should not do it at design-time in Lazarus IDE
60 (so e.g. TCastleControl cannot play animations at design-time in Lazarus IDE).
61
62 If you want to reliably do some continuous work, use Castle Game Engine
63 features to do it. There are various alternative ways:
64
65 - Register an event on @link(OnUpdate) of this component,
66
67 - Add custom @link(TCastleUserInterface) instance to the @link(Controls) list
68 with overridden @link(TCastleUserInterface.Update) method,)
69
70 - Register an event on @link(TCastleApplicationProperties.OnUpdate
71 ApplicationProperties.OnUpdate) from the @link(CastleApplicationProperties)
72 unit.
73
74 The advantage of Application.AddOnIdleHandler is that it always works,
75 it reliably prevents LCL from calling WidgetSet.AppWaitMessage that hangs
76 indefinitely long.
77
78 - Using timer means that we don't have to define idle handler.
79
80 This removes problems of idle:
81 We don't block other idle handlers (or timers).
82 We can animate at design-time in Lazarus IDE.
83
84 Disadvantage: It simply doesn't work with GTK widgetset.
85 The timer execution doesn't break the WidgetSet.AppWaitMessage
86 on GTK, and so timer with Interval=1 can in fact hang for an arbitrarily
87 long time if you don't make any event (like mouse movement).
88 }
89 {.$define CASTLE_CONTROL_UPDATE_TIMER}
90
91 type
92 TCastleControl = class;
93
94 { TCastleContainer that cooperates with TCastleControl. }
95 TCastleControlContainer = class(TCastleContainer)
96 strict private
97 FDesignUrl: String;
98 FDesignLoaded: TCastleUserInterface;
99 FDesignLoadedOwner: TComponent;
100 procedure SetDesignUrl(const Value: String);
101 procedure LoadDesign;
102 private
103 Parent: TCastleControl;
104 procedure UnLoadDesign;
105 protected
106 function GetMousePosition: TVector2; override;
107 procedure SetMousePosition(const Value: TVector2); override;
108 public
109 constructor Create(AParent: TCastleControl); reintroduce;
110 procedure Invalidate; override;
111 function GLInitialized: boolean; override;
112 function PixelsWidth: Integer; override;
113 function PixelsHeight: Integer; override;
114 procedure SetInternalCursor(const Value: TMouseCursor); override;
115 function SaveScreen(const SaveRect: TRectangle): TRGBImage; override; overload;
116
117 procedure EventOpen(const OpenWindowsCount: Cardinal); override;
118 procedure EventClose(const OpenWindowsCount: Cardinal); override;
119 function EventPress(const Event: TInputPressRelease): boolean; override;
120 function EventRelease(const Event: TInputPressRelease): boolean; override;
121 procedure EventUpdate; override;
122 procedure EventMotion(const Event: TInputMotion); override;
123 procedure EventBeforeRender; override;
124 procedure EventRender; override;
125 procedure EventResize; override;
126 public
127 { When the DesignUrl is set you can use this method to find
128 loaded components. Like this:
129
130 @longCode(#
131 MyButton := MyCastleControl.DesignedComponent('MyButton') as TCastleButton;
132 #)
133
134 When the name is not found, raises exception (unless Required is @false,
135 then it returns @nil).
136
137 @seealso DesignUrl }
138 function DesignedComponent(const ComponentName: String;
139 const Required: Boolean = true): TComponent;
140 published
141 { Load and show the design (.castle-user-interface file).
142 You can reference the loaded components by name using @link(DesignedComponent).
143
144 If you have more complicated control flow,
145 we recommend to leave this property empty, and split your management
146 into a number of states (TCastleView) instead.
147 In this case, load design using TCastleView.DesignUrl.
148 This property makes it however easy to use .castle-user-interface
149 in simple cases, when TCastleControl just shows one UI.
150
151 The design loaded here is visible also at design-time,
152 when editing the form in Lazarus/Delphi.
153 Though we have no way to edit it now in Lazarus/Delphi (you have to use CGE editor
154 to edit the design), so it is just a preview in this case.
155
156 See https://castle-engine.io/control_on_form for documentation how to use TCastleControl. }
157 property DesignUrl: String read FDesignUrl write SetDesignUrl;
158 end;
159
160 { Control to render everything (3D or 2D) with Castle Game Engine.
161
162 See https://castle-engine.io/control_on_form for a documentation
163 how to use this.
164
165 You can use this with TCastleView, following https://castle-engine.io/control_on_form instructions.
166 In this case, all user interface creation and event handling should
167 be inside some state.
168
169 You can also add any user-interface controls to the @link(Controls) property.
170 User-interface controls are any @link(TCastleUserInterface) descendants,
171 like @link(TCastleImageControl) or @link(TCastleButton) or @link(TCastleViewport).
172 Use events like @link(OnPress) to react to events.
173 Use event @link(OnUpdate) to do something continuously.
174
175 By default, the control is filled with simple color from
176 @link(TCastleContainer.BackgroundColor Container.BackgroundColor).
177
178 This control is an alternative to rendering things using TCastleWindow.
179 Note that you cannot use both TCastleControl and TCastleWindow
180 within the same application. }
181 TCastleControl = class(TCustomOpenGLControl)
182 strict private
183 FContainer: TCastleControlContainer;
184 FMousePosition: TVector2;
185 FGLInitialized: boolean;
186 FAutoRedisplay: boolean;
187 { manually track when we need to be repainted, useful for AggressiveUpdate }
188 Invalidated: boolean;
189 FOnOpen: TNotifyEvent;
190 FOnBeforeRender: TNotifyEvent;
191 FOnRender: TNotifyEvent;
192 FOnResize: TNotifyEvent;
193 FOnClose: TNotifyEvent;
194 FOnPress: TControlInputPressReleaseEvent;
195 FOnRelease: TControlInputPressReleaseEvent;
196 FOnMotion: TControlInputMotionEvent;
197 FOnUpdate: TNotifyEvent;
198 FKeyPressHandler: TLCLKeyPressHandler;
199 FAutoFocus: Boolean;
200
201 class var
202 { "Updating" means that the mechanism to call DoUpdateEverything
203 continuosly is set up. }
204 UpdatingEnabled: Boolean;
205
206 {$ifdef CASTLE_CONTROL_UPDATE_TIMER}
207 UpdatingTimer: TCustomTimer;
208 {$endif}
209
210 {$ifdef CASTLE_CONTROL_UPDATE_TIMER}
211 class procedure UpdatingTimerEvent(Sender: TObject);
212 {$else}
213 class procedure UpdatingIdleEvent(Sender: TObject; var Done: Boolean);
214 {$endif}
215 class procedure UpdatingEnable;
216 class procedure UpdatingDisable;
217 class procedure DoUpdateEverything;
218
219 { Sometimes, releasing shift / alt / ctrl keys will not be reported
220 properly to KeyDown / KeyUp. Example: opening a menu
221 through Alt+F for "_File" will make keydown for Alt,
222 but not keyup for it, and DoExit will not be called,
223 so ReleaseAllKeysAndMouse will not be called.
224
225 To counteract this, call this method when Shift state is known,
226 to update Pressed when needed. }
227 procedure UpdateShiftState(const Shift: TShiftState);
228
229 procedure KeyPressHandlerPress(Sender: TObject;
230 const Event: TInputPressRelease);
231
232 procedure SetMousePosition(const Value: TVector2);
233 procedure SetAutoRedisplay(const Value: boolean);
234 function GetDesignUrl: String;
235 procedure SetDesignUrl(const Value: String);
236
237 { Force DoUpdate and Paint (if invalidated) events to happen,
238 if sufficient time (based on LimitFPS, that in this case acts like
239 "desired FPS") passed.
240 This is needed when user "clogs" the GTK / WinAPI / Qt etc. event queue.
241 In this case Lazarus (LCL) doesn't automatically fire the idle and repaint
242 events.
243
244 The behavior of Lazarus application Idle events is such that they
245 are executed only when there are no events left to process.
246 This makes sense, and actually follows the docs and the name "idle".
247
248 In contrast, our DoUpdate expects to be run continuously, that is:
249 about the same number
250 of times per second as the screen Redraw (and if the screen doesn't need to
251 be redrawn, our DoUpdate should still run a sensible number of times
252 per second --- around the same value as LimitFPS, or (when LimitFPS
253 is set to 0, meaning "unused") as many times as possible).
254 For our DoUpdate, it should not matter whether your event
255 loop has something left to process. We need this,
256 since typical games / 3D simulations must try to update animations and
257 repaint at a constant rate, even when user is moving around.
258
259 The problem is most obvious when moving the mouse, for example when using
260 the mouse look to walk and look around in Walk mode (TCastleWalkNavigation.MouseLook),
261 or when dragging with mouse
262 in Examine mode. The event loop is then typically busy processing mouse move
263 events all the time, so it's never/seldom empty (note: it doesn't mean that
264 event loop is clogged, as mouse move events can be potentially accumulated
265 at various levels --- LCL, underlying widgetset like GTK, underlying system
266 like XWindows etc. I think in practice XWindows does it, but I'm not sure).
267 Our program should however still be responsive. Not only the screen should
268 be redrawn, regardless if our event loop is empty or not, but also
269 our Update event should be continuously called. But if we just use LCL Idle/Redraw
270 behavior (that descends from other widgetsets) then you may find that:
271 - during mouse look things "stutter" --- no Idle, not even Redraw,
272 happens regularly.
273 - during mouse drag Redraw may be regular, but still Idle are not called
274 (so e.g. animations do not move, instead they suddenly jump a couple
275 of seconds
276 forward when you stop dragging after a couple of seconds).
277
278 Note that TCastleWindow (with backends other than LCL) do not have this
279 problem. Maybe we process events faster, so that we don't get clogged
280 during MouseLook?
281
282 We can't fix it by hacking Application methods,
283 especially as LCL Application.ProcessMessage may handle a "batch"
284 of events (for example, may be ~ 100 GTK messages, see
285 TGtkWidgetSet.AppProcessMessages in lazarus/trunk/lcl/interfaces/gtk/gtkwidgetset.inc).
286 So instead we hack it from the inside: from time to time
287 (more precisely, LimitFPS times per second),
288 when receving an often occuring event (right now: just MouseMove),
289 we'll call the DoUpdate, and (if pending Invalidate call) Paint methods.
290
291 In theory, we could call this on every event (key down, mouse down etc.).
292 But in practice:
293 - Doing this from KeyDown would make redraw when moving by only holding
294 down some keys stutter a little (screen seems like not refreshed fast
295 enough). Reason for this stutter is not known,
296 it also stutters in case of mouse move, but we have no choice in this case:
297 either update with stuttering, or not update (continuously) at all.
298 TCastleWindow doesn't have this problem, mouse look is smooth there.
299 - It's also not needed from events other than mouse move.
300
301 In theory, for LimitFPS = 0, we should just do this every time.
302 But this would overload the system
303 (you would see smooth animation and rendering, but there will be latency
304 with respect to handling input, e.g. mouse move will be processed with
305 a small delay). So we use MaxDesiredFPS to cap it. }
306 procedure AggressiveUpdate;
307 private
308 class function GetMainContainer: TCastleContainer;
309 protected
310 procedure DestroyHandle; override;
311 procedure DoExit; override;
312 procedure Resize; override;
313 procedure KeyDown(var Key: Word; Shift: TShiftState); override;
314 procedure UTF8KeyPress(var UTF8Key: TUTF8Char); override;
315 procedure KeyUp(var Key: Word; Shift: TShiftState); override;
316 procedure MouseDown(Button: Controls.TMouseButton;
317 Shift:TShiftState; X,Y:Integer); override;
318 procedure MouseUp(Button: Controls.TMouseButton;
319 Shift:TShiftState; X,Y:Integer); override;
320 procedure MouseMove(Shift: TShiftState; NewX, NewY: Integer); override;
321 function DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; override;
322
323 procedure DoUpdate; virtual;
324
325 property GLInitialized: boolean read FGLInitialized;
326 public
327 class var
328 { Central control.
329
330 This is only important now if you use deprecated way of setting TCastleView,
331 using class properties/methods TUIState.Current, TUIState.Push.
332 If instead you use new way of setting TCastleView,
333 using container properties/methods TCastleContainer.Current, TCastleContainer.Push,
334 then this value isn't useful.
335
336 This means that in new applications, you probably have no need to set this value. }
337 MainControl: TCastleControl deprecated 'this should no longer be useful, if you change views using MyControl.Container.View := .. or MyControl.Container.PushView(...)';
338
339 constructor Create(AOwner: TComponent); override;
340 destructor Destroy; override;
341
342 { List of user-interface controls currently active.
343 You can add your TCastleUserInterface instances
344 (like TCastleViewport, TCastleButton and much more) to this list.
345 We will pass events to these controls, draw them etc.
346 See @link(TCastleContainer.Controls) for details. }
347 function Controls: TInternalChildrenControls;
348
349 function MakeCurrent(SaveOldToStack: boolean = false): boolean; override;
350 procedure Invalidate; override;
351 procedure Paint; override;
352
353 { Keys currently pressed. }
354 function Pressed: TKeysPressed;
355 { Mouse buttons currently pressed.
356 See @link(TCastleContainer.MousePressed) for details. }
357 function MousePressed: TCastleMouseButtons;
358 procedure ReleaseAllKeysAndMouse;
359
360 { Current mouse position.
361 See @link(TTouch.Position) for a documentation how this is expressed. }
362 property MousePosition: TVector2 read FMousePosition write SetMousePosition;
363
364 { Application speed. }
365 function Fps: TFramesPerSecond;
366
367 { Capture the current control contents to an image.
368 @groupBegin }
369 procedure SaveScreen(const Url: String); overload;
370 function SaveScreen: TRGBImage; overload;
371 function SaveScreen(const SaveRect: TRectangle): TRGBImage; overload;
372 { @groupEnd }
373
374 { Color buffer where we draw, and from which it makes sense to grab pixels.
375 Use only if you save the screen using low-level SaveScreen_NoFlush function.
376 Usually, you should save the screen using the simpler @link(SaveScreen) method,
377 and then the @name is not useful. }
378 function SaveScreenBuffer: TColorBuffer;
379
380 { Rectangle representing the inside of this container.
381 Always (Left,Bottom) are zero, and (Width,Height) correspond to container
382 sizes. }
383 function Rect: TRectangle;
384
385 function DesignedComponent(const ComponentName: String): TComponent;
386 deprecated 'use Container.DesignedComponent';
387
388 { Be cafeful about comments in the published section.
389 They are picked up and shown automatically by Lazarus Object Inspector,
390 and it has it's own logic, much much dumber than what PasDoc sees.
391 There seems no way to hide comment there.
392
393 We publish most, but not all, stuff from inherited TCustomOpenGLControl.
394
395 Exceptions:
396 - Don't publish these, as not every widgetset has them:
397 property RedBits;
398 property GreenBits;
399 property BlueBits;
400
401 - Don't publish these, as we have our own events for this:
402 property OnResize;
403 property OnClick;
404 property OnKeyDown;
405 property OnKeyPress;
406 property OnKeyUp;
407 property OnMouseDown;
408 property OnMouseMove;
409 property OnMouseUp;
410 property OnMouseWheel;
411 property OnMouseWheelDown;
412 property OnMouseWheelUp;
413 property OnPaint;
414
415 - Don't use, engine handles this completely:
416 property OnMakeCurrent;
417 property AutoResizeViewport;
418 }
419 published
420 property Align;
421 property Anchors;
422 property BorderSpacing;
423 property Enabled;
424 property OpenGLMajorVersion;
425 property OpenGLMinorVersion;
426 property MultiSampling;
427 property AlphaBits;
428 property DepthBits;
429 property StencilBits default DefaultStencilBits;
430 property AUXBuffers;
431 {$ifdef HAS_RENDER_AT_DESIGN_TIME}
432 property Options;
433 {$endif}
434 property OnChangeBounds;
435 property OnConstrainedResize;
436 property OnDblClick;
437 property OnDragDrop;
438 property OnDragOver;
439 property OnEnter;
440 property OnExit;
441
442 property OnMouseEnter;
443 property OnMouseLeave;
444 property OnShowHint;
445 property PopupMenu;
446 property ShowHint;
447 property Visible;
448 property TabOrder;
449 property TabStop default true;
450
451 { Automatically make this control focused (receiving key input)
452 when user clicks on it.
453
454 If this is @true, consider showing it in some way, e.g. draw something special
455 in OnRender when this control is focused. You can check "Focused" property
456 ( https://lazarus-ccr.sourceforge.io/docs/lcl/controls/twincontrol.focused.html )
457 or FormXxx.ActiveControl or register OnEnter / OnExit LCL events. }
458 property AutoFocus: Boolean read FAutoFocus write FAutoFocus default false;
459
460 { Access Castle Game Engine container properties and events,
461 not specific for Lazarus LCL. }
462 property Container: TCastleControlContainer read FContainer;
463
464 { Event called when the OpenGL context is created.
465
466 You can initialize things that require OpenGL context now.
467 Often you do not need to use this callback (engine components will
468 automatically create/release OpenGL resource when necessary).
469 You usually will also want to implement OnClose callback that
470 should release stuff you create here.
471
472 Often, instead of using this callback, it's cleaner to derive new classes
473 from TCastleUserInterface class or it's descendants,
474 and override their GLContextOpen / GLContextClose methods to react to
475 context being open/closed. Using such TCastleUserInterface classes
476 is usually easier, as you add/remove them from controls whenever
477 you want (e.g. you add them in ApplicationInitialize),
478 and underneath they create/release/create again the OpenGL resources
479 when necessary.
480
481 Note that we automatically initialize necessary Castle Game Engine resources
482 when context is created (@link(GLVersion), @link(GLFeatures) and more).
483
484 @deprecated Instead of this, use TCastleUserInterface and TCastleView virtual
485 method @link(TCastleUserInterface.GLContextOpen).
486 Or use ApplicationProperties.OnGLContextOpen to know when GL context is
487 created. }
488 property OnOpen: TNotifyEvent read FOnOpen write FOnOpen;
489 {$ifdef FPC}deprecated 'instead of this, use TCastleUserInterface and TCastleView virtual method GLContextOpen; or use ApplicationProperties.OnGLContextOpen';{$endif}
490
491 { Event called when the context is closed, right before the OpenGL context
492 is destroyed. This is your last chance to release OpenGL resources,
493 like textures, shaders, display lists etc. This is a counterpart
494 to OnOpen event.
495
496 @deprecated Instead of this, use TCastleUserInterface and TCastleView virtual
497 method @link(TCastleUserInterface.GLContextClose).
498 Or use ApplicationProperties.OnGLContextClose. }
499 property OnClose: TNotifyEvent read FOnClose write FOnClose;
500 {$ifdef FPC}deprecated 'instead of this, use TCastleUserInterface and TCastleView virtual method GLContextClose; or use ApplicationProperties.OnGLContextClose';{$endif}
501
502 { Event always called right before OnRender.
503 These two events, OnBeforeRender and OnRender,
504 will be always called sequentially as a pair.
505
506 The only difference between these two events is that
507 time spent in OnBeforeRender
508 is NOT counted as "frame time"
509 by Fps.OnlyRenderFps. This is useful when you have something that needs
510 to be done from time to time right before OnRender and that is very
511 time-consuming. It such cases it is not desirable to put such time-consuming
512 task inside OnRender because this would cause a sudden big change in
513 Fps.OnlyRenderFps value. So you can avoid this by putting
514 this in OnBeforeRender.
515
516 @deprecated Instead of this, use TCastleUserInterface and TCastleView virtual
517 method BeforeRender. Or just use virtual Render or OnRender event. }
518 property OnBeforeRender: TNotifyEvent read FOnBeforeRender write FOnBeforeRender;
519 {$ifdef FPC}deprecated 'instead of this, use TCastleUserInterface and TCastleView virtual method BeforeRender; or use virtual Render or OnRender event';{$endif}
520
521 { Render window contents here.
522
523 Called when window contents must be redrawn,
524 e.g. after creating a window, after resizing a window, after uncovering
525 the window etc. You can also request yourself a redraw of the window
526 by the Invalidate method, which will cause this event to be called
527 at nearest good time.
528
529 Note that calling Invalidate while in EventRender (OnRender) is not ignored.
530 It instructs to call EventRender (OnRender) again, as soon as possible.
531
532 When you have some controls on the @link(Controls) list,
533 the OnRender event is done @bold(last).
534 So here you can draw on top of the existing UI controls.
535 To draw something underneath the existing controls, create a new TCastleUserInterface
536 and override it's @link(TCastleUserInterface.Render) and insert it to the controls
537 using @code(Controls.InsertBack(MyBackgroundControl);).
538
539 @deprecated Instead of this, use TCastleUserInterface and TCastleView
540 virtual method Render and OnRender event. }
541 property OnRender: TNotifyEvent read FOnRender write FOnRender;
542 {$ifdef FPC}deprecated 'instead of this, use TCastleUserInterface and TCastleView virtual method Render or OnRender event';{$endif}
543
544 { Called when the control size (@code(Width), @code(Height)) changes.
545 It's also guaranteed to be called right after the OnOpen event.
546
547 @deprecated Instead of this, use TCastleUserInterface and TCastleView virtual
548 method Resize. }
549 property OnResize: TNotifyEvent read FOnResize write FOnResize;
550 {$ifdef FPC}deprecated 'instead of this, use TCastleUserInterface and TCastleView virtual method Resize';{$endif}
551
552 { Called when user presses a key or mouse button or moves mouse wheel.
553
554 @deprecated Instead of this, use TCastleUserInterface and TCastleView virtual
555 method Press and OnPress event. }
556 property OnPress: TControlInputPressReleaseEvent read FOnPress write FOnPress;
557 {$ifdef FPC}deprecated 'instead of this, use TCastleUserInterface and TCastleView virtual method Press or OnPress event';{$endif}
558
559 { Called when user releases a pressed key or mouse button.
560
561 It's called right after @code(Pressed[Key]) changed from true to false.
562
563 The TInputPressRelease structure, passed as a parameter to this event,
564 contains the exact information what was released.
565
566 Note that reporting characters for "key release" messages is not
567 perfect, as various key combinations (sometimes more than one?) may lead
568 to generating given character. We have some intelligent algorithm
569 for this, used to make Characters table and to detect
570 this C for OnRelease callback. The idea is that a character is released
571 when the key that initially caused the press of this character is
572 also released.
573
574 This solves in a determined way problems like
575 "what happens if I press Shift, then X,
576 then release Shift, then release X". (will "X" be correctly
577 released as pressed and then released? yes.
578 will small "x" be reported as released at the end? no, as it was never
579 pressed.)
580
581 @deprecated Instead of this, use TCastleUserInterface and TCastleView virtual
582 method Release and OnRelease event. }
583 property OnRelease: TControlInputPressReleaseEvent read FOnRelease write FOnRelease;
584 {$ifdef FPC}deprecated 'instead of this, use TCastleUserInterface and TCastleView virtual method Release or OnRelease event';{$endif}
585
586 { Mouse or a finger on touch device moved.
587
588 For a mouse, remember you always have the currently
589 pressed mouse buttons in MousePressed. When this is called,
590 the MousePosition property records the @italic(previous)
591 mouse position, while callback parameter NewMousePosition gives
592 the @italic(new) mouse position.
593
594 @deprecated Instead of this, use TCastleUserInterface and TCastleView virtual
595 method Motion and OnMotion event. }
596 property OnMotion: TControlInputMotionEvent read FOnMotion write FOnMotion;
597 {$ifdef FPC}deprecated 'instead of this, use TCastleUserInterface and TCastleView virtual method Motion or OnMotion event';{$endif}
598
599 { Continuously occuring event.
600 This event is called roughly as regularly as redraw,
601 and you should use this to update your game state.
602
603 Note that this is different than LCL "idle" event,
604 as it's guaranteed to be run continuously, even when your application
605 is clogged with events (like when using TCastleWalkNavigation.MouseLook).
606
607 @deprecated Instead of this, use TCastleUserInterface and TCastleView virtual
608 method Update and OnUpdate event. }
609 property OnUpdate: TNotifyEvent read FOnUpdate write FOnUpdate;
610 {$ifdef FPC}deprecated 'instead of this, use TCastleUserInterface and TCastleView virtual method Update or OnUpdate event';{$endif}
611
612 { Should we automatically redraw the window all the time,
613 without the need for an @link(Invalidate) call.
614 If @true (the default), OnRender will called constantly.
615
616 If your game may have a still screen (nothing animates),
617 then this approach is a little unoptimal, as we use CPU and GPU
618 for drawing, when it's not needed. In such case, you can set this
619 property to @false, and make sure that you call
620 @link(Invalidate) always when you need to redraw the screen.
621 Note that the engine components always call @link(Invalidate) when
622 necessary, so usually you should only call it yourself if you provide
623 a custom @link(OnRender) implementation. }
624 property AutoRedisplay: boolean read FAutoRedisplay write SetAutoRedisplay
625 default true;
626
627 { Load and show the design (.castle-user-interface file).
628 You can reference the loaded components by name using @link(DesignedComponent).
629
630 If you have more complicated control flow,
631 we recommend to leave this property empty, and split your management
632 into a number of states (TCastleView) instead.
633 In this case, load design using TCastleView.DesignUrl.
634 This property makes it however easy to use .castle-user-interface
635 in simple cases, when TCastleControl just shows one UI.
636
637 The design loaded here is visible also at design-time,
638 when editing the form in Lazarus/Delphi.
639 Though we have to way to edit it now in Lazarus/Delphi (you have to use CGE editor
640 to edit the design), so it is just a preview in this case. }
641 property DesignUrl: String read GetDesignUrl write SetDesignUrl stored false;
642 deprecated 'use Container.DesignUrl';
643 end;
644
645 TCastleControlCustom = TCastleControl deprecated 'use TCastleControl';
646
647 { Note: we need this deprecated class to be a separate class,
648 not just an alias for TCastleControl,
649 to be able to register it using RegisterNoIcon,
650 to support in old projects. }
651 TCastleControlBase = class (TCastleControl) end deprecated 'use TCastleControl';
652
653 procedure Register;
654
655 implementation
656
657 uses Math, Contnrs, LazUTF8, Clipbrd,
658 CastleControls, CastleGLUtils, CastleStringUtils, CastleLog, CastleRenderContext,
659 CastleUriUtils, CastleComponentSerialize, CastleInternalLclDesign;
660
661 // TODO: We never call Fps.InternalSleeping, so Fps.WasSleeping will be always false.
662 // This may result in confusing Fps.ToString in case AutoRedisplay was false.
663
664 { globals -------------------------------------------------------------------- }
665
666 procedure Register;
667 begin
668 RegisterComponents('Castle', [
669 TCastleControl
670 ]);
671 // register deprecated components in a way that they can be serialized, but are not visible on LCL palette
672 RegisterNoIcon([
673 {$warnings off}
674 TCastleControlBase
675 {$warnings on}
676 ]);
677 end;
678
679 var
680 { All TCastleControl instances created. We use this to share OpenGL contexts,
681 as all OpenGL contexts in our engine must share OpenGL resources
682 (our OnGLContextOpen and such callbacks depend on it,
683 and it makes implementation much easier). }
684 ControlsList: TComponentList;
685
686 { Tracks how many controls on ControlsList have GL context initialized. }
687 ControlsOpen: Cardinal;
688
689 { Used by DoLimitFPS in TCastleControl.DoUpdateEverything. }
690 LastLimitFPSTime: TTimerResult;
691
692 { TCastleControlContainer ---------------------------------------------------- }
693
694 procedure TCastleControlContainer.LoadDesign;
695
696 { Note: implementation of LoadDesign, UnLoadDesign and friends follow similar
697 methods in TCastleView. Here they are much simplified, as we have no concept
698 of "started" / "stopped", so no DesignPreload too. }
699
700 var
701 OldCastleApplicationMode: TCastleApplicationMode;
702 begin
703 if DesignUrl <> '' then
704 begin
705 { Make sure InternalCastleApplicationMode is correct, to
706 - not e.g. do physics in Lazarus/Delphi form designer.
707 - not show design-time stuff in DesignUrl loaded in CGE editor "help->system information".
708
709 Note that we restore later InternalCastleApplicationMode.
710 This way we avoid changing InternalCastleApplicationMode for future loads,
711 when TCastleControl is used inside castle-editor.
712 Testcase:
713 in CGE editor:
714 - open tools/castle-editor project
715 - double click on demo design in data/demo_animation/
716 - open help->system information (this uses TCastleControl too, with DesignUrl assigned)
717 - close help->system information
718 - close design
719 - reopen design
720 }
721 OldCastleApplicationMode := InternalCastleApplicationMode;
722 try
723 if csDesigning in ComponentState then
724 InternalCastleApplicationMode := appDesign
725 else
726 InternalCastleApplicationMode := appRunning;
727 FixApplicationDataInIDE; // in case DesignUrl uses castle-data: protocol, which is most often the case
728
729 FDesignLoadedOwner := TComponent.Create(nil);
730 try
731 FDesignLoaded := UserInterfaceLoad(DesignUrl, FDesignLoadedOwner);
732 {$ifdef HAS_RENDER_AT_DESIGN_TIME}
733 Parent.Options := Parent.Options + [ocoRenderAtDesignTime];
734 {$endif}
735 except
736 { If loading design file failed, and we're inside form designer,
737 merely report a warning. This allows deserializing LFMs with broken URLs. }
738 on E: Exception do
739 begin
740 if CastleDesignMode then // looks at InternalCastleApplicationMode
741 begin
742 WritelnWarning('TCastleControl', 'Failed to load design "%s": %s', [
743 UriDisplay(DesignUrl),
744 ExceptMessage(E)
745 ]);
746 Exit;
747 end else
748 raise;
749 end;
750 end;
751 Controls.InsertFront(FDesignLoaded);
752 finally
753 InternalCastleApplicationMode := OldCastleApplicationMode;
754 end;
755 end;
756 end;
757
758 procedure TCastleControlContainer.UnLoadDesign;
759 begin
760 FreeAndNil(FDesignLoadedOwner);
761 FDesignLoaded := nil; // freeing FDesignLoadedOwner must have freed this too
762 end;
763
764 procedure TCastleControlContainer.SetDesignUrl(const Value: String);
765 begin
766 if FDesignUrl <> Value then
767 begin
768 UnLoadDesign;
769 FDesignUrl := Value;
770 LoadDesign;
771 end;
772 end;
773
774 function TCastleControlContainer.DesignedComponent(const ComponentName: String;
775 const Required: Boolean = true): TComponent;
776 begin
777 if FDesignLoaded <> nil then
778 Result := FDesignLoadedOwner.FindComponent(ComponentName)
779 else
780 Result := nil;
781
782 if Required and (Result = nil) then
783 raise EComponentNotFound.CreateFmt('Cannot find component named "%s" in design "%s"', [
784 ComponentName,
785 UriDisplay(DesignUrl)
786 ]);
787 end;
788
789 constructor TCastleControlContainer.Create(AParent: TCastleControl);
790 begin
791 inherited Create(AParent); // AParent must be a component Owner to show published properties of container in LFM
792 Parent := AParent;
793 Dpi := Screen.PixelsPerInch;
794 end;
795
796 procedure TCastleControlContainer.Invalidate;
797 begin
798 Parent.Invalidate;
799 end;
800
801 function TCastleControlContainer.GLInitialized: boolean;
802 begin
803 Result := Parent.GLInitialized;
804 end;
805
806 function TCastleControlContainer.PixelsWidth: Integer;
807 begin
808 Result := Parent.Width;
809 end;
810
811 function TCastleControlContainer.PixelsHeight: Integer;
812 begin
813 Result := Parent.Height;
814 end;
815
816 function TCastleControlContainer.GetMousePosition: TVector2;
817 begin
818 Result := Parent.MousePosition;
819 end;
820
821 procedure TCastleControlContainer.SetMousePosition(const Value: TVector2);
822 begin
823 Parent.MousePosition := Value;
824 end;
825
826 procedure TCastleControlContainer.SetInternalCursor(const Value: TMouseCursor);
827 var
828 NewCursor: TCursor;
829 begin
830 NewCursor := CursorFromCastle(Value);
831
832 { Check explicitly "Cursor <> NewCursor", to avoid changing LCL property Cursor
833 too often. The SetInternalCursor may be called very often (in each mouse move).
834 (It is probably already optimized in LCL,
835 and in window manager too, but it's safer to not depend on it). }
836 if Parent.Cursor <> NewCursor then
837 Parent.Cursor := NewCursor;
838 end;
839
840 function TCastleControlContainer.SaveScreen(const SaveRect: TRectangle): TRGBImage;
841 begin
842 if Parent.MakeCurrent then
843 begin
844 EventBeforeRender;
845 EventRender;
846 end;
847 Result := SaveScreen_NoFlush(PixelsRect, Parent.SaveScreenBuffer);
848 end;
849
850 {$warnings off} // keep deprecated OnXxx wor
851
852 procedure TCastleControlContainer.EventOpen(const OpenWindowsCount: Cardinal);
853 begin
854 inherited;
855 if Assigned(Parent.OnOpen) then
856 Parent.OnOpen(Parent);
857 end;
858
859 procedure TCastleControlContainer.EventClose(const OpenWindowsCount: Cardinal);
860 begin
861 if Assigned(Parent.OnClose) then
862 Parent.OnClose(Parent);
863 inherited;
864 end;
865
866 function TCastleControlContainer.EventPress(const Event: TInputPressRelease): boolean;
867 begin
868 Result := inherited;
869 if (not Result) and Assigned(Parent.OnPress) then
870 begin
871 Parent.OnPress(Parent, Event);
872 Result := true;
873 end;
874 end;
875
876 function TCastleControlContainer.EventRelease(const Event: TInputPressRelease): boolean;
877 begin
878 Result := inherited;
879 if (not Result) and Assigned(Parent.OnRelease) then
880 begin
881 Parent.OnRelease(Parent, Event);
882 Result := true;
883 end;
884 end;
885
886 procedure TCastleControlContainer.EventUpdate;
887 begin
888 inherited;
889 if Assigned(Parent.OnUpdate) then
890 Parent.OnUpdate(Parent);
891 end;
892
893 procedure TCastleControlContainer.EventMotion(const Event: TInputMotion);
894 begin
895 inherited;
896 if Assigned(Parent.OnMotion) then
897 Parent.OnMotion(Parent, Event);
898 end;
899
900 procedure TCastleControlContainer.EventBeforeRender;
901 begin
902 inherited;
903 if Assigned(Parent.OnBeforeRender) then
904 Parent.OnBeforeRender(Parent);
905 end;
906
907 procedure TCastleControlContainer.EventRender;
908 begin
909 inherited;
910 if Assigned(Parent.OnRender) then
911 Parent.OnRender(Parent);
912 end;
913
914 procedure TCastleControlContainer.EventResize;
915 begin
916 inherited;
917 if Assigned(Parent.OnResize) then
918 Parent.OnResize(Parent);
919 end;
920
921 {$warnings on}
922
923 { TCastleControl -------------------------------------------------- }
924
925 constructor TCastleControl.Create(AOwner: TComponent);
926 begin
927 inherited;
928 TabStop := true;
929 FAutoRedisplay := true;
930 FKeyPressHandler := TLCLKeyPressHandler.Create;
931 FKeyPressHandler.OnPress := @KeyPressHandlerPress;
932 StencilBits := DefaultStencilBits;
933
934 {$ifdef DARWIN}
935 { On macOS, request "core" OpenGL context, otherwise we'll never get newer OpenGL than 2.1 }
936 OpenGLMajorVersion := 3;
937 OpenGLMinorVersion := 2;
938 { Just like in castlewindow_cocoa.inc, force modern at this point,
939 to avoid TGLFeatures using GLExt functions that use deprecated
940 OpenGL glGetString(GL_EXTENSIONS). }
941 TGLFeatures.RequestCapabilities := rcForceModern;
942 {$endif}
943
944 FContainer := TCastleControlContainer.Create(Self);
945 { SetSubComponent and Name setting (must be unique only within TCastleControl,
946 so no troubles) are necessary to store it in LFM and display in object inspector
947 nicely. }
948 FContainer.SetSubComponent(true);
949 FContainer.Name := 'Container';
950
951 // TODO: what if ControlsList[0] was created but it not active?
952 // Does this maybe explain crash with docked editor?
953 // We should set SharedControl to AnyOtherOpenContext, right before context is created, in CreateParams
954 if ControlsList.Count <> 0 then
955 SharedControl := ControlsList[0] as TCastleControl;
956 ControlsList.Add(Self);
957
958 Invalidated := false;
959 end;
960
961 destructor TCastleControl.Destroy;
962 begin
963 Container.UnLoadDesign;
964
965 FreeAndNil(FContainer);
966 FreeAndNil(FKeyPressHandler);
967
968 { Not necessary to remove from ControlsList explicitly,
969 as it is TComponentList and it will automatically remove us.
970 if ControlsList <> nil then
971 ControlsList.Remove(Self); }
972
973 inherited;
974 end;
975
976 class procedure TCastleControl.DoUpdateEverything;
977
978 procedure DoLimitFPS;
979 var
980 NowTime: TTimerResult;
981 TimeRemainingFloat: Single;
982 begin
983 if ApplicationProperties.LimitFPS > 0 then
984 begin
985 NowTime := Timer;
986
987 { When this is run for the 1st time, LastLimitFPSTime is zero,
988 so NowTime - LastLimitFPSTime is huge, so we will not do any Sleep
989 and only update LastLimitFPSTime.
990
991 For the same reason, it is not a problem if you do not call DoLimitFPS
992 often enough (for example, you do a couple of ProcessMessage calls
993 without DoLimitFPS for some reason), or when user temporarily sets
994 LimitFPS to zero and then back to 100.0.
995 In every case, NowTime - LastLimitFPSTime will be large, and no sleep
996 will happen. IOW, in the worst case --- we will not limit FPS,
997 but we will *never* slow down the program when it's not really necessary. }
998
999 TimeRemainingFloat :=
1000 { how long I should wait between _LimitFPS calls }
1001 1 / ApplicationProperties.LimitFPS -
1002 { how long I actually waited between _LimitFPS calls }
1003 TimerSeconds(NowTime, LastLimitFPSTime);
1004 { Don't do Sleep with too small values.
1005 It's better to have larger FPS values than limit,
1006 than to have them too small. }
1007 if TimeRemainingFloat > 0.001 then
1008 begin
1009 Sleep(Round(1000 * TimeRemainingFloat));
1010 LastLimitFPSTime := Timer;
1011 end else
1012 LastLimitFPSTime := NowTime;
1013 end;
1014 end;
1015
1016 var
1017 I: Integer;
1018 C: TCastleControl;
1019 begin
1020 { Call DoUpdate on all TCastleControl instances. }
1021 ApplicationProperties._Update;
1022 for I := ControlsList.Count - 1 downto 0 do
1023 begin
1024 C := ControlsList[I] as TCastleControl;
1025 if C.GLInitialized then
1026 C.DoUpdate;
1027 end;
1028 ApplicationProperties._UpdateEnd;
1029 DoLimitFPS;
1030 end;
1031
1032 class procedure TCastleControl.UpdatingEnable;
1033 begin
1034 inherited;
1035 {$ifdef CASTLE_CONTROL_UPDATE_TIMER}
1036 UpdatingTimer := TCustomTimer.Create(nil);
1037 UpdatingTimer.Interval := 1;
1038 UpdatingTimer.OnTimer := {$ifdef FPC}@{$endif} UpdatingTimerEvent;
1039 {$else}
1040 Application.AddOnIdleHandler({$ifdef FPC}@{$endif} UpdatingIdleEvent);
1041 {$endif}
1042 end;
1043
1044 class procedure TCastleControl.UpdatingDisable;
1045 begin
1046 {$ifdef CASTLE_CONTROL_UPDATE_TIMER}
1047 FreeAndNil(UpdatingTimer);
1048 {$else}
1049 Application.RemoveOnIdleHandler({$ifdef FPC}@{$endif} UpdatingIdleEvent);
1050 {$endif}
1051 inherited;
1052 end;
1053
1054 {$ifdef CASTLE_CONTROL_UPDATE_TIMER}
1055 class procedure TCastleControl.UpdatingTimerEvent(Sender: TObject);
1056 begin
1057 DoUpdateEverything;
1058 end;
1059 {$else}
1060 class procedure TCastleControl.UpdatingIdleEvent(Sender: TObject; var Done: Boolean);
1061 begin
1062 DoUpdateEverything;
1063 Done := false;
1064 end;
1065 {$endif}
1066
1067 procedure TCastleControl.SetAutoRedisplay(const Value: boolean);
1068 begin
1069 FAutoRedisplay := value;
1070 if Value then Invalidate;
1071 end;
1072
1073 function TCastleControl.MakeCurrent(SaveOldToStack: boolean): boolean;
1074 begin
1075 { This call makes no sense when OpenGL context is no longer available,
1076 which means Handle = 0.
1077 Inherited would make error - LOpenGLMakeCurrent in LCL would
1078 make "RaiseGDBException('LOpenGLSwapBuffers Handle=0');".
1079 For some reason, it may be reported as EDivByZero, "Division by zero".
1080
1081 Better to just exit with false. }
1082 if Handle = 0 then
1083 Exit(false);
1084
1085 Result := inherited MakeCurrent(SaveOldToStack);
1086
1087 RenderContext := Container.Context;
1088
1089 { React to context being created.
1090
1091 Note: Initially I wanted to detect context being created by overriding
1092 CreateHandle, instead of checking for it in every MakeCurrent.
1093
1094 Reasoning: looking at implementation of OpenGLContext,
1095 actual creating and destroying of OpenGL contexts
1096 (i.e. calls to LOpenGLCreateContext and LOpenGLDestroyContextInfo)
1097 is done within Create/DestroyHandle.
1098
1099 But this was wrong. Under GTK LOpenGLCreateContext
1100 only creates gtk_gl_area --- it doesn't *realize* it.
1101 Which means that actually LOpenGLCreateContext doesn't create
1102 OpenGL context. Looking at implementation of GLGtkGlxContext
1103 we see that only during MakeCurrent the widget is guaranteed
1104 to be realized.
1105 }
1106 if not GLInitialized then
1107 begin
1108 FGLInitialized := true;
1109
1110 GLInformationInitialize;
1111 // _GLContextEarlyOpen is not really necessary here now, but we call it for consistency
1112 ApplicationProperties._GLContextEarlyOpen;
1113 Inc(ControlsOpen);
1114 Container.EventOpen(ControlsOpen);
1115 Resize; // will call Container.EventResize
1116 Invalidate;
1117
1118 { When using Application.AddOnIdleHandler:
1119 Do not add it at design-time, to not block other idle handlers in Lazarus IDE.
1120
1121 When using TCustomTimer:
1122 It is OK to let it work at design-time too.
1123 And then we will have animations in Lazarus IDE in TCastleControl
1124 (e.g. if you load design with animated TCastleScene in TCastleControl.DesignUrl). }
1125
1126 if {$ifndef CASTLE_CONTROL_UPDATE_TIMER}
1127 (not (csDesigning in ComponentState)) and
1128 {$endif}
1129 (not UpdatingEnabled) then
1130 begin
1131 UpdatingEnabled := true;
1132 UpdatingEnable;
1133 end;
1134 end;
1135 end;
1136
1137 procedure TCastleControl.DestroyHandle;
1138 begin
1139 { React to context being destroyed. }
1140 if GLInitialized then
1141 begin
1142 Container.EventClose(ControlsOpen);
1143 Dec(ControlsOpen);
1144 FGLInitialized := false;
1145
1146 if UpdatingEnabled and (ControlsOpen = 0) then
1147 begin
1148 UpdatingEnabled := false;
1149 UpdatingDisable;
1150 end;
1151 end;
1152
1153 inherited DestroyHandle;
1154 end;
1155
1156 procedure TCastleControl.Resize;
1157 begin
1158 inherited;
1159
1160 { Call MakeCurrent here, to make sure CastleUIControls always get
1161 Resize with good GL context. }
1162 if GLInitialized and MakeCurrent then
1163 Container.EventResize;
1164 end;
1165
1166 procedure TCastleControl.Invalidate;
1167 begin
1168 Invalidated := true;
1169 inherited;
1170 end;
1171
1172 procedure TCastleControl.ReleaseAllKeysAndMouse;
1173
1174 { This does a subset of MouseUp implementation, only caring about updating CGE state now. }
1175 procedure CastleMouseUp(const MyButton: TCastleMouseButton);
1176 begin
1177 Container.MousePressed := Container.MousePressed - [MyButton];
1178 Container.EventRelease(InputMouseButton(MousePosition, MyButton, 0));
1179 end;
1180
1181 { This does a subset of KeyUp implementation, only caring about updating CGE state now. }
1182 procedure CastleKeyUp(const MyKey: TKey);
1183 var
1184 MyKeyString: String;
1185 begin
1186 { Do this before anything else, in particular before even Pressed.KeyUp below.
1187 This may call OnPress (which sets Pressed to true). }
1188 FKeyPressHandler.Flush;
1189
1190 Pressed.KeyUp(MyKey, MyKeyString);
1191
1192 if (MyKey <> keyNone) or (MyKeyString <> '') then
1193 Container.EventRelease(InputKey(MousePosition, MyKey, MyKeyString));
1194 end;
1195
1196 var
1197 Key: TKey;
1198 MouseButton: TCastleMouseButton;
1199 begin
1200 { This should also take care of releasing Characters. }
1201 for Key := Low(Key) to High(Key) do
1202 if Pressed[Key] then
1203 CastleKeyUp(Key);
1204
1205 for MouseButton := Low(MouseButton) to High(MouseButton) do
1206 if MouseButton in MousePressed then
1207 CastleMouseUp(MouseButton);
1208
1209 Container.MouseLookIgnoreNextMotion;
1210 end;
1211
1212 procedure TCastleControl.UpdateShiftState(const Shift: TShiftState);
1213 begin
1214 Pressed.Keys[keyShift] := ssShift in Shift;
1215 Pressed.Keys[keyAlt ] := ssAlt in Shift;
1216 Pressed.Keys[keyCtrl ] := ssCtrl in Shift;
1217 end;
1218
1219 procedure TCastleControl.KeyPressHandlerPress(Sender: TObject;
1220 const Event: TInputPressRelease);
1221 var
1222 NewEvent: TInputPressRelease;
1223 begin
1224 // Key or KeyString non-empty, our TLCLKeyPressHandler already checks it
1225 Assert((Event.Key <> keyNone) or (Event.KeyString <> ''));
1226
1227 NewEvent := Event;
1228 NewEvent.Position := MousePosition;
1229 NewEvent.KeyRepeated :=
1230 // Key already pressed
1231 ((NewEvent.Key = keyNone) or Pressed.Keys[NewEvent.Key]) and
1232 // KeyString already pressed
1233 ((NewEvent.KeyString = '') or Pressed.Strings[NewEvent.KeyString]);
1234
1235 { Note that Event has invalid position (TLCLKeyPressHandler always sends
1236 zero). So all the following code has to use NewEvent instead. }
1237
1238 Pressed.KeyDown(NewEvent.Key, NewEvent.KeyString);
1239
1240 Container.EventPress(NewEvent);
1241
1242 { The result of "Container.EventPress" (whether the key was handled)
1243 is for now not used anywhere.
1244 Passing it back to LCL is not possible, since we do not process keys
1245 directly in TCastleControl.KeyDown, we wait for a matching
1246 UTFKeyPress. }
1247 end;
1248
1249 procedure TCastleControl.KeyDown(var Key: Word; Shift: TShiftState);
1250 begin
1251 { Do this before EventPress
1252 (would be nice to also do it after Pressed.KeyDown inside
1253 TCastleControl.KeyPressHandlerPress, but ignore for now) }
1254 UpdateShiftState(Shift);
1255
1256 inherited KeyDown(Key, Shift); { LCL OnKeyDown before our callbacks }
1257
1258 FKeyPressHandler.KeyDown(Key, Shift);
1259
1260 { Do not change focus by arrow keys, this would break our handling of arrows
1261 over TCastleControl. We can prevent Lazarus from interpreting these
1262 keys as focus-changing (actually, Lazarus tells widget manager that these
1263 are already handled) by setting them to zero. }
1264 if (Key = VK_Down) or
1265 (Key = VK_Up) or
1266 (Key = VK_Right) or
1267 (Key = VK_Left) then
1268 Key := 0;
1269 end;
1270
1271 procedure TCastleControl.UTF8KeyPress(var UTF8Key: TUTF8Char);
1272 begin
1273 inherited UTF8KeyPress(UTF8Key); { LCL OnUTF8KeyPress before our callbacks }
1274 FKeyPressHandler.UTF8KeyPress(UTF8Key);
1275 end;
1276
1277 procedure TCastleControl.KeyUp(var Key: Word; Shift: TShiftState);
1278 var
1279 MyKey: TKey;
1280 MyKeyString: String;
1281 begin
1282 { Do this before anything else, in particular before even Pressed.KeyUp below.
1283 This may call OnPress (which sets Pressed to true). }
1284 FKeyPressHandler.BeforeKeyUp(Key, Shift);
1285
1286 MyKey := KeyToCastle(Key, Shift);
1287 if MyKey <> keyNone then
1288 Pressed.KeyUp(MyKey, MyKeyString);
1289
1290 UpdateShiftState(Shift); { do this after Pressed update above, and before EventRelease }
1291
1292 { Do not change focus by arrow keys, this breaks our handling of them.
1293 See KeyDown for more comments. }
1294 if (Key = VK_Down) or
1295 (Key = VK_Up) or
1296 (Key = VK_Right) or
1297 (Key = VK_Left) then
1298 Key := 0;
1299
1300 inherited KeyUp(Key, Shift); { LCL OnKeyUp before our callbacks }
1301
1302 if (MyKey <> keyNone) or (MyKeyString <> '') then
1303 if Container.EventRelease(InputKey(MousePosition, MyKey, MyKeyString)) then
1304 Key := 0; // handled
1305 end;
1306
1307 procedure TCastleControl.MouseDown(Button: Controls.TMouseButton;
1308 Shift: TShiftState; X, Y: Integer);
1309 var
1310 MyButton: TCastleMouseButton;
1311 begin
1312 if AutoFocus and not Focused then
1313 SetFocus;
1314
1315 FMousePosition := Vector2(X, Height - 1 - Y);
1316
1317 if MouseButtonToCastle(Button, MyButton) then
1318 Container.MousePressed := Container.MousePressed + [MyButton];
1319
1320 UpdateShiftState(Shift); { do this after Pressed update above, and before *Event }
1321
1322 inherited MouseDown(Button, Shift, X, Y); { LCL OnMouseDown before our callbacks }
1323
1324 if MouseButtonToCastle(Button, MyButton) then
1325 Container.EventPress(InputMouseButton(MousePosition, MyButton, 0,
1326 ModifiersDown(Container.Pressed)));
1327 end;
1328
1329 procedure TCastleControl.MouseUp(Button: Controls.TMouseButton;
1330 Shift: TShiftState; X, Y: Integer);
1331 var
1332 MyButton: TCastleMouseButton;
1333 begin
1334 FMousePosition := Vector2(X, Height - 1 - Y);
1335
1336 if MouseButtonToCastle(Button, MyButton) then
1337 Container.MousePressed := Container.MousePressed - [MyButton];
1338
1339 UpdateShiftState(Shift); { do this after Pressed update above, and before *Event }
1340
1341 inherited MouseUp(Button, Shift, X, Y); { LCL OnMouseUp before our callbacks }
1342
1343 if MouseButtonToCastle(Button, MyButton) then
1344 Container.EventRelease(InputMouseButton(MousePosition, MyButton, 0));
1345 end;
1346
1347 procedure TCastleControl.AggressiveUpdate;
1348 const
1349 MaxDesiredFPS = TCastleApplicationProperties.DefaultLimitFPS;
1350 var
1351 DesiredFPS: Single;
1352 begin
1353 if ApplicationProperties.LimitFPS <= 0 then
1354 DesiredFPS := MaxDesiredFPS
1355 else
1356 DesiredFPS := Min(MaxDesiredFPS, ApplicationProperties.LimitFPS);
1357 if TimerSeconds(Timer, Fps.UpdateStartTime) > 1 / DesiredFPS then
1358 begin
1359 DoUpdate;
1360 if Invalidated then Paint;
1361 end;
1362 end;
1363
1364 procedure TCastleControl.MouseMove(Shift: TShiftState; NewX, NewY: Integer);
1365 begin
1366 { check GLInitialized, because it seems it can be called before GL context
1367 is created (on Windows) or after it's destroyed (sometimes on Linux).
1368 We don't want to pass anything to Container in such case. }
1369
1370 if GLInitialized then
1371 begin
1372 Container.EventMotion(InputMotion(MousePosition,
1373 Vector2(NewX, Height - 1 - NewY), MousePressed, 0));
1374
1375 // change FMousePosition *after* EventMotion, callbacks may depend on it
1376 FMousePosition := Vector2(NewX, Height - 1 - NewY);
1377
1378 UpdateShiftState(Shift);
1379 AggressiveUpdate;
1380 end;
1381
1382 inherited MouseMove(Shift, NewX, NewY);
1383 end;
1384
1385 function TCastleControl.DoMouseWheel(Shift: TShiftState; WheelDelta: Integer;
1386 MousePos: TPoint): Boolean;
1387 begin
1388 Result := Container.EventPress(InputMouseWheel(MousePosition, WheelDelta/120, true,
1389 ModifiersDown(Container.Pressed)));
1390 AggressiveUpdate;
1391 if Result then Exit;
1392
1393 Result := inherited DoMouseWheel(Shift, WheelDelta, MousePos);
1394 end;
1395
1396 procedure TCastleControl.DoUpdate;
1397 begin
1398 if AutoRedisplay then Invalidate;
1399 FKeyPressHandler.Flush; // finish any pending key presses
1400
1401 { Update event also requires that proper OpenGL context is current.
1402
1403 This matters because OpenGL resources may be used durign update,
1404 e.g. TCastleScene.Update will update auto-generated textures,
1405 doing e.g. TGLGeneratedCubeMapTextureNode.Update.
1406 This should run in proper OpenGL context.
1407 Esp. as not all resources must be shared between contexts:
1408 FBO are not shared in new OpenGL versions, see
1409 https://stackoverflow.com/questions/4385655/is-it-possible-to-share-an-opengl-framebuffer-object-between-contexts-threads
1410
1411 Testcase: open examples/mobile/simple_3d_demo/ in editor,
1412 open main design,
1413 click on previews with GeneratedCubeMap like castle_with_lights_and_camera.wrl .
1414 Without this fix, we'll have an OpenGL error.
1415
1416 Doing MakeCurrent here is consistent with TCastleWindow.DoUpdate . }
1417 MakeCurrent;
1418 Container.EventUpdate;
1419 end;
1420
1421 procedure TCastleControl.DoExit;
1422 begin
1423 inherited;
1424 ReleaseAllKeysAndMouse;
1425 end;
1426
1427 procedure TCastleControl.Paint;
1428 begin
1429 { Note that we don't call here inherited, instead doing everything ourselves. }
1430 if MakeCurrent then
1431 begin
1432 { clear Invalidated before rendering, so that calling Invalidate in OnRender works }
1433 Invalidated := false;
1434 Container.EventBeforeRender;
1435 Fps.InternalRenderBegin;
1436 try
1437 Container.EventRender;
1438 DoOnPaint; // call OnPaint, like it would be a top-most TCastleUserInterface
1439 if GLVersion.BuggySwapNonStandardViewport then
1440 RenderContext.Viewport := Rect;
1441 SwapBuffers;
1442 // it seems calling Invalidate from Paint doesn't work, so we'll
1443 // have to do it elsewhere
1444 // if AutoRedisplay then Invalidate;
1445 finally Fps.InternalRenderEnd end;
1446 end;
1447 end;
1448
1449 function TCastleControl.SaveScreenBuffer: TColorBuffer;
1450 begin
1451 if DoubleBuffered then
1452 Result := cbBack else
1453 Result := cbFront;
1454 end;
1455
1456 procedure TCastleControl.SaveScreen(const Url: String);
1457 begin
1458 Container.SaveScreen(Url);
1459 end;
1460
1461 function TCastleControl.SaveScreen: TRGBImage;
1462 begin
1463 Result := Container.SaveScreen;
1464 end;
1465
1466 function TCastleControl.SaveScreen(const SaveRect: TRectangle): TRGBImage;
1467 begin
1468 Result := Container.SaveScreen(SaveRect);
1469 end;
1470
1471 procedure TCastleControl.SetMousePosition(const Value: TVector2);
1472 var
1473 NewCursorPos: TPoint;
1474 begin
1475 NewCursorPos := ControlToScreen(
1476 Point(Floor(Value[0]), Height - 1 - Floor(Value[1])));
1477
1478 { Do not set Mouse.CursorPos to the same value, to make sure we don't cause
1479 unnecessary OnMotion on some systems while actual MousePosition didn't change. }
1480 if (NewCursorPos.x <> Mouse.CursorPos.x) or (NewCursorPos.y <> Mouse.CursorPos.y) then
1481 Mouse.CursorPos := NewCursorPos;
1482 end;
1483
1484 function TCastleControl.MousePressed: TCastleMouseButtons;
1485 begin
1486 Result := Container.MousePressed;
1487 end;
1488
1489 function TCastleControl.Pressed: TKeysPressed;
1490 begin
1491 Result := Container.Pressed;
1492 end;
1493
1494 function TCastleControl.Fps: TFramesPerSecond;
1495 begin
1496 Result := Container.Fps;
1497 end;
1498
1499 function TCastleControl.Rect: TRectangle;
1500 begin
1501 Result := Container.PixelsRect;
1502 end;
1503
1504 function TCastleControl.DesignedComponent(const ComponentName: String
1505 ): TComponent;
1506 begin
1507 Result := Container.DesignedComponent(ComponentName);
1508 end;
1509
1510 function TCastleControl.Controls: TInternalChildrenControls;
1511 begin
1512 Result := Container.Controls;
1513 end;
1514
1515 class function TCastleControl.GetMainContainer: TCastleContainer;
1516 begin
1517 {$warnings off} // using MainControl just to keep it working
1518 if MainControl <> nil then
1519 Result := MainControl.Container
1520 else
1521 Result := nil;
1522 {$warnings on}
1523 end;
1524
1525 function TCastleControl.GetDesignUrl: String;
1526 begin
1527 Result := Container.DesignUrl;
1528 end;
1529
1530 procedure TCastleControl.SetDesignUrl(const Value: String);
1531 begin
1532 Container.DesignUrl := Value;
1533 end;
1534
1535 { TLCLClipboard ----------------------------------------------------------- }
1536
1537 type
1538 TLCLClipboard = class(TCastleClipboard)
1539 protected
1540 function GetAsText: String; override;
1541 procedure SetAsText(const Value: String); override;
1542 end;
1543
1544 function TLCLClipboard.GetAsText: String;
1545 begin
1546 Result := UTF8ToSys(Clipbrd.Clipboard.AsText);
1547 end;
1548
1549 procedure TLCLClipboard.SetAsText(const Value: String);
1550 begin
1551 Clipbrd.Clipboard.AsText := SysToUTF8(Value);
1552 end;
1553
1554 { initialization / finalization ---------------------------------------------- }
1555
1556 procedure InitializeClipboard;
1557 begin
1558 // make the Clipboard in CastleControls integrated with LCL clipboard
1559 RegisterClipboard(TLCLClipboard.Create);
1560 end;
1561
1562 initialization
1563 ControlsList := TComponentList.Create(false);
1564 InitializeClipboard;
1565 OnMainContainer := @TCastleControl(nil).GetMainContainer;
1566 finalization
1567 OnMainContainer := nil;
1568 FreeAndNil(ControlsList);
1569 end.