-
-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathbgmod.lpr
More file actions
1327 lines (1213 loc) · 46.4 KB
/
Copy pathbgmod.lpr
File metadata and controls
1327 lines (1213 loc) · 46.4 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
program bgmod;
{$mode objfpc}{$H+}
uses
Classes, SysUtils, IniFiles, Process, BaseUnix, Unix;
function CopyFile(const Src, Dst: string): Boolean;
var
SrcStream, DstStream: TFileStream;
begin
Result := False;
try
SrcStream := TFileStream.Create(Src, fmOpenRead or fmShareDenyWrite);
try
DstStream := TFileStream.Create(Dst, fmCreate);
try
DstStream.CopyFrom(SrcStream, SrcStream.Size);
Result := True;
finally
DstStream.Free;
end;
finally
SrcStream.Free;
end;
except
// ignore copy failures
end;
end;
function execvp(file_: PChar; argv: PPChar): Integer; cdecl; external 'c' name 'execvp';
function execvpe(file_: PChar; argv: PPChar; envp: PPChar): Integer; cdecl; external 'c' name 'execvpe';
procedure SetEnvVarInList(EnvStrings: TStringList; const AKey, AVal: string);
var
idx: Integer;
Prefix: string;
begin
Prefix := AKey + '=';
for idx := 0 to EnvStrings.Count - 1 do
begin
if Pos(Prefix, EnvStrings[idx]) = 1 then
begin
EnvStrings[idx] := Prefix + AVal;
Exit;
end;
end;
EnvStrings.Add(Prefix + AVal);
end;
function GetEnvVarFromList(EnvStrings: TStringList; const AKey: string): string;
var
idx: Integer;
Prefix: string;
begin
Prefix := AKey + '=';
for idx := 0 to EnvStrings.Count - 1 do
begin
if Pos(Prefix, EnvStrings[idx]) = 1 then
begin
Result := Copy(EnvStrings[idx], Length(Prefix) + 1, MaxInt);
Exit;
end;
end;
Result := '';
end;
var
GameDir: string;
CentralLogDir: string;
CentralLogFile: string;
BgmodPath: string;
ConfigDir: string;
SourceDir: string;
procedure Log(const Msg: string);
var
F: TextFile;
LogMsg: string;
begin
LogMsg := FormatDateTime('yyyy-MM-dd hh:nn:ss', Now) + ' - ' + Msg;
WriteLn(LogMsg);
// Append to /tmp/bgmod.log
try
AssignFile(F, '/tmp/bgmod.log');
if FileExists('/tmp/bgmod.log') then
Append(F)
else
Rewrite(F);
WriteLn(F, LogMsg);
CloseFile(F);
except
// ignore logging failures
end;
// Append to game directory bgmod.log if resolved
if GameDir <> '' then
begin
try
AssignFile(F, IncludeTrailingPathDelimiter(GameDir) + 'bgmod.log');
if FileExists(IncludeTrailingPathDelimiter(GameDir) + 'bgmod.log') then
Append(F)
else
Rewrite(F);
WriteLn(F, LogMsg);
CloseFile(F);
except
// ignore logging failures
end;
end;
// Append to central GOverlay logs directory if resolved
if CentralLogFile <> '' then
begin
try
if not DirectoryExists(CentralLogDir) then
ForceDirectories(CentralLogDir);
AssignFile(F, CentralLogFile);
if FileExists(CentralLogFile) then
Append(F)
else
Rewrite(F);
WriteLn(F, LogMsg);
CloseFile(F);
except
// ignore logging failures
end;
end;
end;
function GetCommandOutput(const Cmd: string): string;
var
Proc: TProcess;
List: TStringList;
begin
Result := '';
Proc := TProcess.Create(nil);
List := TStringList.Create;
try
Proc.Executable := '/bin/sh';
Proc.Parameters.Add('-c');
Proc.Parameters.Add(Cmd);
Proc.Options := [poUsePipes, poWaitOnExit];
Proc.Execute;
List.LoadFromStream(Proc.Output);
Result := Trim(List.Text);
except
on E: Exception do
Log('Error running shell command: ' + E.Message);
end;
List.Free;
Proc.Free;
end;
function FindUEShippingExe(const BaseDir: string; Depth: Integer): string;
var
SR: TSearchRec;
SearchPath, Res: string;
begin
Result := '';
if Depth > 4 then Exit;
if DirectoryExists(IncludeTrailingPathDelimiter(BaseDir) + 'Binaries' + PathDelim + 'Win64') then
begin
SearchPath := IncludeTrailingPathDelimiter(BaseDir) + 'Binaries' + PathDelim + 'Win64' + PathDelim + '*.exe';
if FindFirst(SearchPath, faAnyFile, SR) = 0 then
begin
try
repeat
if (SR.Attr and faDirectory) = 0 then
begin
Result := IncludeTrailingPathDelimiter(BaseDir) + 'Binaries' + PathDelim + 'Win64';
Break;
end;
until FindNext(SR) <> 0;
finally
FindClose(SR);
end;
if Result <> '' then Exit;
end;
end;
SearchPath := IncludeTrailingPathDelimiter(BaseDir) + '*';
if FindFirst(SearchPath, faDirectory, SR) = 0 then
begin
try
repeat
if (SR.Name <> '.') and (SR.Name <> '..') and ((SR.Attr and faDirectory) <> 0) then
begin
if (UpperCase(SR.Name) <> 'ENGINE') and
(UpperCase(SR.Name) <> 'BUGREPORTCLIENT') and
(UpperCase(SR.Name) <> 'CRASHREPORTCLIENT') then
begin
Res := FindUEShippingExe(IncludeTrailingPathDelimiter(BaseDir) + SR.Name, Depth + 1);
if Res <> '' then
begin
Result := Res;
Break;
end;
end;
end;
until FindNext(SR) <> 0;
finally
FindClose(SR);
end;
end;
end;
procedure CopyDirectory(const SrcDir, DestDir: string);
var
SR: TSearchRec;
SrcFile, DestFile: string;
begin
if not DirectoryExists(DestDir) then
ForceDirectories(DestDir);
if FindFirst(IncludeTrailingPathDelimiter(SrcDir) + '*', faAnyFile, SR) = 0 then
begin
try
repeat
if (SR.Name <> '.') and (SR.Name <> '..') then
begin
SrcFile := IncludeTrailingPathDelimiter(SrcDir) + SR.Name;
DestFile := IncludeTrailingPathDelimiter(DestDir) + SR.Name;
if (SR.Attr and faDirectory) <> 0 then
CopyDirectory(SrcFile, DestFile)
else
begin
try
if FileExists(DestFile) then
DeleteFile(DestFile);
CopyFile(SrcFile, DestFile);
// Ensure permissions are copied
fpChmod(DestFile, &755);
except
on E: Exception do
Log('Failed to copy file ' + SrcFile + ' -> ' + DestFile + ': ' + E.Message);
end;
end;
end;
until FindNext(SR) <> 0;
finally
FindClose(SR);
end;
end;
end;
function GetGlobalBGModPath(const LocalBgmodPath: string): string;
var
DataHome: string;
PosFlatpak: Integer;
FlatpakBase: string;
Ini: TIniFile;
IsStable: Boolean;
ChannelFolder: string;
begin
IsStable := True;
if FileExists(IncludeTrailingPathDelimiter(LocalBgmodPath) + 'bgmod.conf') then
begin
Ini := TIniFile.Create(IncludeTrailingPathDelimiter(LocalBgmodPath) + 'bgmod.conf');
try
IsStable := Ini.ReadInteger('Config', 'OPT_CHANNEL', 0) <> 1;
finally
Ini.Free;
end;
end;
if IsStable then
ChannelFolder := 'optiscaler-stable'
else
ChannelFolder := 'optiscaler-edge';
PosFlatpak := Pos('io.github.benjamimgois.goverlay', LocalBgmodPath);
if PosFlatpak > 0 then
begin
FlatpakBase := Copy(LocalBgmodPath, 1, PosFlatpak + Length('io.github.benjamimgois.goverlay'));
Result := IncludeTrailingPathDelimiter(FlatpakBase) + 'data' + PathDelim + 'goverlay' + PathDelim + ChannelFolder;
end
else
begin
DataHome := GetEnvironmentVariable('XDG_DATA_HOME');
if DataHome = '' then
DataHome := GetUserDir + '.local/share';
Result := IncludeTrailingPathDelimiter(DataHome) + 'goverlay' + PathDelim + ChannelFolder;
end;
Result := IncludeTrailingPathDelimiter(Result);
end;
// Compare specific keys between two goverlay.vars files.
// ignoreFsrVersion=True -> only OptiScalerVersion/FakeNVAPI (cache sync check)
// ignoreFsrVersion=False -> also includes fsrversion (GameDir freshness check)
function NeedsUpdateWithKeys(const LocalPath, GlobalPath: string; IgnoreFsrVersion: Boolean): Boolean;
var
LocalVars, GlobalVars: string;
LocalSL, GlobalSL: TStringList;
LocalVal, GlobalVal: string;
VersionKeys: array[0..2] of string = ('optiscalerversion', 'fakenvapiversion', 'fsrversion');
k, LastKey: Integer;
function GetValFromList(SL: TStringList; const AKey: string): string;
var
j, sp: Integer;
ln, k2: string;
begin
Result := '';
for j := 0 to SL.Count - 1 do
begin
ln := Trim(SL[j]);
sp := Pos('=', ln);
if sp > 0 then
begin
k2 := Trim(Copy(ln, 1, sp - 1));
if SameText(k2, AKey) then
begin
Result := Trim(Copy(ln, sp + 1, Length(ln)));
Exit;
end;
end;
end;
end;
begin
Result := False;
LocalVars := IncludeTrailingPathDelimiter(LocalPath) + 'goverlay.vars';
GlobalVars := IncludeTrailingPathDelimiter(GlobalPath) + 'goverlay.vars';
if not FileExists(GlobalVars) then Exit;
if not FileExists(LocalVars) then
begin
Result := True;
Exit;
end;
// When ignoring fsrversion (cache sync), only compare the first 2 keys.
if IgnoreFsrVersion then
LastKey := 1
else
LastKey := 2;
LocalSL := TStringList.Create;
GlobalSL := TStringList.Create;
try
try
LocalSL.LoadFromFile(LocalVars);
GlobalSL.LoadFromFile(GlobalVars);
for k := 0 to LastKey do
begin
LocalVal := GetValFromList(LocalSL, VersionKeys[k]);
GlobalVal := GetValFromList(GlobalSL, VersionKeys[k]);
if LocalVal <> GlobalVal then
begin
Result := True;
Exit;
end;
end;
except
on E: Exception do
Log('Error loading vars files for comparison: ' + E.Message);
end;
finally
LocalSL.Free;
GlobalSL.Free;
end;
end;
// Cache → ConfigDir: ignore fsrversion (user preference, not a version change)
function NeedsLocalUpdate(const LocalPath, GlobalPath: string): Boolean;
begin
Result := NeedsUpdateWithKeys(LocalPath, GlobalPath, True);
end;
// ConfigDir → GameDir: include fsrversion so an INT8/Latest change triggers reinstall
function NeedsGameDirUpdate(const LocalPath, GlobalPath: string): Boolean;
begin
Result := NeedsUpdateWithKeys(LocalPath, GlobalPath, False);
end;
// Marker-based ownership check.
// A proxy DLL is GOverlay-owned when its name is a known GOverlay proxy DLL
// (per IsProxyDllName) and a goverlay.vars marker file exists in the same
// directory. The goverlay.vars marker is written by this installer (see the
// install block, which ends with SafeCopyFile(ConfigDir + 'goverlay.vars',
// ...)) and is therefore a channel-agnostic signature that GOverlay placed
// the DLLs there, regardless of whether OptiScaler was installed on the
// stable or bleeding-edge channel. This replaces the previous file-size
// comparison against bgmod/renames/<name>.dll / bgmod/OptiScaler.dll, which
// only matched the stable template and silently failed for bleeding-edge
// installs whose DLL has a different size, leaving proxy DLLs behind during
// the disabled-cleanup path here and during uninstaller runs.
function IsProxyDllName(const FileName: string): Boolean; forward;
function IsGOverlayProxyFile(const TargetDir, FileName: string): Boolean;
begin
Result := False;
if not IsProxyDllName(FileName) then Exit;
Result := FileExists(IncludeTrailingPathDelimiter(TargetDir) + 'goverlay.vars');
end;
function IsProxyDllName(const FileName: string): Boolean;
begin
Result := SameText(FileName, 'dxgi.dll') or
SameText(FileName, 'winmm.dll') or
SameText(FileName, 'dbghelp.dll') or
SameText(FileName, 'version.dll') or
SameText(FileName, 'wininet.dll') or
SameText(FileName, 'winhttp.dll');
end;
procedure CopyDirectoryFiltered(const SrcDir, DestDir: string);
var
SR: TSearchRec;
SrcFile, DestFile: string;
begin
if not DirectoryExists(DestDir) then
ForceDirectories(DestDir);
if FindFirst(IncludeTrailingPathDelimiter(SrcDir) + '*', faAnyFile, SR) = 0 then
begin
try
repeat
if (SR.Name <> '.') and (SR.Name <> '..') then
begin
if (UpperCase(SR.Name) = 'BGMOD.CONF') or (UpperCase(SR.Name) = 'OPTISCALER.INI') then
Continue;
SrcFile := IncludeTrailingPathDelimiter(SrcDir) + SR.Name;
DestFile := IncludeTrailingPathDelimiter(DestDir) + SR.Name;
if (SR.Attr and faDirectory) <> 0 then
CopyDirectoryFiltered(SrcFile, DestFile)
else
begin
try
if FileExists(DestFile) then
DeleteFile(DestFile);
CopyFile(SrcFile, DestFile);
fpChmod(DestFile, &755);
except
on E: Exception do
Log('Failed to copy file ' + SrcFile + ' -> ' + DestFile + ': ' + E.Message);
end;
end;
end;
until FindNext(SR) <> 0;
finally
FindClose(SR);
end;
end;
end;
// Reads a key=value pair from a flat text vars file.
// Returns empty string if not found.
function ReadVarFromFile(const FilePath, Key: string): string;
var
SL: TStringList;
i, SepPos: Integer;
Line, K, V: string;
begin
Result := '';
if not FileExists(FilePath) then Exit;
SL := TStringList.Create;
try
SL.LoadFromFile(FilePath);
for i := 0 to SL.Count - 1 do
begin
Line := Trim(SL[i]);
SepPos := Pos('=', Line);
if SepPos > 0 then
begin
K := Trim(Copy(Line, 1, SepPos - 1));
V := Trim(Copy(Line, SepPos + 1, Length(Line)));
if SameText(K, Key) then
begin
Result := V;
Exit;
end;
end;
end;
finally
SL.Free;
end;
end;
// After CopyDirectoryFiltered syncs the cache to ConfigDir, this restores
// the correct FSR DLL in ConfigDir based on the saved fsrversion value.
// This ensures the subsequent copy to GameDir picks the right DLL.
procedure RestoreFsrDllInConfigDir(const AConfigDir, ASourceDir: string);
var
FsrVer, SrcDll, DestDll: string;
begin
FsrVer := ReadVarFromFile(IncludeTrailingPathDelimiter(AConfigDir) + 'goverlay.vars', 'fsrversion');
if (FsrVer = '4.0.2c INT8') or (FsrVer = '4.0.2c (INT8)') then
begin
SrcDll := IncludeTrailingPathDelimiter(ASourceDir) + 'FSR4_INT8' + PathDelim + 'amd_fidelityfx_upscaler_dx12.dll';
DestDll := IncludeTrailingPathDelimiter(AConfigDir) + 'amd_fidelityfx_upscaler_dx12.dll';
if FileExists(SrcDll) then
begin
Log('Restoring FSR4 INT8 DLL in config dir after sync.');
if FileExists(DestDll) then DeleteFile(DestDll);
CopyFile(SrcDll, DestDll);
end
else
Log('Warning: FSR4_INT8 DLL not found at: ' + SrcDll);
end;
end;
procedure SafeCopyFile(const Src, Dest: string);
begin
if not FileExists(Src) then
begin
Log('Warning: Source file ' + Src + ' does not exist, skipping copy');
Exit;
end;
try
ForceDirectories(ExtractFilePath(Dest));
if FileExists(Dest) then
DeleteFile(Dest);
if CopyFile(Src, Dest) then
begin
fpChmod(Dest, &755);
Log('Successfully copied: ' + Src + ' -> ' + Dest);
end
else
Log('Failed to copy: ' + Src + ' -> ' + Dest);
except
on E: Exception do
Log('Exception copying ' + Src + ' -> ' + Dest + ': ' + E.Message);
end;
end;
procedure SyncOptiScalerIni(const AConfigDir, AGameDir: string; APreserveIni: Boolean);
var
ConfigIni, GameIni: string;
AgeConfig, AgeGame: TDateTime;
begin
ConfigIni := IncludeTrailingPathDelimiter(AConfigDir) + 'OptiScaler.ini';
GameIni := IncludeTrailingPathDelimiter(AGameDir) + 'OptiScaler.ini';
if not FileExists(ConfigIni) then Exit;
if not FileExists(GameIni) then
begin
Log('OptiScaler.ini not found in game directory. Copying from config...');
SafeCopyFile(ConfigIni, GameIni);
end
else if not APreserveIni then
begin
Log('PreserveIni is false. Overwriting OptiScaler.ini in game directory...');
SafeCopyFile(ConfigIni, GameIni);
end
else
begin
if FileAge(ConfigIni, AgeConfig) and FileAge(GameIni, AgeGame) then
begin
if AgeConfig > AgeGame then
begin
Log('GOverlay configuration is newer than game directory config. Syncing OptiScaler.ini...');
SafeCopyFile(ConfigIni, GameIni);
end
else
Log('Preserved existing OptiScaler.ini (game directory file is up-to-date or modified in-game).');
end;
end;
end;
procedure SafeDeleteFile(const Path: string);
begin
if not FileExists(Path) then Exit;
try
if DeleteFile(Path) then
Log('Cleaned up file: ' + Path)
else
Log('Failed to delete file: ' + Path);
except
on E: Exception do
Log('Exception deleting ' + Path + ': ' + E.Message);
end;
end;
procedure SafeDeleteDirectory(const Path: string);
var
SR: TSearchRec;
FileP: string;
begin
if not DirectoryExists(Path) then Exit;
if FindFirst(IncludeTrailingPathDelimiter(Path) + '*', faAnyFile, SR) = 0 then
begin
try
repeat
if (SR.Name <> '.') and (SR.Name <> '..') then
begin
FileP := IncludeTrailingPathDelimiter(Path) + SR.Name;
if (SR.Attr and faDirectory) <> 0 then
SafeDeleteDirectory(FileP)
else
SafeDeleteFile(FileP);
end;
until FindNext(SR) <> 0;
finally
FindClose(SR);
end;
end;
try
if RemoveDir(Path) then
Log('Removed directory: ' + Path)
else
Log('Failed to remove directory: ' + Path);
except
on E: Exception do
Log('Exception removing directory ' + Path + ': ' + E.Message);
end;
end;
procedure CleanDirectory(const SrcDir, DestDir: string);
var
SR: TSearchRec;
SrcFile, DestFile: string;
begin
if not DirectoryExists(SrcDir) or not DirectoryExists(DestDir) then Exit;
if FindFirst(IncludeTrailingPathDelimiter(SrcDir) + '*', faAnyFile, SR) = 0 then
begin
try
repeat
if (SR.Name <> '.') and (SR.Name <> '..') then
begin
SrcFile := IncludeTrailingPathDelimiter(SrcDir) + SR.Name;
DestFile := IncludeTrailingPathDelimiter(DestDir) + SR.Name;
if (SR.Attr and faDirectory) <> 0 then
begin
CleanDirectory(SrcFile, DestFile);
RemoveDir(DestFile);
end
else
begin
if FileExists(DestFile) then
SafeDeleteFile(DestFile);
end;
end;
until FindNext(SR) <> 0;
finally
FindClose(SR);
end;
end;
end;
// Restore an original DLL from the per-game backup folder, or fall through to
// the marker-based delete if no backup exists. The in-GameDir `<file>.b`
// mechanism is gone — backups now live in BackupsDir (outside GameDir) so
// they cannot be corrupted by reinstalls or Steam "Verify integrity".
procedure SafeCleanOrRestore(const TargetDir, BackupsDir, FileName: string; IsOriginalGameFile: Boolean);
var
FullFile, FullBackup: string;
begin
FullFile := IncludeTrailingPathDelimiter(TargetDir) + FileName;
FullBackup := IncludeTrailingPathDelimiter(BackupsDir) + FileName;
if FileExists(FullBackup) then
begin
try
if FileExists(FullFile) then
DeleteFile(FullFile);
if CopyFile(FullBackup, FullFile) then
begin
Log('Restored original ' + FileName + ' from ' + BackupsDir);
DeleteFile(FullBackup);
end
else
Log('Failed to restore ' + FileName + ' from backup');
except
on E: Exception do
Log('Exception restoring ' + FileName + ': ' + E.Message);
end;
end
else if not IsOriginalGameFile then
begin
if IsProxyDllName(FileName) then
begin
if IsGOverlayProxyFile(TargetDir, FileName) then
SafeDeleteFile(FullFile)
else
Log('Skipping deletion of third-party proxy DLL: ' + FullFile);
end
else
SafeDeleteFile(FullFile);
end;
end;
// Back up the genuine original DLL from GameDir into the per-game backup
// folder, never inside GameDir. The backup is only written on the first
// install for this game (when goverlay.vars is NOT yet present in GameDir),
// and only if the destination slot is empty. This double guard prevents the
// reinstall-corruption bug where a previously-installed GOverlay proxy
// (sitting in GameDir/<name> on the second install) would be backed up as
// "original" — because on reinstall, goverlay.vars already exists, so this
// function becomes a no-op and the original captured on the first install
// (or nothing, when the game shipped no such DLL) stays intact in
// BackupsDir. Uses CopyFile (not Rename) so the GameDir file is left in
// place for the subsequent overwrite by the proxy install step.
procedure SafeBackupFile(const GameDir, BackupsDir, DllFile: string);
var
FullSrc, FullDest: string;
begin
FullSrc := IncludeTrailingPathDelimiter(GameDir) + DllFile;
FullDest := IncludeTrailingPathDelimiter(BackupsDir) + DllFile;
if not FileExists(FullSrc) then Exit;
if FileExists(IncludeTrailingPathDelimiter(GameDir) + 'goverlay.vars') then
begin
Log('Skipping backup of ' + DllFile + ' (game already has GOverlay install)');
Exit;
end;
if FileExists(FullDest) then
begin
Log('Skipping backup of ' + DllFile + ' (backup slot already filled)');
Exit;
end;
try
if CopyFile(FullSrc, FullDest) then
Log('Backed up original ' + DllFile + ' -> ' + BackupsDir + DllFile)
else
Log('Failed to backup ' + DllFile);
except
on E: Exception do
Log('Exception backing up ' + DllFile + ': ' + E.Message);
end;
end;
procedure ResolveGameDirectory;
var
Arg, ExePath, LutrisId, Cmd: string;
i, j, PosPipe: Integer;
LauncherIni: TIniFile;
LauncherList: TStringList;
KeyLine, KeyName, EntryVal, TargetSub, Repl, CleanKey: string;
begin
GameDir := '';
// 1. Check command line arguments for .exe
for i := 1 to ParamCount do
begin
Arg := ParamStr(i);
if LowerCase(ExtractFileExt(Arg)) = '.exe' then
begin
// Game launcher replacements
LauncherList := TStringList.Create;
LauncherIni := nil;
try
if FileExists(ExtractFilePath(ParamStr(0)) + 'bgmod.conf') then
begin
LauncherIni := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'bgmod.conf');
LauncherIni.ReadSectionValues('Launchers', LauncherList);
end;
if LauncherList.Count = 0 then
begin
LauncherList.Add('Cyberpunk 2077=REDprelauncher.exe|bin/x64/Cyberpunk2077.exe');
LauncherList.Add('Witcher 3=REDprelauncher.exe|bin/x64_dx12/witcher3.exe');
LauncherList.Add('Baldurs Gate 3=Launcher/LariLauncher.exe|bin/bg3_dx11.exe');
LauncherList.Add('Baldurs Gate 3 Alt=Launcher\LariLauncher.exe|bin/bg3_dx11.exe');
LauncherList.Add('HITMAN 3=Launcher.exe|Retail/HITMAN3.exe');
LauncherList.Add('HITMAN World of Assassination=Launcher.exe|Retail/HITMAN3.exe');
LauncherList.Add('SYNCED=Launcher/sop_launcher.exe|SYNCED.exe');
LauncherList.Add('2KLauncher=2KLauncher/LauncherPatcher.exe|DoesntMatter.exe');
LauncherList.Add('Warhammer 40,000 DARKTIDE=launcher/Launcher.exe|binaries/Darktide.exe');
LauncherList.Add('Warhammer Vermintide 2=launcher/Launcher.exe|binaries_dx12/vermintide2_dx12.exe');
LauncherList.Add('Satisfactory=FactoryGameSteam.exe|Engine/Binaries/Win64/FactoryGameSteam-Win64-Shipping.exe');
LauncherList.Add('FINAL FANTASY XIV Online=boot/ffxivboot.exe|game/ffxiv_dx11.exe');
LauncherList.Add('DuneAwakening=Launcher/FuncomLauncher.exe|DuneSandbox/Binaries/Win64/DuneSandbox-Win64-Shipping.exe');
end;
for j := 0 to LauncherList.Count - 1 do
begin
KeyLine := LauncherList[j];
PosPipe := Pos('=', KeyLine);
if PosPipe > 0 then
begin
KeyName := Trim(Copy(KeyLine, 1, PosPipe - 1));
CleanKey := KeyName;
if Pos(' Alt', CleanKey) > 0 then
CleanKey := Copy(CleanKey, 1, Pos(' Alt', CleanKey) - 1);
if Pos(' alt', CleanKey) > 0 then
CleanKey := Copy(CleanKey, 1, Pos(' alt', CleanKey) - 1);
EntryVal := Trim(Copy(KeyLine, PosPipe + 1, MaxInt));
PosPipe := Pos('|', EntryVal);
if PosPipe > 0 then
begin
TargetSub := Trim(Copy(EntryVal, 1, PosPipe - 1));
Repl := Trim(Copy(EntryVal, PosPipe + 1, MaxInt));
if (Pos(CleanKey, Arg) > 0) and (Pos(TargetSub, Arg) > 0) then
begin
Arg := StringReplace(Arg, TargetSub, Repl, [rfReplaceAll, rfIgnoreCase]);
Break;
end;
end;
end;
end;
finally
if Assigned(LauncherIni) then
LauncherIni.Free;
LauncherList.Free;
end;
GameDir := ExtractFilePath(Arg);
Log('Resolved GameDir from argument: ' + GameDir);
Break;
end;
end;
// 2. Check command line arguments for Lutris game run ID
if GameDir = '' then
begin
for i := 1 to ParamCount do
begin
Arg := ParamStr(i);
if Pos('lutris:rungameid/', Arg) = 1 then
begin
LutrisId := Copy(Arg, Length('lutris:rungameid/') + 1, MaxInt);
Log('Detected Lutris game ID: ' + LutrisId);
Cmd := 'lutris_id=' + LutrisId + '; slug=$(lutris --list-games --json 2>/dev/null | jq -r ".[] | select(.id == $lutris_id) | .slug"); [ -n "$slug" ] && config_file=$(find ~/.config/lutris/games/ -iname "${slug}-*.yml" | head -1); [ -n "$config_file" ] && grep -E "^\s*exe:" "$config_file" | sed "s/.*exe:[[:space:]]*//"';
ExePath := GetCommandOutput(Cmd);
if ExePath <> '' then
begin
GameDir := ExtractFilePath(ExePath);
Log('Resolved Lutris GameDir: ' + GameDir);
end
else
Log('Failed to resolve Lutris slug or game configuration file');
Break;
end;
end;
end;
// 3. Check STEAM_COMPAT_INSTALL_PATH fallback
if GameDir = '' then
begin
GameDir := GetEnvironmentVariable('STEAM_COMPAT_INSTALL_PATH');
if GameDir <> '' then
Log('Resolved GameDir from STEAM_COMPAT_INSTALL_PATH: ' + GameDir);
end;
// 4. Unreal Engine subfolder resolution
if (GameDir <> '') and DirectoryExists(IncludeTrailingPathDelimiter(GameDir) + 'Engine') then
begin
Log('UE Engine folder detected, searching for shipping executable...');
ExePath := FindUEShippingExe(GameDir, 1);
if ExePath <> '' then
begin
GameDir := ExePath;
Log('Adjusted UE GameDir: ' + GameDir);
end;
end;
end;
var
DllName, DllBase, CurrentOverrides, NewOverrides, TempStr, GlobalBgmodPath: string;
GOverlayMangoHud, GOverlayVkBasalt, GOverlayOptiscaler, GOverlayTweaks, PreserveIni: Boolean;
Ini: TIniFile;
EnvList, EnvStrings: TStringList;
BackupsDir: string;
IsPerGameProfile: Boolean;
i, p, StartArgIdx, EnvCount: Integer;
Key, Val, Line: string;
EnvArgs: array of PChar;
Args: array of PChar;
ArgsStrings: array of string;
OrigDlls: array[0..13] of string = (
'd3dcompiler_47.dll',
'amd_fidelityfx_dx12.dll',
'amd_fidelityfx_loader_dx12.dll',
'amd_fidelityfx_framegeneration_dx12.dll',
'amd_fidelityfx_upscaler_dx12.dll',
'amd_fidelityfx_vk.dll',
'libxess.dll',
'libxess_dx11.dll',
'libxess_fg.dll',
'libxell.dll',
'nvngx.dll',
'nvngx_dlss.dll',
'nvngx_dlssd.dll',
'nvngx_dlssg.dll'
);
ProxyDlls: array[0..6] of string = (
'dxgi.dll',
'winmm.dll',
'dbghelp.dll',
'version.dll',
'wininet.dll',
'winhttp.dll',
'd3d12.dll'
);
{$if defined(CPUAARCH64) and defined(LINUX)}
procedure Dummy_libc_csu_init; cdecl; public name '__libc_csu_init';
begin
end;
procedure Dummy_libc_csu_fini; cdecl; public name '__libc_csu_fini';
begin
end;
{$endif}
begin
BgmodPath := ExtractFilePath(ParamStr(0));
// Resolve central GOverlay log path
CentralLogDir := '';
CentralLogFile := '';
if BgmodPath <> '' then
begin
TempStr := ExcludeTrailingPathDelimiter(BgmodPath);
Key := ExtractFileName(TempStr); // GameName or 'bgmod'
Val := ExtractFilePath(TempStr); // Parent folder path (e.g. gameconfig/ or share/goverlay/)
ConfigDir := BgmodPath;
if LowerCase(Key) = 'bgmod' then
begin
// Global mode: ConfigDir = gameconfig/global/ (full copy of bgmod/ with user configs)
ConfigDir := IncludeTrailingPathDelimiter(Val) + 'gameconfig' + PathDelim + 'global' + PathDelim;
// SourceDir: prefer gameconfig/global/ if it has DLLs, otherwise fall back to bgmod/
if FileExists(ConfigDir + 'OptiScaler.dll') then
SourceDir := ConfigDir
else
SourceDir := BgmodPath;
end
else
begin
SourceDir := GetGlobalBGModPath(BgmodPath);
if SourceDir = '' then
SourceDir := BgmodPath;
end;
// Resolve the per-game backup folder for original DLLs. It lives outside
// GameDir (in the per-game config dir) so it cannot be corrupted by
// repeated installs, channel switches, or Steam "Verify integrity". Only
// create the folder when running in per-game mode (Key <> 'bgmod'): in
// global-profile mode backups are skipped per design (collision risk
// across games; the legacy global flow did not back up reliably anyway).
IsPerGameProfile := LowerCase(Key) <> 'bgmod';
BackupsDir := ConfigDir + 'backups' + PathDelim;
if IsPerGameProfile and not DirectoryExists(BackupsDir) then
ForceDirectories(BackupsDir);
if Val <> '' then
begin
Line := ExtractFileName(ExcludeTrailingPathDelimiter(Val)); // 'gameconfig' or 'goverlay' or similar
CurrentOverrides := ExtractFilePath(ExcludeTrailingPathDelimiter(Val)); // GOverlay base path (e.g. ~/.local/share/goverlay/)
if LowerCase(Line) = 'gameconfig' then
begin
CentralLogDir := IncludeTrailingPathDelimiter(CurrentOverrides) + 'logs' + PathDelim + Key;
CentralLogFile := IncludeTrailingPathDelimiter(CentralLogDir) + 'bgmod.log';
end
else if LowerCase(Key) = 'bgmod' then
begin
CentralLogDir := IncludeTrailingPathDelimiter(Val) + 'logs';
CentralLogFile := IncludeTrailingPathDelimiter(CentralLogDir) + 'bgmod.log';
end;
end;
end;
// Default values
GOverlayMangoHud := False;
GOverlayVkBasalt := False;
GOverlayOptiscaler := False;
GOverlayTweaks := False;
DllName := 'dxgi.dll';
PreserveIni := True;
EnvList := TStringList.Create;
EnvStrings := TStringList.Create;
// Read configurations from bgmod.conf
if FileExists(ConfigDir + 'bgmod.conf') then
begin
Ini := TIniFile.Create(ConfigDir + 'bgmod.conf');
try
GOverlayMangoHud := Ini.ReadString('Config', 'GOVERLAY_MANGOHUD', '0') = '1';
GOverlayVkBasalt := Ini.ReadString('Config', 'GOVERLAY_VKBASALT', '0') = '1';
GOverlayOptiscaler := Ini.ReadString('Config', 'GOVERLAY_OPTISCALER', '0') = '1';
GOverlayTweaks := Ini.ReadString('Config', 'GOVERLAY_TWEAKS', '0') = '1';
DllName := Ini.ReadString('Config', 'DLL', 'dxgi.dll');
PreserveIni := Ini.ReadString('Config', 'PRESERVE_INI', 'true') = 'true';
Ini.ReadSectionValues('Env', EnvList);
finally
Ini.Free;
end;
end;