Repository navigation
Expand file tree
/
Copy pathApus.Engine.SDLplatform.pas
More file actions
1241 lines (1144 loc) · 40.2 KB
/
Copy pathApus.Engine.SDLplatform.pas
File metadata and controls
1241 lines (1144 loc) · 40.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Windows-specific functions used by Game object
//
// Copyright (C) 2020 Ivan Polyacov, Apus Software (ivan@apus-software.com)
// This file is licensed under the terms of BSD-3 license (see license.txt)
// This file is a part of the Apus Game Engine (http://apus-software.com/engine/)
{$I defines.inc}
unit Apus.Engine.SDLplatform;
interface
uses Types, sdl2, Apus.Core, Apus.Engine.API, Apus.Engine.OpenGL
{$IFDEF GLES},dglOpenGLES{$ENDIF};
type
TSDLEvents=array of TSDL_Event;
{ TSDLGLWindow }
TSDLGLWindow=class(TWindow)
constructor Create(aWnd:PSDL_Window;const windowName:String8);
procedure Close; override;
procedure Terminate; override;
procedure Configure(params:TGameSettings); override;
procedure Show(show:boolean); override;
function GetHandle:THandle; override;
procedure GetSize(out width,height:integer); override;
procedure MoveTo(x,y:integer;width:integer=0;height:integer=0); override;
procedure SetCaption(text:string); override;
procedure Minimize; override;
procedure Maximize; override;
procedure Restore; override;
procedure FlashWindow(count:integer); override;
procedure ProcessMessages; override;
function IsTerminated:boolean; override;
procedure ScreenToClient(var p:TPoint); override;
procedure ClientToScreen(var p:TPoint); override;
procedure SampleOSPointer; override;
procedure InitGraph; override;
procedure InitGraphShared(primary:TWindow;mainContextReleased:boolean=false); override;
procedure DoneGraph; override;
procedure ReleaseGraphContext; override;
procedure ActivateGraphContext; override;
procedure PresentFrame; override;
function SetVSync(divider:integer):boolean; override;
private
wnd:PSDL_Window;
ctx:TSDL_GLContext;
contextVAO:cardinal; // per-context VAO for shared secondary window
terminated:boolean;
reportedDPI:integer; // last DPI posted by CheckDPI, 0 until the first one
graphInfo:TOpenGLContextDesc;
sdlID:cardinal; // SDL window ID: events carry it
events:TSDLEvents; // events routed to this window, guarded by sdlEvents
eventCount:integer;
dropList:Strings8; // files of the drop in progress (SDL_DROPBEGIN..SDL_DROPCOMPLETE)
customFrame:boolean; // the window is borderless: the app draws the frame
configured:boolean; // Configure was called: the startup state is applied
maximizePending:boolean; // startup maximized state: applied on the first switch to dmWindow
limitMin,limitMax:TSize; // size limits passed to SDL, window coordinates, 0 - not set
procedure UpdateFrame; // border on/off for the frame policy and the window state
procedure UpdateSizeLimits; // pass TWindow.sizeLimits to SDL when they change
function FrameHitTestAt(const p:TSDL_Point):TSDL_HitTestResult;
procedure AddEvent(const event:TSDL_Event);
procedure HandleEvent(const event:TSDL_Event);
function GetDPI:integer; // DPI of the display this window is currently on
procedure CheckDPI; // re-query it and post a change
function CreateOpenGLContext(var graph:TOpenGLContextDesc;shareWithCurrent:boolean=false):UIntPtr;
end;
{ TSDLPlatform }
TSDLPlatform=class(TInterfacedObject,ISystemPlatform)
constructor Create;
function GetPlatformName:string;
function CanChangeSettings:boolean;
procedure GetScreenSize(out width,height:integer);
procedure GetRealScreenSize(out width,height:integer);
function GetScreenDPI:integer;
function GetMousePos:TPoint; // Get mouse position on screen
procedure SetMousePos(scrX,scrY:integer); // Move mouse cursor (screen coordinates)
function GetSystemCursor(cursorId:integer):THandle;
function LoadCursor(fname:string):THandle;
procedure SetCursor(cur:THandle);
procedure FreeCursor(cur:THandle);
function GetShiftKeysState:cardinal;
function CreateWindow(const name:String8;title:string):TWindow;
end;
implementation
uses {$IFDEF MSWINDOWS}Windows, MultiMon,{$ENDIF}
SysUtils, Apus.Log, Apus.Threads, Apus.Files, Apus.Strings, Apus.EventMan, Apus.Engine.Game, Apus.Images,
Apus.GfxFormats, Apus.Engine.Controller, Apus.Engine.Types, Apus.Engine.Window
{$IFDEF GLDESKTOP},dglOpenGL{$ENDIF}; // GLDESKTOP, not OPENGL: under GLES the desktop unit would shadow dglOpenGLES' loader procs
type
TSDLController=record
joystick:PSDL_Joystick;
controller:PSDL_GameController;
end;
const
glcsReady=0;
glcsReleaseRequested=1;
glcsReleased=2;
var
savedLogHandler:TSDL_LogOutputFunction;
glShareState:integer=glcsReady;
SDLcontrollers:array[0..high(controllers)] of TSDLController;
// SDL has one event queue for all windows, and every window's thread polls it. Polled
// events are routed to their window's queue under this lock, so each window sees its
// events in SDL order whichever thread polled them. A leaf lock: nothing is entered inside.
sdlEvents:TLock;
sdlWindows:array of TSDLGLWindow; // live windows, guarded by sdlEvents
procedure InitJoystick(idx:integer);
begin
ASSERT(idx in [0..high(controllers)]);
if idx>high(controllers) then begin
Log.Msg('SDL joystick %d not supported',[idx]);
exit;
end;
Log.Msg('Init SDL joystick %d',[idx]);
Mem.Clear(controllers[idx],sizeof(controllers[idx]));
with SDLcontrollers[idx] do begin
joystick:=SDL_JoystickOpen(idx);
if joystick<>nil then with controllers[idx] do begin
controllerType:=gcJoystick;
numAxes:=SDL_JoystickNumAxes(joystick);
numButtons:=SDL_JoystickNumButtons(joystick);
name:=SDL_JoystickName(joystick);
Log.Msg('SDL joystick: "%s" axes:%d, buttons:%d',[name,numAxes,numButtons]);
end;
if SDL_IsGameController(idx)=SDL_TRUE then begin
Log.Msg('SDL: joystick %d is controller',[idx]);
controller:=SDL_GameControllerOpen(idx);
if controller<>nil then begin
controllers[idx].controllerType:=gcGamepad;
end;
end;
end;
controllers[idx].index:=idx;
end;
procedure InitControllers;
var
i,n:integer;
begin
n:=SDL_NumJoysticks;
if n<=0 then exit;
for i:=0 to Clamp(n-1,0,3) do begin
InitJoystick(i);
end;
end;
{ TSDLGLWindow }
constructor TSDLGLWindow.Create(aWnd:PSDL_Window;const windowName:String8);
begin
inherited Create(windowName);
wnd:=aWnd;
ctx:=nil;
contextVAO:=0;
terminated:=false;
sdlID:=SDL_GetWindowID(wnd);
sdlEvents.Enter;
try
SetLength(sdlWindows,length(sdlWindows)+1);
sdlWindows[high(sdlWindows)]:=self;
finally
sdlEvents.Leave;
end;
end;
{ TSDLPlatform }
function TSDLPlatform.CanChangeSettings:boolean;
begin
result:=true;
end;
procedure TSDLGLWindow.ClientToScreen(var p:TPoint);
var
x,y:integer;
begin
SDL_GetWindowPosition(wnd,@x,@y);
inc(p.x,x);
inc(p.y,y);
end;
procedure TSDLGLWindow.ScreenToClient(var p:TPoint);
var
x,y:integer;
begin
SDL_GetWindowPosition(wnd,@x,@y);
dec(p.x,x);
dec(p.y,y);
end;
procedure TSDLGLWindow.SampleOSPointer;
var
pnt:TPoint;
logicalWidth,logicalHeight:integer;
begin
// TODO: match WindowsPlatform.SampleOSPointer (deferred until SDL-on-Windows, see
// Work/engine_work_ahead.md P1):
// 1) gate on SDL_GetMouseFocus<>wnd → off-screen sentinel (clears stale hover when
// our window is covered, fixes cross-read between app windows);
// 2) while a button is held, report raw continuous coords (SDL_CaptureMouse /
// relative mode) so a camera-drag does not jump to the sentinel off-window.
SDL_GetMouseState(@pnt.x,@pnt.y); // already client-relative to focused window
SDL_GetWindowSize(wnd,@logicalWidth,@logicalHeight);
if (pnt.x<0) or (pnt.y<0) or
(pnt.x>=logicalWidth) or (pnt.y>=logicalHeight) then begin
SetPointerOutside;
exit;
end;
if (logicalWidth>0) and (logicalHeight>0) then begin
pnt.x:=round(pnt.x*clientWidth/logicalWidth);
pnt.y:=round(pnt.y*clientHeight/logicalHeight);
end;
SetPointer(pnt);
end;
procedure TSDLGLWindow.Close;
var
i:integer;
begin
sdlEvents.Enter; // stop routing events here
try
for i:=high(sdlWindows) downto 0 do
if sdlWindows[i]=self then begin
sdlWindows[i]:=sdlWindows[high(sdlWindows)];
SetLength(sdlWindows,high(sdlWindows));
end;
events:=nil;
eventCount:=0;
finally
sdlEvents.Leave;
end;
SDL_DestroyWindow(wnd);
wnd:=nil;
end;
procedure TSDLGLWindow.Terminate;
begin
terminated:=true;
if self=mainWindow then Signal('Engine\Cmd\Exit',0);
end;
procedure TSDLGLWindow.FlashWindow(count:integer);
begin
end;
function TSDLPlatform.GetMousePos:TPoint;
begin
SDL_GetGlobalMouseState(@result.X,@result.Y);
end;
procedure TSDLPlatform.SetMousePos(scrX,scrY:integer);
begin
SDL_WarpMouseGlobal(scrX,scrY);
end;
function TSDLPlatform.GetPlatformName:string;
begin
result:='spSDL';
end;
// Physical DPI of a display. Some backends (a few X11/Wayland setups) never know it -
// 96 keeps the surface model on the unscaled ladder instead of guessing.
function DisplayDPI(displayIndex:integer):integer;
var
ddpi:single;
begin
if SDL_GetDisplayDPI(displayIndex,@ddpi,nil,nil)<>0 then begin
Log.Force('SDL: DPI query failed for display %d: %s. Assume 96 DPI',[displayIndex,SDL_GetError]);
exit(96);
end;
result:=round(ddpi);
end;
// The DPI of the primary display: asked before any window exists, to size the first one.
// Once a window is up, its own display is what matters - see TSDLGLWindow.GetDPI.
function TSDLPlatform.GetScreenDPI:integer;
begin
result:=DisplayDPI(0);
end;
procedure TSDLPlatform.GetScreenSize(out width, height: integer);
var
mode:TSDL_DisplayMode;
begin
SDL_GetDesktopDisplayMode(0,@mode);
width:=mode.w;
height:=mode.h;
end;
procedure TSDLPlatform.GetRealScreenSize(out width,height:integer);
begin
// not possible to query before window creation
width:=0;
height:=0;
end;
function TSDLPlatform.GetShiftKeysState: cardinal;
var
keys:TSDL_KeyMod;
begin
result:=0;
keys:=SDL_GetModState;
if keys and KMOD_SHIFT>0 then result:=result or sscShift;
if keys and KMOD_CTRL>0 then result:=result or sscCtrl;
if keys and KMOD_ALT>0 then result:=result or sscAlt;
if keys and KMOD_GUI>0 then result:=result or sscWin;
if keys and KMOD_RSHIFT>0 then result:=result or sscRShift;
if keys and KMOD_RCTRL>0 then result:=result or sscRCtrl;
if keys and KMOD_RALT>0 then result:=result or sscRAlt;
if keys and KMOD_RGUI>0 then result:=result or sscRWin;
end;
function TSDLPlatform.GetSystemCursor(cursorId: integer): THandle;
var
cur:integer; // not WORD because of Delphi calling convention issue
begin
case cursorID of
Apus.Engine.API.CursorID.Default:cur:=SDL_SYSTEM_CURSOR_ARROW;
Apus.Engine.API.CursorID.Link:cur:=SDL_SYSTEM_CURSOR_HAND;
Apus.Engine.API.CursorID.Wait:cur:=SDL_SYSTEM_CURSOR_WAIT;
Apus.Engine.API.CursorID.Input:cur:=SDL_SYSTEM_CURSOR_IBEAM;
Apus.Engine.API.CursorID.Help:cur:=SDL_SYSTEM_CURSOR_WAITARROW;
Apus.Engine.API.CursorID.ResizeH:cur:=SDL_SYSTEM_CURSOR_SIZENS;
Apus.Engine.API.CursorID.ResizeW:cur:=SDL_SYSTEM_CURSOR_SIZEWE;
Apus.Engine.API.CursorID.ResizeHW:cur:=SDL_SYSTEM_CURSOR_SIZEALL;
Apus.Engine.API.CursorID.ResizeNWSE:cur:=SDL_SYSTEM_CURSOR_SIZENWSE;
Apus.Engine.API.CursorID.ResizeNESW:cur:=SDL_SYSTEM_CURSOR_SIZENESW;
Apus.Engine.API.CursorID.Cross:cur:=SDL_SYSTEM_CURSOR_CROSSHAIR;
end;
result:=THandle(SDL_CreateSystemCursor(cur));
if result=0 then
Log.Msg('Error - SDL_CSC failed: '+SDL_GetError);
end;
function TSDLPlatform.LoadCursor(fname:string):THandle;
var
surface:PSDL_Surface;
data:ByteArray;
image:TRawImage;
hotX,hotY:integer;
cursor:PSDL_Cursor;
begin
try
data:=Files.LoadAsBytes(Files.FixName(fname));
image:=nil;
LoadCUR(data,image,hotX,hotY);
image.Lock;
surface:=SDL_CreateRGBSurfaceFrom(image.data,image.width,image.height,32,image.pitch,
$FF0000,$FF00,$FF,$FF000000);
if surface=nil then raise EWarning.Create('Surface creation failed: '+SDL_GetError);
cursor:=SDL_CreateColorCursor(surface,hotX,hotY);
SDL_FreeSurface(surface);
image.Unlock;
result:=THandle(cursor);
except
on e:Exception do
raise EWarning.Create('Failed to load cursor from %s: %s',[fname,ExceptionMsg(e)]);
end;
end;
procedure TSDLPlatform.SetCursor(cur:THandle);
begin
SDL_SetCursor(pointer(cur));
end;
procedure TSDLPlatform.FreeCursor(cur:THandle);
begin
SDL_FreeCursor(pointer(cur));
end;
function TSDLGLWindow.GetHandle:THandle;
begin
if wnd=nil then exit(0);
result:=THandle(SDL_GetWindowID(wnd));
end;
procedure TSDLGLWindow.GetSize(out width,height:integer);
begin
if wnd=nil then begin
width:=0; height:=0;
end else
SDL_GL_GetDrawableSize(wnd,@width,@height);
end;
function TSDLGLWindow.GetDPI:integer;
var
displayIndex:integer;
begin
if wnd=nil then exit(96);
displayIndex:=SDL_GetWindowDisplayIndex(wnd);
if displayIndex<0 then begin
Log.Warn('SDL: cannot tell which display window "%s" is on: %s',[name,SDL_GetError]);
exit(96);
end;
result:=DisplayDPI(displayIndex);
end;
// Re-query the display DPI and post it if it changed - the SDL counterpart of
// WM_DPICHANGED (see Apus.Engine.WindowsPlatform). SDL 2 has no single reliable event
// for this, so every event that might mean a new DPI is funnelled here; reportedDPI
// filters out the duplicates, which surface.dpi cannot do because it lags a frame behind.
procedure TSDLGLWindow.CheckDPI;
var
dpi:integer;
begin
dpi:=GetDPI;
if dpi=reportedDPI then exit;
reportedDPI:=dpi;
Log.Msg('SDL: window "%s" is on display %d at %d DPI',
[name,SDL_GetWindowDisplayIndex(wnd),dpi]);
RequestDPI(dpi);
end;
procedure MyLogHandler(userdata: Pointer; category: TSDL_LogCategory; priority: TSDL_LogPriority; const msg: PAnsiChar); cdecl;
begin
if priority>=SDL_LOG_PRIORITY_ERROR then
Log.Force('SDL: '+msg)
else
Log.Msg('SDL: '+msg);
if Assigned(savedLogHandler) then
savedLogHandler(userData,category,priority,msg);
end;
constructor TSDLPlatform.Create;
var
plName:AnsiString;
ver:TSDL_Version;
begin
{$IFDEF MSWINDOWS}
SetEnvironmentVariable('SDL_AUDIODRIVER','winmm');
{$ENDIF}
// closing the last window is a close request (TWindow.RequestClose), not SDL_QUIT on top of it
SDL_SetHint(SDL_HINT_QUIT_ON_LAST_WINDOW_CLOSE,'0');
if SDL_Init(SDL_INIT_EVERYTHING)<>0 then
raise EError.Create('SDL init error: '+SDL_GetError);
SDL_EventState(SDL_DROPFILE,SDL_ENABLE); // on by default in SDL2, but windows accept drops only while it is on
plName:=SDL_GetPlatform;
SDL_GetVersion(@ver);
SDL_LogGetOutputFunction(@savedLogHandler,nil);
SDL_LogSetOutputFunction(MyLogHandler,nil);
Log.Msg('SDL Platform Initialized. System: %s, runtime %d.%d.%d, headers %d.%d.%d',
[plName,ver.major,ver.minor,ver.patch,SDL_MAJOR_VERSION,SDL_MINOR_VERSION,SDL_PATCHLEVEL]);
InitControllers;
end;
procedure ApplyOpenGLContextAttributes(const graph:TOpenGLContextDesc;shareWithCurrent:boolean);
var
major,minor,profileMask,flags:integer;
begin
major:=graph.minMajor;
minor:=graph.minMinor;
{$IFDEF GLES}
// ES 3.0 baseline: do NOT apply the desktop 3.3 minimum clamp.
profileMask:=SDL_GL_CONTEXT_PROFILE_ES;
major:=3;
minor:=0;
{$ELSE}
if (major<3) or ((major=3) and (minor<3)) then begin
major:=3;
minor:=3;
end;
profileMask:=SDL_GL_CONTEXT_PROFILE_COMPATIBILITY;
if graph.profile=oglpCore then
profileMask:=SDL_GL_CONTEXT_PROFILE_CORE;
{$ENDIF}
flags:=0;
if graph.debugContext then flags:=flags or SDL_GL_CONTEXT_DEBUG_FLAG;
if graph.forwardCompatible then flags:=flags or SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG;
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION,major);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION,minor);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,profileMask);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS,flags);
SDL_GL_SetAttribute(SDL_GL_SHARE_WITH_CURRENT_CONTEXT,byte(shareWithCurrent));
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE,24); // SDL default is 16
end;
function TSDLPlatform.CreateWindow(const name:String8;title:string):TWindow;
var
ust:UTF8String;
localWindow:PSDL_Window;
begin
Log.Msg('CreateWindow: %s (%s)',[name,title]);
ApplyOpenGLContextAttributes(oglContextTemplate,false);
ust:=title;
// NB: SDL_WINDOWS_DPI_SCALING is deliberately left off. It would make SDL express
// window sizes in logical points, while the engine already scales the requested size
// by deviceScale itself (TGameApplication.SetupGameSettings) - the two would fight.
localWindow:=SDL_CreateWindow(PAnsiChar(ust),SDL_WINDOWPOS_UNDEFINED,SDL_WINDOWPOS_UNDEFINED,100,100,
SDL_WINDOW_OPENGL+SDL_WINDOW_HIDDEN+SDL_WINDOW_ALLOW_HIGHDPI{+SDL_WINDOW_RESIZABLE});
if localWindow=nil then
raise EError.Create('SDL window creation failed: '+SDL_GetError);
result:=TSDLGLWindow.Create(localWindow,name);
end;
function PackWords(p1,p2:integer):TTag;
begin
result:=TTag((p1 and $FFFF)+(p2 and $FFFF) shl 16);
end;
function GetMouseButtonNum(btn:integer):integer;
begin
case btn of
SDL_BUTTON_LEFT:exit(1);
SDL_BUTTON_RIGHT:exit(2);
SDL_BUTTON_MIDDLE:exit(3);
end;
result:=0;
end;
// TKey of a key event. Letters and digits follow the layout, as Windows VK codes do (a
// letter of a non-Latin layout gives the Latin letter of its key, as on Windows); the
// other keys - the key at the position on the US layout.
function KeyFromSDL(sym,scancode:integer):TKey;
begin
case sym of
ord('a')..ord('z'):result:=TKey(sym-32);
ord('0')..ord('9'):result:=TKey(sym);
else
result:=Scan.ToKey(scancode);
end;
end;
// Route an event: target is its window, nil if the event is not window-specific; false
// if it names a window that is not ours (any more). Call under sdlEvents.
function FindEventWindow(const event:TSDL_Event;out target:TSDLGLWindow):boolean;
var
id:cardinal;
i:integer;
begin
target:=nil;
case event.type_ of
SDL_WINDOWEVENT:id:=event.window.windowID;
SDL_MOUSEBUTTONDOWN,SDL_MOUSEBUTTONUP:id:=event.button.windowID;
SDL_MOUSEWHEEL:id:=event.wheel.windowID;
SDL_KEYDOWN,SDL_KEYUP:id:=event.key.windowID;
SDL_TEXTINPUT:id:=event.text.windowID;
SDL_DROPFILE..SDL_DROPCOMPLETE:id:=event.drop.windowID;
SDL_QUITEV:begin // the app quits: the main window decides (TWindow.RequestClose)
if mainWindow is TSDLGLWindow then target:=TSDLGLWindow(mainWindow);
exit(true);
end;
else exit(true);
end;
if id=0 then exit(true); // e.g. a key without a focused window
for i:=0 to high(sdlWindows) do
if sdlWindows[i].sdlID=id then begin
target:=sdlWindows[i];
exit(true);
end;
result:=false;
end;
procedure ProcessControllerEvent(event:TSDL_Event);
var
n,axis,button:integer;
cButton:TConButtonType;
tag:TTag;
function ValidN:boolean;
begin
result:=(n>=0) and (n<=high(controllers));
end;
begin
case event.type_ of
SDL_JOYDEVICEADDED:InitJoystick(event.jdevice.which);
SDL_JOYDEVICEREMOVED:begin
n:=event.jdevice.which;
if not ValidN then exit;
Log.Msg('SDL: delete controller %d',[n]);
controllers[n].controllerType:=gcUnplugged;
with SDLcontrollers[n] do begin
if controller<>nil then begin
SDL_GameControllerClose(controller);
controller:=nil;
end;
if joystick<>nil then begin
SDL_JoystickClose(joystick);
joystick:=nil;
end;
end;
end;
SDL_JOYAXISMOTION:begin
n:=event.jaxis.which;
if not ValidN then exit;
axis:=event.jaxis.axis;
if axis in [0..7] then
controllers[n].axes[TConAxisType(axis)]:=Clamp(event.jaxis.value/32767,-1,1);
end;
SDL_JOYBUTTONDOWN,SDL_JOYBUTTONUP:begin
n:=event.jbutton.which;
if not ValidN then exit;
button:=event.jbutton.button;
if button in [0..15] then begin
tag:=PackTag(button,n,0,0);
if event.type_=SDL_JOYBUTTONDOWN then begin
Bits.SetBit(controllers[n].buttons,button,true);
Signal('JOY\BTNDOWN',tag);
end else begin
Bits.SetBit(controllers[n].buttons,button,false);
Signal('JOY\BTNUP',tag);
end;
end;
end;
SDL_CONTROLLERAXISMOTION:begin
//event.caxis.which
end;
SDL_CONTROLLERBUTTONDOWN,SDL_CONTROLLERBUTTONUP:begin
n:=event.cbutton.which;
if not ValidN then exit;
case event.cbutton.button of
SDL_CONTROLLER_BUTTON_A: cButton:=btButtonA;
SDL_CONTROLLER_BUTTON_B: cButton:=btButtonB;
SDL_CONTROLLER_BUTTON_X: cButton:=btButtonX;
SDL_CONTROLLER_BUTTON_Y: cButton:=btButtonY;
SDL_CONTROLLER_BUTTON_BACK: cButton:=btButtonBack;
SDL_CONTROLLER_BUTTON_GUIDE: cButton:=btButtonGuide;
SDL_CONTROLLER_BUTTON_START: cButton:=btButtonStart;
SDL_CONTROLLER_BUTTON_DPAD_UP: cButton:=btButtonDPadUp;
SDL_CONTROLLER_BUTTON_DPAD_DOWN: cButton:=btButtonDPadDown;
SDL_CONTROLLER_BUTTON_DPAD_LEFT: cButton:=btButtonDPadLeft;
SDL_CONTROLLER_BUTTON_DPAD_RIGHT: cButton:=btButtonDPadRight;
else cButton:=btButton0;
end;
if cButton<btButtonA then exit;
// Tag: byte0 = button, byte1 = controller
tag:=PackTag(ord(cButton),n,0,0);
if event.type_=SDL_CONTROLLERBUTTONDOWN then begin
Bits.SetBit(controllers[n].buttons,ord(cButton),true);
Signal('GAMEPAD\BTNDOWN\'+Apus.Engine.Controller.GetButtonName(cButton),tag);
end else begin
Bits.SetBit(controllers[n].buttons,ord(cButton),false);
Signal('GAMEPAD\BTNUP\'+Apus.Engine.Controller.GetButtonName(cButton),tag);
end;
end;
end;
end;
procedure TSDLGLWindow.AddEvent(const event:TSDL_Event);
begin
if eventCount>=length(events) then SetLength(events,eventCount*2+16);
events[eventCount]:=event;
inc(eventCount);
end;
// Poll the shared SDL queue, route the events, then handle the ones of this window
// (and the ones of no window). Events polled by another window's thread are handled
// here at the latest on the next frame.
procedure TSDLGLWindow.ProcessMessages;
var
event:TSDL_Event;
target:TSDLGLWindow;
list:TSDLEvents;
i,count:integer;
begin
sdlEvents.Enter;
try
while SDL_PollEvent(@event)<>0 do begin
if not FindEventWindow(event,target) then begin
if event.type_=SDL_WINDOWEVENT then continue; // a closed window: drop
target:=self; // input with a stale window ID: as before routing existed
end;
if target=nil then target:=self;
target.AddEvent(event);
end;
list:=events;
count:=eventCount;
events:=nil;
eventCount:=0;
finally
sdlEvents.Leave;
end;
for i:=0 to count-1 do
HandleEvent(list[i]);
UpdateSizeLimits;
end;
// Handle an event routed to this window, in this window's thread
procedure TSDLGLWindow.HandleEvent(const event:TSDL_Event);
var
ust:String8;
wst:String16;
i,len,w,h:integer;
mbtn:integer;
begin
if game=nil then exit;
case event.type_ of
SDL_WINDOWEVENT:begin
case event.window.event of
SDL_WINDOWEVENT_FOCUS_GAINED:;
// a drag does not survive switching to another window (SDL 2.0.22+ captures the
// pointer while a button is held, so a release outside still comes), held keys are
// released (SDL releases them too: the second release is dropped)
SDL_WINDOWEVENT_FOCUS_LOST:begin
PlatformCancelGesture;
PlatformReleaseKeys;
end;
SDL_WINDOWEVENT_HIDDEN:begin
PlatformCancelGesture;
PlatformReleaseKeys;
Log.Msg('Window hidden');
Signal('ENGINE\SETACTIVE',0);
Signal('ENGINE\WINDOW\HIDDEN');
end;
SDL_WINDOWEVENT_SHOWN:begin
Log.Msg('Window shown');
Signal('ENGINE\SETACTIVE',1);
Signal('ENGINE\WINDOW\SHOWN');
end;
SDL_WINDOWEVENT_MINIMIZED:begin
PlatformCancelGesture;
PlatformReleaseKeys;
Log.Msg('Window minimized');
Signal('ENGINE\SETACTIVE',0);
PlatformStateChanged(TWindowState.Minimized);
end;
SDL_WINDOWEVENT_RESTORED:begin
Log.Msg('Window restored');
Signal('ENGINE\SETACTIVE',1);
PlatformStateChanged(TWindowState.Normal);
UpdateFrame;
end;
SDL_WINDOWEVENT_MAXIMIZED:begin
Log.Msg('Window maximized');
PlatformStateChanged(TWindowState.Maximized);
UpdateFrame;
end;
SDL_WINDOWEVENT_CLOSE:RequestClose;
// RESIZED covers user/window-manager resizing, SIZE_CHANGED also covers
// programmatic ones (SDL_SetWindowSize) - both just post the request,
// the window's own thread applies it at the start of its next frame.
SDL_WINDOWEVENT_RESIZED,SDL_WINDOWEVENT_SIZE_CHANGED:begin
GetSize(w,h);
RequestResize(w,h);
CheckDPI; // the display scale may have changed under a still window
end;
// The window may have landed on a display of a different DPI. DISPLAY_CHANGED is
// the precise event (SDL 2.0.18+), MOVED the fallback for older runtimes; MOVED
// also arrives per dragged pixel, hence the filtering inside CheckDPI.
SDL_WINDOWEVENT_MOVED,SDL_WINDOWEVENT_DISPLAY_CHANGED:CheckDPI;
end;
end;
// SDL_MOUSEMOTION intentionally not handled here:
// mouse position is sampled once per frame via TWindow.SamplePointer,
// which avoids OS-rate event flood on high-polling-rate mice.
SDL_MOUSEBUTTONDOWN:begin
if not game.GetSettings.showSystemCursor then systemPlatform.SetCursor(0);
mbtn:=GetMouseButtonNum(event.button.button);
// signals MOUSE\BTNDOWN, samples the pointer and dispatches (not in the virtual mouse mode)
PlatformMouseButton(mbtn,true);
end;
SDL_MOUSEBUTTONUP:begin
if not game.GetSettings.showSystemCursor then systemPlatform.SetCursor(0);
mbtn:=GetMouseButtonNum(event.button.button);
PlatformMouseButton(mbtn,false);
end;
SDL_MOUSEWHEEL:begin
// SDL counts notches, the engine uses the Windows units (WHEEL_DELTA=120 per notch).
// With natural scrolling (SDL_MOUSEWHEEL_FLIPPED) y is already inverted by the OS
// setting - kept as is, as WM_MOUSEWHEEL delivers it
PlatformMouseWheel(event.wheel.y*120);
end;
// the physical keyboard is ignored while the virtual input is active
SDL_KEYDOWN:if not virtualInput.IsActive then begin
Signal('KBD\KEYDOWN',ord(KeyFromSDL(event.key.keysym.sym,event.key.keysym.scancode))+
integer(event.key.keysym.scancode) shl 16);
end;
SDL_KEYUP:if not virtualInput.IsActive then begin
Signal('KBD\KEYUP',ord(KeyFromSDL(event.key.keysym.sym,event.key.keysym.scancode))+
integer(event.key.keysym.scancode) shl 16);
end;
SDL_TEXTINPUT:if not virtualInput.IsActive then begin
len:=StrLen(event.text.text);
SetLength(ust,len);
move(event.text.text,ust[1],len);
wst:=UTF8.ToWide(ust);
for i:=1 to length(wst) do
Signal('KBD\UNICHAR',word(wst[i]));
end;
// SDL2 reports no drop point
SDL_DROPBEGIN:dropList:=nil;
SDL_DROPFILE:begin
len:=StrLen(event.drop.file_);
SetLength(ust,len);
if len>0 then move(event.drop.file_^,ust[1],len); // raw copy: SDL paths are UTF-8
SDL_free(event.drop.file_);
SetLength(dropList,length(dropList)+1);
dropList[high(dropList)]:=ust;
end;
SDL_DROPTEXT:SDL_free(event.drop.file_);
SDL_DROPCOMPLETE:begin
PlatformDropFiles(dropList,Types.Point(-1,-1),false);
dropList:=nil;
end;
// the OS quit command (Cmd+Q, Ctrl+C in a terminal), routed to the main window: a close
// request of the main window
SDL_QUITEV:
if self=mainWindow then RequestClose
else Signal('Engine\Cmd\Exit',0);
SDL_JOYAXISMOTION..SDL_JOYDEVICEREMOVED:ProcessControllerEvent(event);
SDL_CONTROLLERAXISMOTION..SDL_CONTROLLERDEVICEREMAPPED:ProcessControllerEvent(event);
end;
end;
function TSDLGLWindow.IsTerminated:boolean;
begin
result:=terminated;
end;
procedure TSDLGLWindow.Minimize;
begin
SDL_MinimizeWindow(wnd);
end;
// SDL hit test: called while SDL pumps events, under X11 possibly on another window's thread
function FrameHitTestCallback(win:PSDL_Window;const area:PSDL_Point;data:Pointer):TSDL_HitTestResult; cdecl;
begin
result:=SDL_HITTEST_NORMAL;
try
result:=TSDLGLWindow(data).FrameHitTestAt(area^);
except
on e:Exception do Log.Warn('Frame hit test: '+ExceptionMsg(e));
end;
end;
// Hit test of an app-drawn frame, p - window coordinates: resize edges first, then frameHitTest
function TSDLGLWindow.FrameHitTestAt(const p:TSDL_Point):TSDL_HitTestResult;
const
results:array[TWindowArea] of TSDL_HitTestResult=(SDL_HITTEST_NORMAL,SDL_HITTEST_DRAGGABLE,
SDL_HITTEST_RESIZE_LEFT,SDL_HITTEST_RESIZE_RIGHT,SDL_HITTEST_RESIZE_TOP,SDL_HITTEST_RESIZE_BOTTOM,
SDL_HITTEST_RESIZE_TOPLEFT,SDL_HITTEST_RESIZE_TOPRIGHT,SDL_HITTEST_RESIZE_BOTTOMLEFT,
SDL_HITTEST_RESIZE_BOTTOMRIGHT);
var
flags:TSDL_WindowFlags;
sizeable,left,right,top,bottom:boolean;
ww,wh,dw,dh,border:integer;
kx,ky:single;
cp:TPoint;
area:TWindowArea;
hitTest:TWindowHitTest;
oldWindow:TWindow;
begin
result:=SDL_HITTEST_NORMAL;
if not customFrame then exit;
flags:=SDL_GetWindowFlags(wnd);
sizeable:=(flags and SDL_WINDOW_RESIZABLE<>0) and (flags and SDL_WINDOW_MAXIMIZED=0);
SDL_GetWindowSize(wnd,@ww,@wh);
SDL_GL_GetDrawableSize(wnd,@dw,@dh);
if (ww<=0) or (wh<=0) then exit;
kx:=dw/ww; ky:=dh/wh; // drawable pixels per window coordinate
if sizeable then begin
border:=Max(2,round(8*surface.dpi/96/kx)); // as the OS frame: 8 pixels at 96 DPI
left:=p.x<border;
right:=p.x>=ww-border;
top:=p.y<border;
bottom:=p.y>=wh-border;
if top and left then exit(SDL_HITTEST_RESIZE_TOPLEFT);
if top and right then exit(SDL_HITTEST_RESIZE_TOPRIGHT);
if bottom and left then exit(SDL_HITTEST_RESIZE_BOTTOMLEFT);
if bottom and right then exit(SDL_HITTEST_RESIZE_BOTTOMRIGHT);
if left then exit(SDL_HITTEST_RESIZE_LEFT);
if right then exit(SDL_HITTEST_RESIZE_RIGHT);
if top then exit(SDL_HITTEST_RESIZE_TOP);
if bottom then exit(SDL_HITTEST_RESIZE_BOTTOM);
end;
LockState;
hitTest:=frameHitTest;
UnlockState;
area:=TWindowArea.Client;
if Assigned(hitTest) and TryClientToCanvas(Types.Point(round(p.x*kx),round(p.y*ky)),cp) then begin
// the provider may use the window's UI: the threadvar must point at this window
oldWindow:=Apus.Engine.API.window;
Apus.Engine.API.window:=self;
try
area:=hitTest(cp.x,cp.y);
finally
Apus.Engine.API.window:=oldWindow;
end;
end;
if not sizeable and (area>TWindowArea.Caption) then area:=TWindowArea.Client;
result:=results[area];
end;
{$IFDEF MSWINDOWS}
// On Windows SDL keeps the client rect when the border changes and doesn't lay out a maximized
// window again: fit it to the work area of its monitor (the restore rect is kept by the OS)
procedure FitMaximizedToWorkArea(wnd:PSDL_Window);
var
info:TSDL_SysWMinfo;
mi:TMonitorInfo;
begin
SDL_VERSION(info.version);
if SDL_GetWindowWMInfo(wnd,@info)=SDL_FALSE then exit;
mi.cbSize:=sizeof(mi);
if not GetMonitorInfo(MonitorFromWindow(info.win.window,MONITOR_DEFAULTTONEAREST),@mi) then exit;
with mi.rcWork do
SetWindowPos(info.win.window,0,left,top,right-left,bottom-top,SWP_NOZORDER or SWP_NOACTIVATE);
end;
{$ENDIF}
// SDL keeps the border state itself: a window maximized with CustomWhenMaximized loses it
procedure TSDLGLWindow.UpdateFrame;
var
flags:TSDL_WindowFlags;
want:boolean;
begin
flags:=SDL_GetWindowFlags(wnd);
if flags and SDL_WINDOW_FULLSCREEN<>0 then exit; // no border to change in fullscreen
want:=(frame=TWindowFrame.Custom) or
((frame=TWindowFrame.CustomWhenMaximized) and (flags and SDL_WINDOW_MAXIMIZED<>0));
if want=customFrame then exit;
customFrame:=want;
if want then SDL_SetWindowBordered(wnd,SDL_FALSE)
else SDL_SetWindowBordered(wnd,SDL_TRUE);
{$IFDEF MSWINDOWS}
if flags and SDL_WINDOW_MAXIMIZED<>0 then FitMaximizedToWorkArea(wnd);
{$ENDIF}
end;
// sizeLimits are canvas units of the client, SDL limits - window coordinates of the client.
// SDL can't drop a limit: a removed one becomes the smallest/largest size it accepts
procedure TSDLGLWindow.UpdateSizeLimits;
const
NO_MAX=16384;
var
limits:TWindowSizeLimits;
minSize,maxSize:TSize;
ww,wh,dw,dh:integer;
k:single;
begin
if SDL_GetWindowFlags(wnd) and SDL_WINDOW_FULLSCREEN<>0 then exit;
LockState;
limits:=sizeLimits;
UnlockState;
minSize.cx:=0; minSize.cy:=0;
maxSize.cx:=0; maxSize.cy:=0;
if Assigned(limits) then limits(minSize,maxSize);
k:=1; // window coordinates per canvas unit
if (surface.canvasSize.cx>0) and (surface.displayRect.Width>0) then
k:=surface.displayRect.Width/surface.canvasSize.cx;
SDL_GetWindowSize(wnd,@ww,@wh);
SDL_GL_GetDrawableSize(wnd,@dw,@dh);
if (ww>0) and (dw>0) then k:=k*ww/dw;
minSize.cx:=round(minSize.cx*k); minSize.cy:=round(minSize.cy*k);
maxSize.cx:=round(maxSize.cx*k); maxSize.cy:=round(maxSize.cy*k);
if (minSize.cx<>limitMin.cx) or (minSize.cy<>limitMin.cy) then begin
SDL_SetWindowMinimumSize(wnd,Max(1,minSize.cx),Max(1,minSize.cy));
limitMin:=minSize;
end;
if (maxSize.cx<>limitMax.cx) or (maxSize.cy<>limitMax.cy) then begin
if maxSize.cx<=0 then ww:=NO_MAX else ww:=maxSize.cx;
if maxSize.cy<=0 then wh:=NO_MAX else wh:=maxSize.cy;
SDL_SetWindowMaximumSize(wnd,ww,wh);
limitMax:=maxSize;
end;
end;
procedure TSDLGLWindow.Maximize;
begin
SDL_MaximizeWindow(wnd);
end;
procedure TSDLGLWindow.Restore;
begin
SDL_RestoreWindow(wnd);
end;
procedure TSDLGLWindow.MoveTo(x,y:integer;width:integer;
height: integer);
begin
if (width>0) and (height>0) then
SDL_SetWindowSize(wnd,width,height);
SDL_SetWindowPosition(wnd,x,y);
end;
function TSDLGLWindow.CreateOpenGLContext(var graph:TOpenGLContextDesc;shareWithCurrent:boolean=false):UIntPtr;