Repository navigation
Expand file tree
/
Copy pathApus.Engine.GameApp.pas
More file actions
1178 lines (1074 loc) · 37.5 KB
/
Copy pathApus.Engine.GameApp.pas
File metadata and controls
1178 lines (1074 loc) · 37.5 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
// Game Framework launcher class
// Copyright (C) 2017 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.GameApp;
interface
uses
{$IF DEFINED(ANDROID) AND DEFINED(ANDROID_NATIVE_JNI)}jni,{$IFEND}
Apus.Core, Apus.Threads, Apus.Config, Apus.Engine.API;
type
{$SCOPEDENUMS ON}
// Screen orientation policy for the main window (R-31)
TOrientation=(any,portrait,landscape);
// How a fixed canvas is rendered: at native resolution (sharp) or at canvas resolution (cheap)
TFixedCanvasRender=(sharp,cheap);
{$SCOPEDENUMS OFF}
// --- Startup configuration groups (fields of TGameApplication, set in SetupApplication) ---
// Application identity and startup files
TAppSetup=record
title:string; // window caption, shown to the user
storageName:string; // name of the writable storage folders (see SetupStorageDirs); title is used when empty
// Config file to load (may contain a path). Prepare opens it as appConfig and replaces the
// name with the file actually used: a copy in AppDataDir when the shipped one must stay intact
configFile:String8;
logFile:string; // log file name, the folder is chosen by Prepare
procedure Init;
end;
// Requested backends. Prepare/Run resolve the request, the request itself stays unchanged
TBackendRequest=record
platform:TSystemPlatform; // spDefault: native on Windows, SDL elsewhere
graphicsAPI:TGraphicsAPI;
procedure Init;
end;
// Main window startup request, translated into TGameSettings by SetupGameSettings
TWindowSetup=record
size:TSize; // client area size
fullscreen:boolean; // start fullscreen ([Alt]+[Enter] switches to the window mode)
maximized:boolean; // start maximized (resizable window only); size is the normal (restored) size
frame:TWindowFrame; // window frame in the window mode: OS or drawn by the app (TWindow.frameHitTest)
resizable:boolean; // user can resize the window
scaleForDPI:boolean; // enlarge the window if DPI is higher than the platform default (96 for desktop monitor); macOS window size is always in points
systemCursor:boolean; // true - system hardware cursor, false - system cursor is disabled, custom cursor must be drawn
procedure Init;
end;
// OpenGL context request: the backend may create a different context
TGLContextRequest=record
coreContext:boolean; // core profile, otherwise compatibility (ignored in GLES builds)
debugContext:boolean; // debug context flag (debugMode also sets it)
forwardCompatible:boolean; // forward-compatible context flag
preferHighest:boolean; // highest available version, with fallback to the minimal one
baseline:boolean; // use no features above GL 3.3 / ES 3.0: checks the baseline paths on a newer GPU
minMajor,minMinor:byte; // minimal acceptable version
procedure Init;
end;
// Startup render policy, applied through the game settings
TRenderSetup=record
vSync:boolean; // false: no VSync, FPS is shown
depthTexture:boolean; // use depth texture instead of the regular depth buffer (not available with direct render)
procedure Init;
end;
// Built-in scenes created at startup
TStartupScenes=record
message:boolean; // built-in dialogs; disable when the application provides its own
console:boolean; // console scene [Win]+[~]
tweaker:boolean; // tweaker scene [Ctrl]+[~]
loader:boolean; // default loader scene with spinner
procedure Init;
end;
var
deviceDPI:integer=96; // equals window.surface.dpi
deviceScale:single=1.0; // deviceDPI/96
instanceID:integer=0;
gameLangCode:string='en';
// The application config document (appSetup.configFile), opened by Prepare and freed with
// the application; nil when there is no config file
appConfig:TConfig=nil;
type
TGameApplication=class
// Call these methods from external code to launch the game
constructor Create;
// Basic initialization (non-visual): logs, configs, settings. Calls SetupApplication first.
// Can be called only once.
procedure Prepare; virtual;
// Creates game objects, window, starts render, create scenes and launch infinite main loop
procedure Run; virtual;
// Finalization (you can use Free to call this indirectly)
destructor Destroy; override;
// These methods provide default functionality. Override them to add extra functions
procedure HandleParam(param:string); virtual; // Handle each command line option
procedure LoadOptions; virtual; // Load settings (may add default values)
procedure SaveOptions; virtual; // Save settings
procedure SetupGameSettings(var settings:TGameSettings); virtual;
// Initialization routines: override with actual functionality
procedure InitSound; virtual;
procedure LoadFonts; virtual; // Load font files (called once)
procedure SelectFonts; virtual; // Select font constants (may be called many times)
procedure InitStyles; virtual; // Which styles to add?
procedure CreateScenes; virtual; // Create and add game scenes
procedure LoadScenes; virtual;
procedure InitCursors; virtual;
procedure SetupHighDPI; virtual;
procedure FatalError(msg:string); virtual;
procedure onResize; virtual;
// --- Working surface declaration (R-31) ---
// Presets fill orientation+surfaceConfig; call them in SetupApplication.
procedure SetupFullWindow; // default: canvas follows the client area
// Canvas follows the client area in units of 1/dpi inch (96: "logical pixels", like
// points on Retina): the same numbers give the same physical size on any display
procedure SetupLogicalCanvas(dpi:integer=96);
procedure SetupFixedCanvas(w,h:integer;render:TFixedCanvasRender=TFixedCanvasRender.sharp);
procedure SetupMobilePortrait(canvasW:integer);
procedure SetupMobileLandscape(canvasH:integer);
procedure SetupPixelArt(w,h:integer);
// Configuration hook: called on EVERY surface rebuild, before the resolver.
// Look at the proposed surface and adjust the axes (perf cap, aspect choice).
// Change config only - not global state. wnd tells the windows apart.
procedure ConfigureSurface(wnd:TWindow;const input:TSurfaceInput;
var config:TSurfaceConfig); virtual;
// Useful tools
procedure ShowMessage(mes:String8;OkEvent:String8='';x:integer=0;y:integer=0); virtual;
procedure Confirm(mes,OkEvent,CancelEvent:String8;x:integer=0;y:integer=0); virtual;
procedure Ask(mes,YesEvent,NoEvent:String8;x:integer=0;y:integer=0); virtual;
public
orientation:TOrientation; // main window orientation policy
surfaceConfig:TSurfaceConfig; // project-level surface declaration (main window)
protected
// --- Startup configuration ---
// Create fills the engine defaults, the project sets its values in SetupApplication.
// Then Prepare applies the config file (LoadOptions) and command line (HandleParam).
// The fields are read by Prepare and Run: changing them afterwards has no effect.
appSetup:TAppSetup;
requestBackend:TBackendRequest;
windowSetup:TWindowSetup;
requestGL:TGLContextRequest;
renderSetup:TRenderSetup;
startupScenes:TStartupScenes;
debugMode:boolean; // -DEBUG: OpenGL debug context, critical section checks
checkForSteam:boolean; // connect to the Steam client in Prepare (needs -dSTEAM, see Apus.Engine.SteamAPI)
sysPlatform:ISystemPlatform;
{$IFDEF DARWIN}
controlThread:Apus.Threads.IThread;
{$ENDIF}
screenWidth,screenHeight:integer;
realScreenWidth,realScreenHeight:integer;
// The single place for project settings: called once at the beginning of Prepare,
// before the log, config and platform are set up. Call inherited first, then assign
// the startup configuration fields and the surface preset (SetupFixedCanvas etc).
procedure SetupApplication; virtual;
procedure ControlLoop;
private
prepared:boolean;
end;
// Legacy GLSurfaceView shell. The SDL-first Android target does not use these bindings.
{$IF DEFINED(ANDROID) AND DEFINED(ANDROID_NATIVE_JNI)}
// Binding functions (to be exported)
procedure AppSurfaceChanged(env:PJNIEnv;this:jobject; width, height:jint);
procedure AppInit(env:PJNIEnv;this:jobject; view:jobject; width,height,dpi:jint; assetManager:jobject; sdkVer:jint);
procedure AppDrawFrame(env:PJNIEnv;this:jobject);
procedure AppPause(env:PJNIEnv;this:jobject);
procedure AppResume(env:PJNIEnv;this:jobject);
function AppInput(env:PJNIEnv;this:jobject; action,i1,i2:jint; text:jstring):jstring;
procedure AppTouch(env:PJNIEnv;this:jobject; x,y:jfloat; action:jint);
procedure AppKey(env:PJNIEnv;this:jobject; keyCode,UChar:jint; event: jobject);
{$IFEND}
implementation
uses
Apus.Engine.Window,
{$IFDEF MSWINDOWS}Windows,Apus.Engine.WindowsPlatform,{$ENDIF}
{$IFDEF SDL}Apus.Engine.SDLplatform,{$ENDIF}
{$IF DEFINED(ANDROID) AND DEFINED(ANDROID_NATIVE_JNI)}Apus.Android,{$IFEND}
SysUtils,Types,Apus.AnimatedValues,{Apus.Engine.UDict,}
Apus.FastGFX,Apus.EventMan,Apus.Publics,
Apus.Engine.UI,Apus.Engine.UIScene,Apus.Engine.Game,Apus.Engine.Tools,
Apus.Engine.ConsoleScene,Apus.Engine.TweakScene,Apus.Engine.MessageScene,Apus.Engine.Notifications,Apus.Engine.RobotAPI,
Apus.Engine.Types,
{Apus.Engine.CustomStyle,Apus.Engine.BitmapStyle,}
Apus.Engine.Sound
{$IFDEF OPENGL},Apus.Engine.OpenGL{$ENDIF}
{$IFDEF STEAM},Apus.Engine.SteamAPI{$ENDIF},
Apus.Conv,
Apus.Files,
Apus.Log,
Apus.Strings,
Apus.Utils;
type
// Default loading scene displaying spinner
TLoadingScene=class(TGameScene)
v:TAnimatedValue;
tex:TTexture;
constructor Create;
function GetArea:TRect; override;
procedure Render; override;
end;
var
app:TGameApplication;
{$IF DEFINED(ANDROID) AND DEFINED(ANDROID_NATIVE_JNI)}
{Android bindings}
var
initialized:boolean;
procedure AppSurfaceChanged(env:PJNIEnv;this:jobject; width, height:jint);
begin
if app<>nil then app.windowSetup.size:=MakeSize(width,height);
// Resize window
end;
procedure AppInit(env:PJNIEnv;this:jobject; view:jobject; width,height,dpi:jint; assetManager:jobject; sdkVer:jint);
begin
if initialized then exit;
try
LogI(Format('AppInit: %d %d %d',[width,height,dpi]));
InitAndroid(env,this,view);
if app<>nil then app.windowSetup.size:=MakeSize(width,height);
deviceDPI:=dpi;
Signal('Engine\InitGame');
if @initGame<>nil then InitGame;
initialized:=true;
except
on e:exception do LogI('Error in AppInit: '+ExceptionMsg(e));
end;
end;
procedure AppDrawFrame(env:PJNIEnv;this:jobject);
begin
try
//Log.Force('DrawFrame!');
Signal('Engine\RunFrame');
except
on e:exception do LogI('Error in AppDrawFrame: '+ExceptionMsg(e));
end;
end;
procedure AppPause(env:PJNIEnv;this:jobject);
begin
try
LogI('AppPause!');
Signal('Engine\ActivateWnd',0);
Signal('Sound\Pause');
HideVirtualKeyboard;
except
on e:exception do LogI('Error in AppPause: '+ExceptionMsg(e));
end;
end;
procedure AppResume(env:PJNIEnv;this:jobject);
begin
try
LogI('AppResume!');
Signal('Engine\ActivateWnd',1);
Signal('Sound\Resume');
except
on e:exception do LogI('Error in AppResume: '+ExceptionMsg(e));
end;
end;
function AppInput(env:PJNIEnv;this:jobject; action,i1,i2:jint; text:jstring):jstring;
var
wst:WideString;
c:TUIControl;
i:integer;
begin
try
result:=nil;
if appEnv=nil then appEnv:=env;
wst:=DecodeUTF8 {TODO: use UTF8.Decode (check arg types)}(StringFromJavaString(text));
c:=FocusedControl;
Log.Msg(Format('AppInput: %d %d %d %s',[action, i1, i2, wst]));
if (c<>nil) and (c is TUIEditBox) then
with c as TUIEditBox do begin
case action of
// Commit text or set selection
1,2:begin
if selCount>0 then begin
// replace selection with given text
delete(realtext,selstart,selcount);
insert(wst,realText,selStart);
end else begin
// Insert text into cursor position and select it
insert(wst,realText,cursorpos+1);
selstart:=cursorpos+1;
end;
selcount:=length(wst);
cursorpos:=selstart+selcount-1;
if action=1 then begin
// Commit
selstart:=cursorPos+1;
selCount:=0;
end;
Log.Msg(Format('Input action=%d, sel=%d:%d, cursor=%d',[action,selstart,selcount,cursorpos]));
end;
// Get text before cursor
3:begin
if selCount>0 then wst:=copy(realText,1,selStart-1)
else wst:=copy(realText,1,cursorPos);
if length(wst)>i1 then delete(wst,1,length(wst)-i1);
result:=JavaString(EncodeUTF8 {TODO: use UTF8.Encode (check arg types)}(wst));
Log.Msg(Format('res=%s (%s)',[Conv.ToStr(result),EncodeUTF8 {TODO: use UTF8.Encode (check arg types)}(wst)]));
end;
// Get text after cursor
4:begin
if selCount>0 then wst:=copy(realtext,selStart+selCount,i1)
else wst:=copy(realText,cursorPos+1,i1);
result:=JavaString(EncodeUTF8 {TODO: use UTF8.Encode (check arg types)}(wst));
Log.Msg(Format('res=%s (%s)',[Conv.ToStr(result),EncodeUTF8 {TODO: use UTF8.Encode (check arg types)}(wst)]));
end;
// Get selected text
5:if selCount>0 then begin
wst:=copy(realText,selStart,selCount);
result:=JavaString(EncodeUTF8 {TODO: use UTF8.Encode (check arg types)}(wst));
end;
// Delete text
6:begin
// After selection
if selCount>0 then i:=selStart+selCount
else i:=cursorpos+1;
delete(realText,i,i2);
// Before selection
if selCount>0 then i:=selStart-1
else i:=cursorPos;
while (i>0) and (i1>0) do begin
delete(realText,i,1);
dec(i); dec(i1);
dec(selStart);
dec(cursorpos);
end;
end;
// Set selection/composing region
7,8:begin
selStart:=i1+1;
selCount:=i2-i1+1;
cursorpos:=i2;
end;
// Enter
10:begin
Signal('Kbd\Char',13);
Signal('Kbd\UniChar',13);
end;
end;
end;
except
on e:exception do LogI('Error in AppInput: '+ExceptionMsg(e));
end;
end;
const
// UI event types
ACTION_DOWN = 0;
ACTION_UP = 1;
ACTION_MOVE = 2;
ACTION_CANCEL = 3;
procedure AppTouch(env:PJNIEnv;this:jobject; x,y:jfloat; action:jint);
var
tag:integer;
begin
try
tag:=smallint(round(x))+smallint(round(y)) shl 16;
//LogI(Format('AppTouch: %d x=%5.1f y=%5.1f tag=%8x',[action,x,y,tag]));
if action=ACTION_DOWN then Signal('Engine\SingleTouchStart',tag);
if action=ACTION_UP then Signal('Engine\SingleTouchRelease',tag);
if action=ACTION_MOVE then Signal('Engine\SingleTouchMove',tag);
except
on e:exception do LogI('Error in AppTouch: '+ExceptionMsg(e));
end;
end;
procedure AppKey(env:PJNIEnv;this:jobject; keyCode,UChar:jint; event: jobject);
begin
LogI(Format('AppKey: %d %d',[keyCode,UChar]));
end;
{$IFEND}
{ Startup configuration groups }
procedure TAppSetup.Init;
begin
title:='Apus Game Engine Template';
storageName:='';
configFile:='';
logFile:='game.log';
end;
procedure TBackendRequest.Init;
begin
platform:={$IFDEF MSWINDOWS}spDefault{$ELSE}spSDL{$ENDIF};
graphicsAPI:=gaAuto;
end;
procedure TWindowSetup.Init;
begin
size:=MakeSize(1024,768);
fullscreen:=false;
maximized:=false;
frame:=TWindowFrame.System;
resizable:=false;
scaleForDPI:=true;
systemCursor:=true;
end;
procedure TGLContextRequest.Init;
begin
coreContext:=true;
debugContext:=false;
forwardCompatible:=false;
preferHighest:=true;
baseline:=false;
minMajor:=3;
minMinor:=0;
end;
procedure TRenderSetup.Init;
begin
vSync:=true;
depthTexture:=false;
end;
procedure TStartupScenes.Init;
begin
message:=true;
console:=true;
tweaker:=false;
loader:=true;
end;
{ TGameApplication }
constructor TGameApplication.Create;
begin
app:=self;
orientation:=TOrientation.any;
surfaceConfig.Init; // full window by default
appSetup.Init;
requestBackend.Init;
windowSetup.Init;
requestGL.Init;
renderSetup.Init;
startupScenes.Init;
end;
procedure TGameApplication.SetupApplication;
begin
// defaults are set in Create: nothing to do here
end;
// --- Working surface presets (R-31) ---
procedure TGameApplication.SetupFullWindow;
begin
orientation:=TOrientation.any;
surfaceConfig.Init;
end;
procedure TGameApplication.SetupLogicalCanvas(dpi:integer=96);
begin
if dpi<=0 then raise EError.Create('Logical canvas DPI must be positive');
orientation:=TOrientation.any;
surfaceConfig.Init;
surfaceConfig.canvasDPI:=dpi;
end;
procedure TGameApplication.SetupFixedCanvas(w,h:integer;render:TFixedCanvasRender=TFixedCanvasRender.sharp);
begin
ASSERT((w>0) and (h>0),'Fixed canvas must have positive size');
orientation:=TOrientation.any;
surfaceConfig.Init;
surfaceConfig.canvasSize:=MakeSize(w,h);
// keepAspect degenerates to the full client area when the aspects match
surfaceConfig.fit:=TSurfaceFit.keepAspect;
if render=TFixedCanvasRender.cheap then
surfaceConfig.renderSize:=MakeSize(w,h); // render at canvas resolution, then blit
end;
procedure TGameApplication.SetupMobilePortrait(canvasW:integer);
begin
ASSERT(canvasW>0,'Canvas width must be positive');
orientation:=TOrientation.portrait;
surfaceConfig.Init;
surfaceConfig.canvasSize:=MakeSize(canvasW,0); // height follows the surface
end;
procedure TGameApplication.SetupMobileLandscape(canvasH:integer);
begin
ASSERT(canvasH>0,'Canvas height must be positive');
orientation:=TOrientation.landscape;
surfaceConfig.Init;
surfaceConfig.canvasSize:=MakeSize(0,canvasH); // width follows the surface
end;
procedure TGameApplication.SetupPixelArt(w,h:integer);
begin
ASSERT((w>0) and (h>0),'Pixel art canvas must have positive size');
orientation:=TOrientation.any;
surfaceConfig.Init;
surfaceConfig.canvasSize:=MakeSize(w,h);
surfaceConfig.renderSize:=MakeSize(w,h);
surfaceConfig.fit:=TSurfaceFit.integerScale;
end;
procedure TGameApplication.ConfigureSurface(wnd:TWindow;const input:TSurfaceInput;
var config:TSurfaceConfig);
begin
// default: keep the declared configuration as is
end;
procedure TGameApplication.CreateScenes;
begin
Signal('GAMEAPP\CreateScenes');
end;
procedure TGameApplication.LoadScenes;
var
scene:TGameScene;
begin
Signal('GAMEAPP\LoadScenes');
TGameScene.LoadAllScenes;
end;
destructor TGameApplication.Destroy;
begin
if game<>nil then game.Stop;
sound.Done;
{$IFDEF STEAM}Steam.Shutdown;{$ENDIF}
FreeAndNil(appConfig);
inherited;
end;
procedure TGameApplication.FatalError(msg: string);
begin
SystemMessage(msg);
halt;
end;
procedure TGameApplication.Ask(mes, YesEvent, NoEvent: String8; x, y: integer);
begin
Apus.Engine.MessageScene.Ask(mes,YesEvent,NoEvent,x,y);
end;
procedure TGameApplication.Confirm(mes, OkEvent, CancelEvent: String8; x,
y: integer);
begin
Apus.Engine.MessageScene.Confirm(mes,OkEvent,CancelEvent,x,y);
end;
procedure TGameApplication.ShowMessage(mes, OkEvent: String8; x, y: integer);
begin
Apus.Engine.MessageScene.ShowMessage(mes,OkEvent,x,y);
end;
procedure TGameApplication.HandleParam(param: string);
begin
param:=UpperCase {TODO: use st.ToUpper}(param);
if param='-WND' then begin
Log.Force('Windowed mode enabled by a command line parameter');
windowSetup.fullscreen:=false;
end;
if param='-FULLSCREEN' then begin
Log.Force('Windowed mode disabled by a command line parameter');
windowSetup.fullscreen:=true;
end;
if param='-MAXIMIZED' then begin
Log.Force('Maximized window requested by a command line parameter');
windowSetup.maximized:=true;
end;
if param='-NOVSYNC' then begin
Log.Force('VSYNC disabled by a command line parameter');
renderSetup.vSync:=false;
end;
if param='-VSYNC' then begin
Log.Force('VSYNC enabled by a command line parameter');
renderSetup.vSync:=true;
end;
if param='-DEBUG' then begin
debugMode:=true;
Apus.Threads.debugCriticalSections:=true;
end;
if param='-GLCORE' then requestGL.coreContext:=true;
if param='-GLCOMPAT' then requestGL.coreContext:=false;
if param='-GLDEBUGCTX' then requestGL.debugContext:=true;
if param='-GLFORWARDCTX' then requestGL.forwardCompatible:=true;
if param='-GLBASELINE' then requestGL.baseline:=true;
if param='-NOSTEAM' then checkForSteam:=false;
if param='-ROBOT' then begin
Apus.Engine.RobotAPI.robotAPIEnabled:=true;
Log.Force('Robot API enabled by command line parameter');
end;
end;
procedure TGameApplication.InitCursors;
begin
game.ToggleCursor(CursorID.Default);
game.ToggleCursor(CursorID.Wait);
Signal('GAMEAPP\InitCursors');
end;
procedure TGameApplication.InitStyles;
begin
Signal('GAMEAPP\InitStyles');
end;
procedure TGameApplication.LoadFonts;
begin
Log.Msg('Loading fonts');
Signal('GAMEAPP\LoadFonts');
end;
procedure TGameApplication.LoadOptions;
var
i:integer;
cfg:TCfgNode;
begin
try
cfg:=appConfig.Root;
// InstanceID = random constant
instanceID:=cfg.Int('InstanceID',0);
if instanceID=0 then begin
instanceID:=(1000*random(50000)+CoreTime.Ticks shl 8+round(now*1000)) mod 100000000;
cfg.SetInt('InstanceID',instanceID);
end;
// Window or Fullscreen
if cfg.Bool('Options.FullScreen',false) then windowSetup.fullscreen:=true;
// Window size
i:=cfg.Int('Options.WindowWidth',-1);
if i>0 then begin
windowSetup.size.cx:=i;
windowSetup.size.cy:=cfg.Int('Options.WindowHeight',windowSetup.size.cy);
end;
windowSetup.scaleForDPI:=cfg.Bool('Options.scaleWindowSize',windowSetup.scaleForDPI);
Signal('GAMEAPP\OptionsLoaded');
except
on e:exception do Log.Force('Options error: '+ExceptionMsg(e));
end;
end;
procedure TGameApplication.onResize;
begin
Signal('GAMEAPP\onResize');
if game.running then SelectFonts;
end;
{$IFDEF MSWINDOWS}
type
TSetProcessDpiAwarenessContext=function(value:THandle):BOOL; stdcall;
const
DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2=THandle(-4);
{$IF Declared(SetProcessDPIAware)} {$ELSE}
function SetProcessDPIAware:BOOL; external user32 name 'SetProcessDPIAware';
{$IFEND}
procedure SetDPIAwareness;
var
lib:THandle;
setCtx:TSetProcessDpiAwarenessContext;
begin
// try Per-Monitor V2 first (Win10 1703+), fall back to system DPI aware
lib:=GetModuleHandle('user32.dll');
if lib<>0 then begin
setCtx:=TSetProcessDpiAwarenessContext(GetProcAddress(lib,'SetProcessDpiAwarenessContext'));
if Assigned(setCtx) then begin
if setCtx(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2) then exit;
end;
end;
SetProcessDPIAware; // fallback
end;
{$ENDIF}
// Config problems are shown as toasts: noticeable, while the program goes on with the defaults
procedure ShowConfigProblem(const msg:String8);
begin
ShowToast(msg,TToastKind.Warning);
end;
procedure TGameApplication.Prepare;
var
i:integer;
st:string;
logPath:String8;
usedPlatform:TSystemPlatform;
begin
if prepared then raise EError.Create('TGameApplication.Prepare can be called only once');
prepared:=true;
if not Assigned(onConfigProblem) then onConfigProblem:=ShowConfigProblem;
try
{$IFDEF MSWINDOWS}
SetDPIAwareness; // a DPI-aware process is a precondition of the surface model
{$ENDIF}
PublishVar(@gameLangCode,'gameLangCode',TVarTypeString);
Apus.Threads.Thread.Register({$IFDEF DARWIN}'MainThread'{$ELSE}'ControlThread'{$ENDIF});
SetupApplication;
//SetCurrentDir(ExtractFileDir(ParamStr(0)));
// Resolve per-platform writable dirs now that the app name is known.
if appSetup.storageName<>'' then SetupStorageDirs(String8(appSetup.storageName))
else SetupStorageDirs(String8(appSetup.title)); // a caption makes a poor folder name, but it's better than nothing
Randomize;
// Log rotation
// The log belongs next to the application, in Logs\ - that's where one looks for
// it first. Fall back to the per-platform writable dir when that's impossible:
// a read-only install location, or a macOS/iOS bundle (the filesystem may allow
// writing inside it, but that breaks the seal).
logPath:='';
if not bundleMode then begin
logPath:=String8(ExtractFilePath(ParamStr(0)))+'Logs'+PathDelim;
if not (Folder.Create(logPath) and Folder.Writable(logPath)) then logPath:='';
end;
if logPath='' then begin
Folder.Create(LogDir);
logPath:=LogDir;
end;
st:=logPath+appSetup.logFile;
st:=Files.FixName(st);
if fileExists(st) then
RenameFile(st,ChangeFileExt(st,'.old'));
Logger.UseLogFile(st,true);
Logger.LogCacheMode(true);
Logger.SetVerbosity(TSeverity.Debug);
if appSetup.configFile<>'' then begin
appSetup.configFile:=Files.FixName(appSetup.configFile);
// Decide where the persistent config lives. Normally it stays next to the
// shipped file (dev tree or a writable install) so behaviour is unchanged.
// It moves to the per-platform writable AppDataDir (seeded once from the
// shipped defaults) when the shipped copy must not be touched: either the
// directory is genuinely read-only, or we run from a macOS .app bundle whose
// Contents/Resources is writable on disk but must stay immutable, since a
// write there breaks the code-signing seal.
st:=ExtractFilePath(ExpandFileName(appSetup.configFile));
if bundleMode or not Folder.Writable(String8(st)) then begin
Folder.Create(AppDataDir);
st:=string(AppDataDir)+ExtractFileName(string(appSetup.configFile));
if not Files.Exists(String8(st)) and Files.Exists(appSetup.configFile) then
Files.CopyFile(String8(appSetup.configFile),String8(st)); // seed from shipped defaults
appSetup.configFile:=st;
end;
// Config problems are not fatal. A missing file: the defaults are used, the first save
// creates it. A broken file: the defaults, a toast, and the file is not overwritten
if not Files.Exists(String8(appSetup.configFile)) then
ReportConfigProblem('Config file not found: '+String8(appSetup.configFile)+'; defaults are used');
appConfig:=TConfig.Create(appSetup.configFile,true);
LoadOptions;
SaveOptions; // Save modified settings (if default values were added)
end;
for i:=1 to paramCount do HandleParam(paramstr(i));
{$IFDEF MSWINDOWS}
if HasParam('-SDL') then begin
requestBackend.platform:=spSDL;
Log.Force('SDL platform requested by a command line parameter');
end;
if HasParam('-WINDOWS') then begin
requestBackend.platform:=spWindows;
Log.Force('Windows platform requested by a command line parameter');
end;
st:=UpperCase(GetParam('-PLATFORM'));
if st='SDL' then begin
requestBackend.platform:=spSDL;
Log.Force('SDL platform requested by -PLATFORM=SDL');
end else
if (st='WINDOWS') or (st='WIN') then begin
requestBackend.platform:=spWindows;
Log.Force('Windows platform requested by -PLATFORM='+st);
end;
{$ENDIF}
usedPlatform:=requestBackend.platform;
{$IFDEF MSWINDOWS}
if usedPlatform=spDefault then usedPlatform:=spWindows;
if usedPlatform=spWindows then sysPlatform:=TWindowsPlatform.Create;
{$ELSE}
if usedPlatform=spWindows then raise EFatalError.Create('Ooops! Windows platform on a non-windows system!');
{$ENDIF}
{$IFDEF UNIX}
if usedPlatform=spDefault then usedPlatform:=spSDL;
{$ENDIF}
if usedPlatform=spSDL then begin
{$IFDEF SDL}
sysPlatform:=TSDLPlatform.Create;
{$ELSE}
raise EError.Create('Define SDL'); // Define SDL symbol to add SDL support
{$ENDIF}
end;
if sysPlatform=nil then raise EFatalError.Create('No platform interface');
case usedPlatform of
spWindows:Log.Msg('Platform backend: Windows');
spSDL:Log.Msg('Platform backend: SDL');
else
Log.Msg('Platform backend id: '+IntToStr(ord(usedPlatform)));
end;
sysPlatform.GetScreenSize(screenWidth,screenHeight);
sysPlatform.GetRealScreenSize(realScreenWidth,realScreenHeight);
{$IFDEF OPENGL}
Apus.Engine.Game.useDepthTexture:=renderSetup.depthTexture;
{$ENDIF}
{$IFDEF STEAM}
if checkForSteam and Steam.Init then
// first launch after a Steam install: take the language chosen in Steam
if Files.Exists('SelectLang') then begin
if Steam.gameLanguage.Same('russian') then gameLangCode:='ru';
if Steam.gameLanguage.Same('english') then gameLangCode:='en';
Log.Msg('First time launch: Steam language is '+gameLangCode);
SaveOptions;
Files.Delete('SelectLang');
end;
{$ENDIF}
except
on e:exception do begin
Log.Force('AppCreate error: '+ExceptionMsg(e));
SystemMessage('Fatal error: '#13#10+ExceptionMsg(e));
halt;
end;
end;
end;
procedure TGameApplication.InitSound;
begin
Signal('GAMEAPP\InitSound');
try
// slDefault picks whichever backend is compiled in (see defines.inc)
sound.Init(slDefault,mainWindow.GetHandle);
except
on e:Exception do begin
Log.Force('Sound initialization failed. Continue without sound. '+e.message);
ShowMessage('No sound available. See log for details.'#13#10'Press OK to continue without sound.','Sound system error');
end;
end;
end;
procedure EngineEventHandler(event:TEventStr;tag:TTag);
var
wnd:TWindow;
begin
if app=nil then exit;
if event='ENGINE\SURFACECHANGED' then begin
wnd:=TWindow(UIntPtr(tag));
// Startup values are applied by SetupGameSettings/SetupHighDPI: text and UI
// subsystems don't exist yet during the first rebuild.
if (wnd<>nil) and (game<>nil) and game.running and
(TSurfaceChange.dpi in wnd.surface.changes) then begin
deviceDPI:=wnd.surface.dpi;
deviceScale:=deviceDPI/96;
app.SetupHighDPI;
ApplyDefaultUIScale(wnd); // not before: SetupHighDPI sets the scale for the new DPI
app.SelectFonts;
end;
app.onResize; // after the rebuild: sizes are already final
end;
end;
procedure TGameApplication.Run;
var
settings:TGameSettings;
usedAPI:TGraphicsAPI;
begin
{$IFDEF OPENGL}
// OpenGL context request is configured on app level and used by platform backend.
oglContextTemplate.minMajor:=requestGL.minMajor;
oglContextTemplate.minMinor:=requestGL.minMinor;
oglContextTemplate.preferHighest:=requestGL.preferHighest;
oglContextTemplate.debugContext:=requestGL.debugContext or debugMode;
oglContextTemplate.forwardCompatible:=requestGL.forwardCompatible;
oglContextTemplate.baseline:=requestGL.baseline;
{$IFDEF GLES}
oglContextTemplate.profile:=oglpES; // GLES builds always use the ES profile, coreContext is ignored
{$ELSE}
if requestGL.coreContext then
oglContextTemplate.profile:=oglpCore
else
oglContextTemplate.profile:=oglpCompatibility;
{$ENDIF}
{$ENDIF}
// CREATE GAME OBJECT
// ------------------------
usedAPI:=requestBackend.graphicsAPI;
{$IFDEF MSWINDOWS}
if usedAPI=gaAuto then begin
{$IFDEF OPENGL}
usedAPI:=gaOpenGL2
{$ENDIF}
end;
{$ENDIF}
{$IFDEF OPENGL}
if usedAPI=gaOpenGL2 then
game:=TGame.Create(sysPlatform,TOpenGL.Create);
{$ENDIF}
if game=nil then raise EFatalError.Create('Game object not created!');
surfaceConfigHook:=ConfigureSurface; // called on every surface rebuild
// CONFIGURE GAME OBJECT
// ------------------------
SetupGameSettings(settings);
game.SetSettings(settings);
if settings.mode<>TDisplayMode.dmSwitchResolution then
Log.Force('Running in cooperative mode')
else
Log.Force('Running in exclusive mode');
SetEventHandler('ENGINE',EngineEventHandler);
// LAUNCH GAME OBJECT
// ------------------------
{$IFDEF IOS}
// UIKit owns the main thread's run loop, so Run() must NOT block. game.Run
// sets everything up (useMainThread=false → InitMainLoop runs synchronously)
// and returns; the shell then drives frames via the display-link callback.
// Scene setup and the idle loop run on a control thread, as on macOS.
game.Run;
controlThread:=Apus.Threads.Thread.Start('ControlThread',ControlLoop);
{$ELSE}
{$IFDEF DARWIN}
controlThread:=Apus.Threads.Thread.Start('ControlThread',ControlLoop);
try
TGame(game).RunCurrentThread;
finally
controlThread.Terminate;
controlThread.Wait(2000);
controlThread:=nil;
end;
{$ELSE}
try
game.Run;
except
on e:exception do begin
SystemMessage('Failed to run the game: '+ExceptionMsg(e));
halt;
end;
end;
ControlLoop;
{$ENDIF}
{$ENDIF} // IOS
end;
procedure TGameApplication.ControlLoop;
var
{$IFDEF DARWIN}
i:integer;
{$ENDIF}
loadingScene:TGameScene;
begin
{$IFDEF DARWIN}
for i:=1 to 400 do begin
if game.running then break;
if CurrentThread.Terminating then exit;
CoreTime.Sleep(50);
end;
if not game.running then exit;
try
{$ENDIF}
Log.Force('RUN');
// Transitional compatibility: control thread also needs current window context
// for scene/UI setup that still happens here.
if window=nil then window:=mainWindow;
SetupHighDPI;
// LOADER SCENE
// ------------------------
if startupScenes.loader then begin
loadingScene:=TLoadingScene.Create;
game.AddScene(loadingScene);
end;
// More initialization
InitSound;
InitCursors;
LoadFonts;
SelectFonts;