-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathApus.Engine.Game.pas
More file actions
2192 lines (1977 loc) · 65.2 KB
/
Apus.Engine.Game.pas
File metadata and controls
2192 lines (1977 loc) · 65.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
// Main runtime unit of the engine
//
// IMPORTANT: Nevertheless BasicGame is implemented as class, it is
// NOT thread-safe itself i.e. does not allow multiple instances!
// (at least between Run/Stop calls)
// If you want to access private data (buffers, images) from other
// threads, use your own synchronization methods
//
// Copyright (C) 2003-2013 Apus Software (www.apus-software.com)
// Author: Ivan Polyacov (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/)
{$IFDEF IOS}{$S-}{$ENDIF}
{$R-}
unit Apus.Engine.Game;
interface
uses Classes, Apus.Core, Apus.Threads, Apus.Engine.Types, Apus.Engine.Window, Apus.Engine.API,
Apus.Engine.DebugOverlays;
var
onFrameDelay:integer=0; // Sleep this time every frame
disableDRT:boolean=false; // always render directly to the backbuffer - no
useDepthTexture:boolean=false; // when default RT is used, allocate a depth buffer texture instead of regular depth buffer
minRedrawIntervalMs:integer=100; // force frame redraw at least once per interval (0=disabled)
type
{ TGame }
TGame=class(TGameBase)
constructor Create(systemPlatform:ISystemPlatform;gfxSystem:IGraphicsSystem); // Создать экземпляр
procedure Run; override; // запустить движок (создание окна, переключение режима и пр.)
procedure Stop; override; // остановить и освободить все ресурсы (требуется повторный запуск через Run)
destructor Destroy; override; // автоматически останавливает, если это не было сделано
procedure SwitchToAltSettings; override; // Alt+Enter
// Events
// Этот метод вызывается из главного цикла всякий раз перед попыткой рендеринга кадра, даже если программа неактивна или девайс потерян
function OnFrame:boolean; override; // true означает что на экране что-то должно изменится поэтому экран нужно перерисовать. Иначе перерисовка выполнена не будет (движение мыши отслеживается отдельно)
procedure RenderFrame; override; // этот метод должен отрисовать кадр в backbuffer
// Scenes
procedure SwitchToScene(name:string); override;
procedure ShowWindowScene(name:string;modal:boolean=true); override;
procedure HideWindowScene(name:string); override;
// Cursors
procedure RegisterCursor(CursorID,priority:integer;cursorHandle:THandle); override;
function GetCursorForID(cursorID:integer):THandle; override;
procedure ToggleCursor(CursorID:integer;state:boolean=true); override;
procedure HideAllCursors; override;
// Translate coordinates in window's client area
procedure ClientToGame(var p:TPoint); override;
procedure GameToClient(var p:TPoint); override;
procedure FLog(st:string); override;
function GetStatus(n:integer):string; override;
procedure FireMessage(st:string8); override;
procedure DebugFeature(feature:TDebugFeature;enable:boolean); override;
procedure ToggleDebugFeature(feature:TDebugFeature);
procedure Lock; override;
procedure Unlock; override;
// Устанавливает флаги о необходимости сделать скриншот (JPEG or PNG)
procedure RequestScreenshot(saveAsJpeg:boolean=true); override;
procedure RequestFrameCapture(obj:TObject=nil); override;
procedure StartVideoCap(filename:string); override;
procedure FinishVideoCap; override;
// Utility functions
function MouseInRect(r:TRect):boolean; overload; override;
function MouseInRect(r:TRect2):boolean; overload; override;
function MouseInRect(x,y,width,height:single):boolean; overload; override;
function MouseIsNear(x,y,radius:single):boolean; overload; override;
function MouseWasInRect(r:TRect):boolean; overload; override;
function MouseWasInRect(r:TRect2):boolean; overload; override;
procedure WaitFor(pb:PBoolean;msg:string=''); override;
// Keyboard events utility functions
procedure SuppressKbdEvent; override;
function GetDepthBufferTex:TTexture; override;
procedure Minimize; override;
// Multi-window
function AddWindow(settings:TGameSettings):TWindow; override;
procedure RemoveWindow(wnd:TWindow); override;
procedure RenderScenesForWindow(wnd:TWindow);
procedure StopExtraWindows;
procedure SetSettings(s:TGameSettings); override; // этот метод служит для изменения режима или его параметров
function GetSettings:TGameSettings; override; // этот метод служит для изменения режима или его параметров
procedure DPadCustomPoint(x,y:single); override;
protected
useMainThread:boolean; // true - launch "main" thread with main loop,
// false - no main thread, catch frame events
canExitNow:boolean; // флаг того, что теперь можно начать деинициализацию
params,newParams:TGameSettings;
aspectRatio:single; // Initial aspect ratio (width/height)
altWidth,altHeight:integer; // saved window size for Alt+Enter
mainThread:IThread;
mainThreadErrorMsg:string8;
controlThreadId:TThreadID;
cursors:array of TObject;
crSect:TLock;
curPrior:integer; // приоритет текущего отображаемого курсора
wndCursor:THandle; // current system cursor
suppressCharEvent:boolean; // suppress next keyboard event (to avoid duplicated handle of both CHAR and KEY events)
avgTime,avgTime2:double;
timerFrame:cardinal;
customPoints,activeCustomPoints:array of TPoint; // custom navigation points
// Debug utilities
debug:TDebugState;
procedure ApplyNewSettings; virtual; // apply newParams to params - must be called from main thread!
procedure SetVSync(divider:integer);
// вызов только из главного потока
procedure InitGraph; virtual; // Инициализация графической части (переключить режим и все такое прочее)
procedure InitDefaultResources; virtual;
procedure AfterInitGraph; virtual; // Вызывается после инициализации графики
// Set window size/style/position
//procedure ConfigureMainWindow; virtual;
// Настраивает отрисовку
// Производит настройку подчинённых объектов/интерфейсов (Painter, UI и т.д)
// Вызывается после инициализации а также при изменения размеров окна, области или режима отрисовки
procedure SetupRenderArea; virtual;
procedure InitMainLoop; virtual;
procedure FrameLoop; virtual; // One iteration of the frame loop
procedure RenderAndPresentFrame; virtual; // May be called from the message handlers
procedure PresentFrame; virtual; // Displays back buffer
procedure DoneGraph; virtual; // Финализация графической части
// Производит захват кадра и производит с ним необходимые действия
procedure CaptureFrame; virtual;
procedure DrawCursor; virtual;
procedure DrawOverlays; virtual;
// находит сцену, которая должна получать сигналы о клавиатурном вводе
function TopmostSceneForKbd:TGameScene; virtual;
// Events
// Called when ENGINE\* event is fired
procedure onEngineEvent(event:String8;tag:NativeInt); virtual;
// Called when ENGINE\CMD\* event is fired
procedure onCmdEvent(event:String8;tag:NativeInt); virtual;
// Called when KBD\* event is fired
procedure onKbdEvent(event:String8;tag:NativeInt); virtual;
// Called when JOYSTICK\* event is fired
procedure onJoystickEvent(event:String8;tag:NativeInt); virtual;
// Called when GAMEPAD\* event is fired
procedure onGamepadEvent(event:String8;tag:NativeInt); virtual;
// Event processors
procedure CharEntered(charCode,scanCode:integer); virtual;
procedure KeyPressed(keyCode,scanCode:integer;pressed:boolean=true); virtual;
procedure SizeChanged(newWidth,newHeight:integer); virtual;
procedure Activate(activeState:boolean); virtual;
// Utils
procedure CreateDebugLogs; virtual;
// Draw magnified part of the screen under mouse
procedure DrawMagnifier; virtual;
// Internal hotkeys such as PrintScreen, Alt+F1 etc
procedure HandleInternalHotkeys(keyCode:integer;pressed:boolean); virtual;
procedure HandleGamepadNavigation;
procedure MainThreadLoop;
end;
// Для использования из главного потока
procedure Delay(time:integer);
implementation
uses Types, SysUtils, TypInfo, Apus.Engine.CmdProc, Apus.Images, Apus.FastGFX, Apus.Engine.ImageTools,
Apus.Engine.Resources,
{$IFDEF VIDEOCAPTURE}Apus.Engine.VideoCapture,{$ENDIF}
Apus.EventMan, Apus.Engine.Scene, Apus.Engine.UI, Apus.Engine.UITypes, Apus.Engine.UIScene,
Apus.Engine.Console, Apus.Publics, Apus.GfxFormats, Apus.Clipboard, Apus.Engine.TextDraw,
Apus.Engine.Controller,
Apus.Colors,
Apus.Engine.RobotAPI,
Apus.Files,
Apus.Lib,
Apus.Strings
{$IFDEF MSWINDOWS},Windows{$ENDIF};
type
TGameCursor=class
ID:integer;
priority:integer;
handle:THandle;
visible:boolean;
end;
TVarTypeGameClass=class(TVarTypeStruct)
class function GetField(variable:pointer;fieldName:string8;out varClass:TVarClass):pointer; override;
class function ListFields:string8; override;
end;
// Startup context for extra window render thread.
// Ownership: lives in AddWindow stack frame while AddWindow synchronously waits for startup result.
PExtraWindowContext=^TExtraWindowContext;
TExtraWindowContext=record
settings:TGameSettings;
callerReleasedMainContext:boolean; // true when AddWindow was called from main render thread
resultWnd:TWindow; // set by thread when window is created
startDone:boolean; // set by thread when startup is finished (success or failure)
startFailed:boolean;
errorMsg:string;
end;
var
gameEx:TGame;
perfValues:array[1..16] of int64;
perfMeasures:array[1..16] of double;
extraWindowCount:integer=0; // number of active extra windows (secondary render threads)
addWindowBusy:integer=0; // serialize AddWindow startup to avoid concurrent shared-context handshakes
{$IFDEF FREETYPE}
// Default vector font is Open Sans
{$I defaultFont.inc}
{$ELSE}
// Default raster fonts (exact sizes are 6.0, 7.0 and 9.0)
{$I defaultFont8.inc}
{$I defaultFont10.inc}
{$I defaultFont12.inc}
{$ENDIF}
// TODO: move to Apus.Utils/CmdLine once modern replacement API is finalized.
function HasParamLocal(const name:string):boolean;
var
i:integer;
s,n:string;
begin
n:=LowerCase(name);
for i:=1 to ParamCount do begin
s:=LowerCase(ParamStr(i));
if s=n then exit(true);
end;
result:=false;
end;
// TODO: move to Apus.Profiling when profiling API migration is complete.
procedure StartMeasure(id:integer); inline;
begin
if (id<low(perfValues)) or (id>high(perfValues)) then exit;
perfValues[id]:=CoreTime.Ticks;
end;
// TODO: move to Apus.Profiling when profiling API migration is complete.
function EndMeasure(id:integer):double; inline;
var
d:int64;
begin
if (id<low(perfValues)) or (id>high(perfValues)) then exit(0);
d:=CoreTime.Ticks-perfValues[id];
result:=d;
perfMeasures[id]:=result;
end;
// TODO: move to Apus.Profiling when profiling API migration is complete.
function EndMeasure2(id:integer):double; inline;
var
d:double;
begin
if (id<low(perfValues)) or (id>high(perfValues)) then exit(0);
d:=CoreTime.Ticks-perfValues[id];
result:=d;
perfMeasures[id]:=perfMeasures[id]*0.9+d*0.1;
end;
{ TGame }
procedure TGame.HandleGamepadNavigation;
var
scene:TUIScene;
procedure Traverse(e:TUIElement);
var
child:TUIElement;
pnt:TPoint;
begin
if e=nil then exit;
with e do begin
if not (flags.enabled and flags.visible) then exit;
pnt:=GetPosOnScreen.CenterPoint;
if e is TUIButton then activeCustomPoints:=activeCustomPoints+[pnt];
for child in children do Traverse(child);
end;
end;
begin
if gamepadNavigationMode=gnmDisabled then exit;
Lock;
try
activeCustomPoints:=customPoints;
SetLength(customPoints,0);
if gamepadNavigationMode=gnmAuto then begin
// Add clickable UI objects
if window.topmostScene is TUIScene then scene:=TUIScene(window.topmostScene)
else exit;
Traverse(scene.UI);
end;
finally
Unlock;
end;
end;
procedure TGame.HandleInternalHotkeys(keyCode:integer; pressed:boolean);
procedure ToggleDebugOverlay(n:integer);
begin
if debug.overlay=n then debug.overlay:=0
else debug.overlay:=n;
end;
function DebugOverlayHotkeyActive:boolean;
begin
result:=(debugHotkey<>0) and Bits.HasAll(window.shiftState,debugHotkey);
end;
begin
if pressed then begin
// Alt+Enter - switch display settings
if (TKey(keyCode and $FF)=TKey.Enter) and (window.shiftstate and sscAlt>0) then
if (params.mode.displayMode<>params.altMode.displayMode) and
(params.altMode.displayMode<>dmNone) then
SwitchToAltSettings;
// Alt+F11
if (TKey(keyCode and $FF)=TKey.F11) and Bits.HasAll(window.shiftState,sscAlt) then begin
SetVSync(params.VSync xor 1); // toggle vsync
end;
// F12 or PrintScreen - screenshot (JPEG), Alt+F12 - (loseless)
if (TKey(keyCode and $FF)=TKey.PrintScreen) or (TKey(keyCode and $FF)=TKey.F12) then
RequestScreenshot(not Bits.HasAll(window.shiftState,sscAlt));
if DebugOverlayHotkeyActive then begin
if TKey(keyCode and $FF)=TKey.F1 then begin
if debug.overlay=0 then begin
debug.overlay:=1;
DebugFeature(dfShowFPS,true);
end else begin
debug.overlay:=0;
debug.features:=[];
end;
end else
if TKey(keyCode and $FF)=TKey.F3 then
ToggleDebugFeature(dfShowMagnifier);
end;
// [Alt]+[1] .. [Alt]+[9] - switch debug overlay when enabled
if (debug.overlay>0) and (TKey(keyCode and $FF) in [TKey.D1..TKey.D9]) and Bits.HasAll(window.shiftState,sscAlt) then begin
debug.overlay:=1+keyCode-byte(TKey.D1);
end;
// Shift+Alt+F1 - Create debug logs
if (TKey(keyCode and $FF)=TKey.F1) and
(window.shiftState and sscAlt>0) and
(window.shiftState and sscShift>0) then CreateDebugLogs;
end;
end;
procedure TGame.RequestScreenshot(saveAsJpeg:boolean=true);
begin
window.RequestScreenshot(saveAsJpeg);
end;
procedure TGame.RequestFrameCapture(obj:TObject=nil);
begin
window.RequestFrameCapture(obj);
end;
procedure TGame.ApplyNewSettings;
begin
params:=newParams;
if (params.mode.displayMode=dmFullScreen) and ((altWidth=0) or (altHeight=0)) then begin
// save size for windowed mode
altWidth:=params.width;
altHeight:=params.height;
end;
if running then begin // смена параметров во время работы
with params.mode do
Log.Msg('Change mode to: %s,%s,%s %d x %d ',
[displayMode.ToString, displayFitMode.ToString, displayScaleMode.ToString,
params.width, params.height]);
window.Configure(params);
if gfx.target<>nil then gfx.target.Backbuffer;
SetupRenderArea;
window.NotifyScenesModeChanged;
end;
end;
procedure TGame.SetVSync(divider: integer);
begin
if (mainThread<>nil) and (mainThread.ID<>GetCurrentThreadID) then begin
Signal('ENGINE\Cmd\SetSwapInterval',divider);
exit;
end;
params.VSync:=divider;
if gfx.config.SetVSyncDivider(divider) then exit;
if window.SetVSync(divider) then exit;
PutMsg('Failed to set VSync: no method available');
end;
procedure TGame.SetSettings(s: TGameSettings);
begin
if not systemPlatform.canChangeSettings then exit;
newParams:=s;
if useMainThread and (mainThread=nil) then begin
ApplyNewSettings; exit;
end;
if (mainThread=nil) or (GetCurrentThreadID<>mainThread.ID) then
Signal('Engine\CMD\ChangeSettings')
else
ApplyNewSettings;
end;
function TGame.MouseInRect(r:TRect):boolean;
begin
result:=window.MouseInRect(r);
end;
function TGame.MouseInRect(r:TRect2):boolean;
begin
result:=window.MouseInRect(r);
end;
function TGame.MouseInRect(x,y,width,height:single):boolean;
begin
result:=window.MouseInRect(x,y,width,height);
end;
function TGame.MouseIsNear(x,y,radius:single):boolean;
begin
result:=window.MouseIsNear(x,y,radius);
end;
procedure TGame.CharEntered(charCode,scanCode:integer);
var
scene:TGameScene;
key:cardinal;
wst:WideString;
ast:AnsiString;
begin
if suppressCharEvent then begin
suppressCharEvent:=false; exit;
end;
if window.shiftstate and sscBaseMask=sscCtrl then exit; // Ignore Ctrl+*
// Send to active scene
scene:=TopmostSceneForKbd;
if scene<>nil then begin
// TODO: lossy Unicode→ANSI conversion — non-ASCII chars may produce empty ast,
// causing ast[1] access to read garbage. Rework to use charcode directly.
wst:=WideChar(charcode);
ast:=AnsiString(wst);
if length(ast)=0 then exit;
key:=byte(ast[1])+(scancode and $FF) shl 8+(charcode and $FFFF) shl 16;
scene.WriteKey(key);
end;
end;
procedure TGame.KeyPressed(keyCode,scanCode:integer;pressed:boolean=true);
var
scene:TGameScene;
uCode:cardinal;
begin
ASSERT(scancode in [0..255]);
uCode:=keyCode and $FFFF+scanCode shl 24;
scene:=TopmostSceneForKbd;
if pressed and (scene<>nil) then
scene.WriteKey(scancode shl 8+keyCode);
HandleInternalHotkeys(keyCode,pressed);
if pressed then begin
window.keyState[scanCode]:=window.keyState[scanCode] or 1;
//Log.Msg('KeyDown %d, KS[%d]=%2x ',[lParam,scanCode,window.keystate[scanCode]]);
if scene<>nil then Signal('SCENE\'+scene.name+'\KeyDown',uCode);
end else begin
window.keyState[scanCode]:=window.keyState[scanCode] and $FE;
//Log.Msg('KeyUp %d, KS[$d]=%2x ',[lParam,scanCode,window.keystate[scanCode]]);
if scene<>nil then Signal('SCENE\'+scene.name+'\KeyUp',uCode);
end;
end;
procedure TGame.SizeChanged(newWidth,newHeight:integer);
begin
if (window.windowWidth<>newWidth) or (window.windowHeight<>newHeight) then begin
window.windowWidth:=newWidth;
window.windowHeight:=newHeight;
Log.Msg('RESIZED: %d,%d',[window.windowWidth,window.windowHeight]);
SetupRenderArea;
window.screenChanged:=true;
end;
end;
procedure TGame.Activate(activeState:boolean);
begin
window.active:=activeState;
if not window.active and (params.mode.displayMode=dmFullScreen) then Minimize;
Log.Msg('ACTIVATE: %d',[byte(window.active)]);
Signal('Engine\ActivateWnd',byte(window.active));
if params.showSystemCursor then wndCursor:=0;
end;
function TGame.MouseWasInRect(r:TRect):boolean;
begin
result:=window.MouseWasInRect(r);
end;
function TGame.MouseWasInRect(r:TRect2):boolean;
begin
result:=window.MouseWasInRect(r);
end;
constructor TGame.Create(systemPlatform:ISystemPlatform;
gfxSystem: IGraphicsSystem);
begin
inherited Create(systemPlatform,gfxSystem);
Log.Force('Creating '+self.ClassName);
game:=self;
running:=false;
terminated:=false;
canExitNow:=false;
useMainThread:=true;
controlThreadId:=GetCurrentThreadId;
// TODO: window fields initialized here before window is created - move to post-CreateWindow init
mainThread:=nil;
params.VSync:=1;
crSect.Init('MainGameObj',20);
// Primary display
systemPlatform.GetScreenSize(screenWidth,screenHeight);
Log.Msg('Screen: %dx%d DPI=%d',[screenWidth,screenHeight,systemPlatform.GetScreenDPI]);
// TODO: PublishVar for renderWidth/renderHeight/windowWidth/windowHeight
// needs window to exist - move to post-CreateWindow init
PublishVar(@game,'game',TVarTypeGameClass);
end;
function TGame.GetSettings:TGameSettings;
begin
result:=params;
end;
function TGame.GetStatus(n:integer):string;
begin
result:='';
end;
destructor TGame.Destroy;
begin
if running then Stop;
crSect.Cleanup;
inherited;
end;
procedure TGame.DoneGraph;
begin
Log.Msg('DoneGraph Start');
DoneRobotAPI;
Signal('Engine\BeforeDoneGraph');
gfx.Done;
window.DoneGraph;
window.Show(false);
Signal('Engine\AfterDoneGraph');
Log.Msg('DoneGraph End');
end;
procedure TGame.DPadCustomPoint(x, y: single);
begin
Lock;
try
SetLength(customPoints,length(customPoints)+1);
customPoints[high(customPoints)].x:=round(x);
customPoints[high(customPoints)].y:=round(y);
finally
Unlock;
end;
end;
procedure TGame.DrawMagnifier;
begin
DrawDebugMagnifier(debug);
end;
procedure TGame.FLog(st:string);
begin
window.FLog(st);
end;
procedure TGame.Lock;
var
caller:pointer;
begin
caller:={$IFDEF FPC}get_caller_addr(get_frame){$ELSE}System.ReturnAddress{$ENDIF};
crSect.Enter(caller);
end;
procedure TGame.Unlock;
begin
crSect.Leave;
end;
procedure TGame.InitDefaultResources;
var
x,y:integer;
size:single;
begin
// Built-in fonts
{$IFDEF FREETYPE}
txt.LoadVectorFont(TBuffer.CreateFrom(@OpenSans_Regular,OpenSans_Regular_Size),'Default');
{$ELSE}
txt.LoadRasterFont(TBuffer.CreateFrom(@defaultFont8,length(defaultFont8)));
txt.LoadRasterFont(TBuffer.CreateFrom(@defaultFont10,length(defaultFont10)));
txt.LoadRasterFont(TBuffer.CreateFrom(@defaultFont12,length(defaultFont12)));
{$ENDIF}
size:=2+0.056*window.screenDPI;
defaultFont:=txt.GetFont('Default',size);
smallFont:=txt.GetFont('Default',size*0.8);
largerFont:=txt.GetFont('Default',size*1.25);
// Default checker texture
defaultTexture:=AllocImage(32,32,ipfARGB,aiTexture+aiAutoMipMap,'defaultTex');
DrawToTexture(defaultTexture);
for y:=0 to defaultTexture.height-1 do
for x:=0 to defaultTexture.width-1 do
PutPixel(x,y,$FF606060+$404040*(((x div 8) xor (y div 8)) and 1));
defaultTexture.Unlock;
//defaultTexture.SetFilter(TTexFilter.fltNearest);
// Mouse cursors
if params.showSystemCursor then begin
RegisterCursor(CursorID.Default,1,systemPlatform.GetSystemCursor(CursorID.Default));
RegisterCursor(CursorID.Link,2,systemPlatform.GetSystemCursor(CursorID.Link));
RegisterCursor(CursorID.Wait,9,systemPlatform.GetSystemCursor(CursorID.Wait));
RegisterCursor(CursorID.Input,3,systemPlatform.GetSystemCursor(CursorID.Input));
RegisterCursor(CursorID.Help,3,systemPlatform.GetSystemCursor(CursorID.Help));
RegisterCursor(CursorID.ResizeH,5,systemPlatform.GetSystemCursor(CursorID.ResizeH));
RegisterCursor(CursorID.ResizeW,5,systemPlatform.GetSystemCursor(CursorID.ResizeW));
RegisterCursor(CursorID.ResizeHW,6,systemPlatform.GetSystemCursor(CursorID.ResizeHW));
RegisterCursor(CursorID.Cross,6,systemPlatform.GetSystemCursor(CursorID.Cross));
RegisterCursor(CursorID.None,99,0);
end;
end;
procedure InitDefaultRT(wnd:TWindow; const params:TGameSettings);
begin
if HasParamLocal('-nodrt') then begin
Log.Msg('Default RT disabled by -noDRT switch');
exit;
end;
if disableDRT then begin
Log.Msg('Default RT disabled');
exit;
end;
wnd.InitDefaultRenderTarget(params.width,params.height,params.zbuffer,useDepthTexture);
end;
procedure TGame.InitGraph;
var
baseDPI:integer;
begin
Log.Msg('InitGraph');
Signal('Engine\BeforeInitGraph');
aspectRatio:=params.width/params.height;
window.Configure(params);
// Some platforms report client size only after first message pump.
window.ProcessMessages;
window.GetSize(window.windowWidth,window.windowHeight);
if window.windowWidth<=0 then window.windowWidth:=params.width;
if window.windowHeight<=0 then window.windowHeight:=params.height;
gfx.Init(window);
// Choose pixel formats
gfx.config.ChoosePixelFormats(pfTrueColor,pfTrueColorAlpha,pfRenderTarget,pfRenderTargetAlpha);
Log.Msg('Selected pixel formats:');
Log.Msg(' TrueColor: %s',[PixFmt2Str(pfTrueColor)]);
Log.Msg(' TrueColorAlpha: %s',[PixFmt2Str(pfTrueColorAlpha)]);
Log.Msg(' as render target:');
Log.Msg(' Opaque: %s',[PixFmt2Str(pfRenderTarget)]);
Log.Msg(' Alpha: %s',[PixFmt2Str(pfRenderTargetAlpha)]);
SetVSync(params.VSync);
//
InitDefaultRT(window,params);
SetupRenderArea;
screenScale:=1.0;
if params.mode.displayScaleMode=dsmDontScale then begin
baseDPI:=96;
{$IFDEF ANDROID}
baseDPI:=192;
{$ENDIF}
{$IFDEF IOS}
baseDPI:=192;
{$ENDIF}
if window.screenDPI>0.95*baseDPI*1.2 then screenScale:=1.2;
if window.screenDPI>0.94*baseDPI*1.5 then screenScale:=1.5;
if window.screenDPI>0.93*baseDPI*2.0 then screenScale:=2.0;
if window.screenDPI>0.92*baseDPI*2.5 then screenScale:=2.5;
end;
InitDefaultResources;
globalTintColor:=$FF808080;
window.ProcessMessages;
consoleSettings.popupCriticalMessages:=params.mode.displayMode<>dmSwitchResolution;
AfterInitGraph;
end;
procedure TGame.AfterInitGraph;
begin
Signal('Engine\AfterInitGraph');
end;
// --- Robot API command handlers ---
const
statusNames:array[TSceneStatus] of String8 = ('frozen','background','active');
ROBOT_PENDING_TOKEN='@PENDING@';
var
fpsMetricsPending:boolean=false;
fpsMetricsReqId:String8='';
fpsMetricsStartFrame:int64=0;
fpsMetricsTargetFrames:integer=0;
// RobotAPI is polled from the main-loop thread, so `window` threadvar points to mainWindow here.
// For now window control commands intentionally support only the main window.
function ValidateMainWindowParam(const req:TRobotRequest; out error:String8):boolean;
var wnd:String8;
begin
wnd:=req.Param('WINDOW').ToLower;
if (wnd='') or (wnd='0') or (wnd='main') or (wnd='mainwnd') then begin
result:=true;
exit;
end;
error:='only main window is supported (WINDOW=0/main)';
result:=false;
end;
function RobotCmdWindows(const req:TRobotRequest; out body:String8):boolean;
begin
if game=nil then begin body:='game not initialized'; exit(false) end;
body:='WINDOW: 0'#13#10+
' windowWidth: '+Conv.ToStr(window.windowWidth)+#13#10+
' windowHeight: '+Conv.ToStr(window.windowHeight)+#13#10+
' renderWidth: '+Conv.ToStr(window.renderWidth)+#13#10+
' renderHeight: '+Conv.ToStr(window.renderHeight)+#13#10+
' screenDPI: '+Conv.ToStr(window.screenDPI)+#13#10+
' screenScale: '+Conv.ToStr(game.screenScale,2)+#13#10+
' displayRect: '+Conv.ToStr(window.displayRect.Left)+','+Conv.ToStr(window.displayRect.Top)+','+
Conv.ToStr(window.displayRect.Right)+','+Conv.ToStr(window.displayRect.Bottom)+#13#10;
result:=true;
end;
function RobotCmdWindowMove(const req:TRobotRequest; out body:String8):boolean;
var
g:TGame;
x,y,w,h:integer;
sx,sy:String8;
p:TPoint;
begin
g:=game as TGame;
if g=nil then begin body:='game not initialized'; exit(false) end;
if not ValidateMainWindowParam(req,body) then exit(false);
sx:=req.Param('X');
sy:=req.Param('Y');
if (sx='') or (sy='') then begin
body:='X and Y parameters required';
exit(false);
end;
x:=Conv.ToInt(sx);
y:=Conv.ToInt(sy);
w:=Conv.ToInt(req.Param('W'));
h:=Conv.ToInt(req.Param('H'));
if ((w>0) xor (h>0)) then begin
body:='W and H should be both specified or both omitted';
exit(false);
end;
window.MoveTo(x,y,w,h);
window.ProcessMessages;
window.GetSize(window.windowWidth,window.windowHeight);
g.SetupRenderArea;
p:=Types.Point(0,0);
window.ClientToScreen(p);
body:='x: '+Conv.ToStr(p.x)+#13#10+
'y: '+Conv.ToStr(p.y)+#13#10+
'windowWidth: '+Conv.ToStr(window.windowWidth)+#13#10+
'windowHeight: '+Conv.ToStr(window.windowHeight)+#13#10+
'renderWidth: '+Conv.ToStr(window.renderWidth)+#13#10+
'renderHeight: '+Conv.ToStr(window.renderHeight)+#13#10;
result:=true;
end;
function RobotCmdWindowResize(const req:TRobotRequest; out body:String8):boolean;
var
g:TGame;
x,y,w,h:integer;
sx,sy:String8;
p:TPoint;
begin
g:=game as TGame;
if g=nil then begin body:='game not initialized'; exit(false) end;
if not ValidateMainWindowParam(req,body) then exit(false);
w:=Conv.ToInt(req.Param('W'));
h:=Conv.ToInt(req.Param('H'));
if (w<=0) or (h<=0) then begin
body:='W and H parameters should be >0';
exit(false);
end;
sx:=req.Param('X');
sy:=req.Param('Y');
if (sx='') and (sy='') then begin
p:=Types.Point(0,0);
window.ClientToScreen(p);
x:=p.x;
y:=p.y;
end else begin
if (sx='') or (sy='') then begin
body:='X and Y should be both specified or both omitted';
exit(false);
end;
x:=Conv.ToInt(sx);
y:=Conv.ToInt(sy);
end;
window.MoveTo(x,y,w,h);
window.ProcessMessages;
window.GetSize(window.windowWidth,window.windowHeight);
g.SetupRenderArea;
p:=Types.Point(0,0);
window.ClientToScreen(p);
body:='x: '+Conv.ToStr(p.x)+#13#10+
'y: '+Conv.ToStr(p.y)+#13#10+
'windowWidth: '+Conv.ToStr(window.windowWidth)+#13#10+
'windowHeight: '+Conv.ToStr(window.windowHeight)+#13#10+
'renderWidth: '+Conv.ToStr(window.renderWidth)+#13#10+
'renderHeight: '+Conv.ToStr(window.renderHeight)+#13#10;
result:=true;
end;
function RobotCmdFps(const req:TRobotRequest; out body:String8):boolean;
var
g:TGame;
n,i,idx,startFrameNum:integer;
collectMetrics:boolean;
begin
g:=game as TGame;
if g=nil then begin body:='game not initialized'; exit(false) end;
collectMetrics:=Conv.ToBool(req.Param('METRICS'));
n:=Conv.ToInt(req.Param('N'));
if collectMetrics and (n<=0) then n:=50;
if collectMetrics then begin
if (not fpsMetricsPending) or (fpsMetricsReqId<>req.id) then begin
fpsMetricsPending:=true;
fpsMetricsReqId:=req.id;
fpsMetricsStartFrame:=window.frameNum;
fpsMetricsTargetFrames:=n;
window.timings.phaseMetrics:=true;
body:=ROBOT_PENDING_TOKEN;
exit(true);
end;
if window.frameNum-fpsMetricsStartFrame<fpsMetricsTargetFrames then begin
body:=ROBOT_PENDING_TOKEN;
exit(true);
end;
fpsMetricsPending:=false;
fpsMetricsReqId:='';
window.timings.phaseMetrics:=false;
n:=fpsMetricsTargetFrames;
if n<=0 then n:=50;
end else
if req.Param('METRICS')<>'' then
window.timings.phaseMetrics:=false;
body:='fps: '+Conv.ToStr(window.FPS,2)+#13#10+
'smoothFPS: '+Conv.ToStr(window.smoothFPS,2)+#13#10+
'frameNum: '+Conv.ToStr(window.frameNum)+#13#10+
'frameTimeMs: '+Conv.ToStr(window.timings.lastFrameTimeUs*0.001,2)+#13#10;
if collectMetrics then begin
body:=body+
'msgMs: '+Conv.ToStr(window.timings.lastMsgUs*0.001,2)+#13#10+
'onFrameMs: '+Conv.ToStr(window.timings.lastOnFrameUs*0.001,2)+#13#10+
'renderMs: '+Conv.ToStr(window.timings.lastRenderUs*0.001,2)+#13#10+
'presentMs: '+Conv.ToStr(window.timings.lastPresentUs*0.001,2)+#13#10+
'sleepMs: '+Conv.ToStr(window.timings.lastSleepUs*0.001,2)+#13#10;
end;
if n>0 then begin
if n>window.timings.frameTimeRingCount then n:=window.timings.frameTimeRingCount;
if n>FRAME_TIME_RING_SIZE then n:=FRAME_TIME_RING_SIZE;
body:=body+'historyCount: '+Conv.ToStr(n)+#13#10;
if n>0 then begin
idx:=window.timings.frameTimeRingPos-n;
if idx<0 then inc(idx,FRAME_TIME_RING_SIZE);
startFrameNum:=integer(window.frameNum)-n+1;
if startFrameNum<0 then startFrameNum:=0;
for i:=0 to n-1 do begin
if collectMetrics then begin
body:=body+
'Frame: '+Conv.ToStr(startFrameNum+i)+#13#10+
' MSG: '+Conv.ToStr(window.timings.phaseMsgRing[(idx+i) mod FRAME_TIME_RING_SIZE]*0.001,2)+#13#10+
' ONFRAME: '+Conv.ToStr(window.timings.phaseOnFrameRing[(idx+i) mod FRAME_TIME_RING_SIZE]*0.001,2)+#13#10+
' RENDER: '+Conv.ToStr(window.timings.phaseRenderRing[(idx+i) mod FRAME_TIME_RING_SIZE]*0.001,2)+#13#10+
' PRESENT: '+Conv.ToStr(window.timings.phasePresentRing[(idx+i) mod FRAME_TIME_RING_SIZE]*0.001,2)+#13#10+
' SLEEP: '+Conv.ToStr(window.timings.phaseSleepRing[(idx+i) mod FRAME_TIME_RING_SIZE]*0.001,2)+#13#10+
' Total: '+Conv.ToStr(window.timings.frameTimeRing[(idx+i) mod FRAME_TIME_RING_SIZE]*0.001,2)+#13#10;
end else
body:=body+'FRAME_MS: '+Conv.ToStr(window.timings.frameTimeRing[(idx+i) mod FRAME_TIME_RING_SIZE]*0.001,2)+#13#10;
if collectMetrics then begin
body:=body+#13#10;
end;
end;
end;
end;
result:=true;
end;
function RobotCmdScenes(const req:TRobotRequest; out body:String8):boolean;
var
i:integer;
s:TGameScene;
activeOnly:boolean;
begin
if game=nil then begin body:='game not initialized'; exit(false) end;
activeOnly:=req.Param('ACTIVE_ONLY')<>'';
body:='';
window.Lock;
try
for i:=0 to high(window.scenes) do begin
s:=window.scenes[i];
if activeOnly and (s.status<>ssActive) then continue;
body:=body+'SCENE: '+s.name+#13#10+
' status: '+statusNames[s.status]+#13#10+
' zOrder: '+Conv.ToStr(s.zOrder)+#13#10+
' frequency: '+Conv.ToStr(s.frequency)+#13#10+
' fullscreen: '+Conv.ToStr(s.fullscreen)+#13#10+
' class: '+String8(s.ClassName)+#13#10;
end;
finally
window.Unlock;
end;
if body='' then begin body:='no scenes available'; exit(false) end;
result:=true;
end;
function RobotCmdScreenshot(const req:TRobotRequest; out body:String8):boolean;
var
fname:String8;
x,y,w,h:integer;
img:TBitmapImage;
res:ByteArray;
begin
if game=nil then begin body:='game not initialized'; exit(false) end;
fname:=req.Param('FILE');
if fname='' then fname:='screenshot.png';
x:=Conv.ToInt(req.Param('X'));
y:=Conv.ToInt(req.Param('Y'));
w:=Conv.ToInt(req.Param('W'));
h:=Conv.ToInt(req.Param('H'));
if w<=0 then w:=window.renderWidth;
if h<=0 then h:=window.renderHeight;
img:=TBitmapImage.Create(w,h,ipfXRGB);
try
gfx.CopyFromBackbuffer(x,window.renderHeight-y-h,img);
img.FlipVertical; // backbuffer is bottom-up in OpenGL
res:=SavePNG(img);
Files.WriteBlock(fname,@res[0],length(res),0);
body:='file: '+fname+#13#10+
'width: '+Conv.ToStr(w)+#13#10+
'height: '+Conv.ToStr(h)+#13#10;
result:=true;
except
on e:Exception do begin
body:=String8(e.Message);
result:=false;
end;
end;
img.Free;
end;
function RobotCmdPixel(const req:TRobotRequest; out body:String8):boolean;
var
x,y:integer;