Repository navigation
Expand file tree
/
Copy pathbootstrap.ps1
More file actions
1767 lines (1575 loc) · 93.9 KB
/
Copy pathbootstrap.ps1
File metadata and controls
1767 lines (1575 loc) · 93.9 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
<#
.SYNOPSIS
Builds a clean working tree for Optimum (client fork):
1. Downloads the official VS Windows installer (vs_install_win-x64_*.exe).
2. Decompiles closed-source DLLs (VintagestoryLib.dll, Vintagestory.dll) with ILSpy.
3. Clones open-source Anego forks at pinned refs (and reference-only repos, if any).
4. Applies post-decompile fixups (csproj rewrites, ambiguity resolution, ref-casts,
GeneratedRegex, serialization metadata restoration, and the long tail of
ILSpy decompiler artifacts documented inline below).
5. Snapshots the post-fixup tree to .baseline/ (used by extract-patches.ps1/.sh).
6. Applies patches/ on top of build/{VintagestoryLib,Vintagestory} and the fork
working trees.
7. Copies sources/ (Optimum-original files) into the working tree.
This mirrors scripts/bootstrap.sh's architecture exactly (same build/ working
tree, same .baseline/ snapshot, same --directory=build patch targeting, same
exit-nonzero-on-patch-failure behavior) so the two scripts stay in lockstep.
Every fixup below is implemented natively in PowerShell (no perl/python3
dependency), since install-windows.ps1's headless pipeline only guarantees
.NET, Git, and Windows PowerShell 5.1 are present on the end user's machine.
This only reconstructs the dev tree. To build redistributable packages, run
scripts/package-all.ps1 (or `make package`) after `dotnet build`.
.PARAMETER Version
Vintage Story version. Default: 1.22.7.
.PARAMETER ClientArchive
Path to an existing Windows installer (.exe). If omitted, downloads from cdn.vintagestory.at.
Pass '__skip__' when the caller (install-windows.ps1) already placed .vanilla via junction.
.PARAMETER Refresh
Force re-extract, re-decompile, re-clone.
.EXAMPLE
.\scripts\bootstrap.ps1
.\scripts\bootstrap.ps1 -Refresh
.\scripts\bootstrap.ps1 -ClientArchive C:\Downloads\vs_install_win-x64_1.22.7.exe
#>
[CmdletBinding()]
param(
[string]$Version,
[string]$ClientArchive,
[switch]$Refresh
)
$ErrorActionPreference = 'Stop'
. "$PSScriptRoot/_exec.ps1"
# Explicit repository-path helper for cloned working trees (mirrors bootstrap.sh).
. "$PSScriptRoot/git-repository.ps1"
$repoRoot = Split-Path -Parent $PSScriptRoot
# A GIT_DIR inherited from the calling environment (some tools and shell rc
# files export it) overrides repository discovery for every git call below:
# the clone succeeds, then the very next `git` against that clone dies with
# "fatal: not in a git directory". Drop it, along with its siblings, so this
# script only ever talks to repositories it names explicitly.
foreach ($gitEnv in 'GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE') {
Remove-Item -Path "Env:$gitEnv" -ErrorAction SilentlyContinue
}
# Resolve VS version from forks.json if not passed explicitly.
if (-not $Version) {
$forksFile = Join-Path $repoRoot 'forks.json'
if (Test-Path $forksFile) { $Version = (Get-Content $forksFile -Raw | ConvertFrom-Json).vintageStoryVersion }
else { $Version = '1.22.7' }
}
$gitInstallUrl = 'https://git-scm.com/download/win'
$Utf8NoBom = New-Object System.Text.UTF8Encoding($false)
# ===========================================================================
# Helpers
# ===========================================================================
function Read-TextFile([string]$Path) {
return [System.IO.File]::ReadAllText($Path)
}
function Write-TextFile([string]$Path, [string]$Text) {
[System.IO.File]::WriteAllText($Path, $Text, $Utf8NoBom)
}
function New-RuntimeDonorSnapshot([string]$SourceRoot, [string]$TargetRoot) {
if (Test-Path $TargetRoot) { Remove-Item -Recurse -Force $TargetRoot }
New-Item -ItemType Directory -Force -Path (Join-Path $TargetRoot 'Mods') | Out-Null
Copy-Item -Force (Join-Path $SourceRoot 'VintagestoryAPI.dll') $TargetRoot
Copy-Item -Recurse -Force (Join-Path $SourceRoot 'Lib') $TargetRoot
foreach ($file in @(
'Mods/VSEssentials.dll',
'Mods/VSEssentials.pdb',
'Mods/VSCreativeMod.dll',
'Mods/VSSurvivalMod.dll',
'Mods/VSSurvivalMod.pdb')) {
Copy-Item -Force (Join-Path $SourceRoot $file) (Join-Path $TargetRoot $file)
}
foreach ($configuration in @('Debug', 'Release')) {
foreach ($name in @('VSEssentials', 'VSSurvivalMod', 'VSCreativeMod')) {
$compiled = Join-Path $repoRoot "bin/$configuration/net10.0/$name.dll"
$vanilla = Join-Path $SourceRoot "Mods/$name.dll"
if ((Test-Path $compiled) -and ((Get-FileHash -Algorithm SHA256 -LiteralPath $compiled).Hash -eq (Get-FileHash -Algorithm SHA256 -LiteralPath $vanilla).Hash)) {
throw "Cannot snapshot $($name): the selected client already contains the matching Optimum build output."
}
}
}
$versionMarker = Get-ChildItem -Path (Join-Path $SourceRoot 'assets') -Filter 'version-*.txt' -File |
Select-Object -First 1
if (-not $versionMarker) { throw 'Vanilla runtime donor snapshot has no version marker.' }
[IO.File]::WriteAllText(
(Join-Path $TargetRoot 'runtime-donor-version.txt'),
$versionMarker.Name,
$Utf8NoBom)
$manifest = Get-ChildItem -Path $TargetRoot -Recurse -File |
Sort-Object FullName |
ForEach-Object {
$relative = './' + $_.FullName.Substring($TargetRoot.Length + 1).Replace('\', '/')
"$((Get-FileHash -Algorithm SHA256 -LiteralPath $_.FullName).Hash.ToLowerInvariant()) $relative"
}
$manifestText = ($manifest -join "`n") + "`n"
[IO.File]::WriteAllBytes(
(Join-Path $TargetRoot 'runtime-donor-manifest.sha256'),
[Text.Encoding]::UTF8.GetBytes($manifestText))
}
function Update-FileInPlace {
param([string]$Path, [scriptblock]$Transform)
if (-not (Test-Path $Path)) { return }
$text = Read-TextFile $Path
$new = & $Transform $text
if ($new -ne $text) { Write-TextFile $Path $new }
}
function Update-TreeInPlace {
param([string[]]$Roots, [scriptblock]$Transform)
foreach ($root in $Roots) {
if (-not (Test-Path $root)) { continue }
Get-ChildItem -Path $root -Recurse -Filter '*.cs' -File | ForEach-Object {
$text = Read-TextFile $_.FullName
$new = & $Transform $text
if ($new -ne $text) { Write-TextFile $_.FullName $new }
}
}
}
function Copy-TreeFresh([string]$Src, [string]$Dst) {
if (Test-Path $Dst) { Remove-Item -Recurse -Force $Dst }
$parent = Split-Path -Parent $Dst
if ($parent -and -not (Test-Path $parent)) { New-Item -ItemType Directory -Force -Path $parent | Out-Null }
Copy-Item -Recurse -Force $Src $Dst
}
function Convert-ToLf([string]$Root) {
if (-not (Test-Path $Root)) { return }
Get-ChildItem -Path $Root -Recurse -File -Include '*.cs','*.csproj','*.json','*.xml','*.props','*.targets','*.patch','*.ps1','*.sh','*.cmd','*.slnx' | ForEach-Object {
$bytes = [IO.File]::ReadAllBytes($_.FullName)
$hasCR = $false
foreach ($b in $bytes) { if ($b -eq 13) { $hasCR = $true; break } }
if ($hasCR) {
$t = [Text.Encoding]::UTF8.GetString($bytes) -creplace ([char]13 + [char]10), [char]10 -creplace [char]13, [char]10
[IO.File]::WriteAllBytes($_.FullName, [Text.Encoding]::UTF8.GetBytes($t))
}
}
}
function Get-PinnedIlspycmdVersion {
$manifest = Join-Path $repoRoot '.config/dotnet-tools.json'
if (-not (Test-Path $manifest)) { return $null }
$json = Get-Content $manifest -Raw | ConvertFrom-Json
return $json.tools.ilspycmd.version
}
function Get-IlspycmdVersionRange {
$manifest = Join-Path $repoRoot '.config/ilspycmd-compat.json'
if (-not (Test-Path $manifest)) {
return [pscustomobject]@{
Minimum = [Version]'10.1.0.8386'
Maximum = [Version]'10.1.1.8388'
}
}
$json = Get-Content $manifest -Raw | ConvertFrom-Json
$minimum = [string]$json.minimumVersion
$maximum = [string]$json.maximumVersion
if ($minimum -notmatch '^\d+\.\d+\.\d+\.\d+$' -or $maximum -notmatch '^\d+\.\d+\.\d+\.\d+$') {
throw "ilspycmd version range is invalid: $manifest"
}
return [pscustomobject]@{
Minimum = [Version]$minimum
Maximum = [Version]$maximum
}
}
function Install-IlspycmdIfMissing {
$dotnetTools = Join-Path $HOME '.dotnet/tools'
if (Test-Path (Join-Path $dotnetTools 'ilspycmd.exe')) {
$env:PATH = "$dotnetTools;$env:PATH"
}
$pinned = Get-PinnedIlspycmdVersion
$existing = Get-Command ilspycmd -ErrorAction SilentlyContinue
if ($existing) {
if (-not $pinned) { return }
$verLine = Invoke-NativeStep { & ilspycmd --version 2>$null | Select-Object -First 1 }
$current = if ($verLine) { ($verLine -split '\s+')[1] } else { '' }
$range = Get-IlspycmdVersionRange
$isStableVersion = $current -match '^\d+\.\d+\.\d+\.\d+$'
$currentVersion = if ($isStableVersion) { [Version]$current } else { $null }
$currentOk = $null -ne $currentVersion -and
$currentVersion -ge $range.Minimum -and $currentVersion -le $range.Maximum
if ($currentOk) { return }
Write-Host "ilspycmd $current is unsupported by this patch set, installing $pinned"
Invoke-NativeStep { dotnet tool uninstall -g ilspycmd 2>&1 | Out-Null }
}
if ($pinned) {
Write-Host "Installing ilspycmd $pinned"
Invoke-NativeStep { dotnet tool install -g ilspycmd --version $pinned | Out-Null }
} else {
Write-Host "Installing ilspycmd (latest)"
Invoke-NativeStep { dotnet tool install -g ilspycmd | Out-Null }
}
$env:PATH = "$dotnetTools;$env:PATH"
}
# --- fix-base-ctor-calls: base._002Ector(args)/this._002Ector(args) -> : base(args)/: this(args) ---
# Port of scripts/fix-base-ctor-calls.py. ILSpy occasionally decompiles the
# base/this constructor chain call using its IL name (.ctor, mangled to
# _002Ector) as a plain method-call statement instead of C#'s only legal
# syntax for it. The call can appear anywhere in the decompiled body; moving
# it to the initializer position is safe because real field initializers
# always run after the base constructor per C# spec, which is the order this
# produces either way.
function Repair-BaseCtorCalls {
param([string[]]$Roots)
$callRe = [regex]'[ \t]*(base|this)\._002Ector\(((?:[^()]|\([^()]*\))*)\);\n'
$sigRe = [regex]'((?:public|private|protected|internal|static)[ \w]*\s\w+\(([^()]*)\)\s*\n)(\t*\{\n)'
function local:Invoke-FixOnce([string]$text) {
foreach ($sigM in $sigRe.Matches($text)) {
$bodyStart = $sigM.Index + $sigM.Length
$depth = 1
$j = $bodyStart
while ($depth -gt 0 -and $j -lt $text.Length) {
if ($text[$j] -eq '{') { $depth++ }
elseif ($text[$j] -eq '}') { $depth-- }
$j++
}
$body = $text.Substring($bodyStart, $j - $bodyStart)
$callM = $callRe.Match($body)
if (-not $callM.Success) { continue }
$kind = $callM.Groups[1].Value
$ctorArgs = $callM.Groups[2].Value
$newBody = $body.Substring(0, $callM.Index) + $body.Substring($callM.Index + $callM.Length)
$header = $sigM.Groups[1].Value
$braceLine = $sigM.Groups[3].Value
$newHeader = $header.TrimEnd("`n") + "`n`t`t: $kind($ctorArgs)`n"
$newText = $text.Substring(0, $sigM.Index) + $newHeader + $braceLine + $newBody + $text.Substring($j)
return , @($newText, $true)
}
return , @($text, $false)
}
$files = @()
foreach ($root in $Roots) {
if (Test-Path $root) { $files += Get-ChildItem -Path $root -Recurse -Filter '*.cs' -File }
}
$totalFilesChanged = 0
foreach ($file in $files) {
$text = Read-TextFile $file.FullName
if (-not $text.Contains('_002Ector(')) { continue }
$original = $text
for ($i = 0; $i -lt 50; $i++) {
$result = Invoke-FixOnce $text
$text = $result[0]
if (-not $result[1]) { break }
}
if ($text -ne $original) {
Write-TextFile $file.FullName $text
$totalFilesChanged++
}
}
Write-Host "Rewrote base/this constructor calls in $totalFilesChanged file(s)."
}
# --- fix-event-reads: bare/this-qualified reads of a custom-accessor event's
# current value (null checks, casts, GetInvocationList()) -> its m_<Name>
# backing field. Port of scripts/fix-event-reads.py. ---
function Repair-EventReads {
param([string[]]$Roots)
$stringRe = [regex]'"(?:[^"\\]|\\.)*"'
$files = @()
foreach ($root in $Roots) {
if (Test-Path $root) { $files += Get-ChildItem -Path $root -Recurse -Filter '*.cs' -File }
}
$totalFilesChanged = 0
$totalSubs = 0
foreach ($file in $files) {
$text = Read-TextFile $file.FullName
$backing = @{}
foreach ($m in [regex]::Matches($text, 'private\s+[\w<>,\.\[\]\s]+?\s+m_(\w+);')) {
$backing[$m.Groups[1].Value] = $true
}
if ($backing.Count -eq 0) { continue }
# Async state machines capture `this` into a `_003C_003E4__this` field and
# commonly alias it to a locally-scoped variable at the top of MoveNext.
# That variable IS `this` for this class, so qualifying an event read
# through it needs the same rewrite as `this.Name`.
$allowedQualifiers = @{ 'this' = $true }
foreach ($m in [regex]::Matches($text, '\b(\w+)\s*=\s*[\w.]*_003C_003E4__this;')) {
$allowedQualifiers[$m.Groups[1].Value] = $true
}
$lines = New-Object System.Collections.Generic.List[string]
$lines.AddRange([string[]]($text -split "`n"))
$fileChanged = $false
$names = $backing.Keys | Sort-Object -Property Length -Descending
foreach ($name in $names) {
$escaped = [regex]::Escape($name)
$declRe = [regex]::new("\bevent\s+\S.*\b$escaped\b")
if (-not $declRe.IsMatch($text)) { continue }
# Match an optional `qualifier.` prefix so it can be inspected: only
# rewrite a bare reference (no qualifier) or one qualified by `this`
# or a this-alias -- never `SomeOtherType.Name`, a different member
# (e.g. an enum value) that happens to share the event's name.
$readRe = [regex]::new("\b(?:(\w+)\.)?$escaped\b(?!\s*[+\-]=)")
for ($i = 0; $i -lt $lines.Count; $i++) {
$line = $lines[$i]
if ($declRe.IsMatch($line)) { continue }
$spans = @()
foreach ($sm in $stringRe.Matches($line)) {
$spans += , @($sm.Index, ($sm.Index + $sm.Length))
}
$out = New-Object System.Text.StringBuilder
$last = 0
$n = 0
foreach ($m in $readRe.Matches($line)) {
$inString = $false
foreach ($sp in $spans) {
if ($sp[0] -le $m.Index -and $m.Index -lt $sp[1]) { $inString = $true; break }
}
if ($inString) { continue }
$hasQualifier = $m.Groups[1].Success
$qualifier = $m.Groups[1].Value
if ($hasQualifier -and -not $allowedQualifiers.ContainsKey($qualifier)) { continue }
$prefix = if ($hasQualifier) { "$qualifier." } else { '' }
[void]$out.Append($line.Substring($last, $m.Index - $last))
[void]$out.Append($prefix + 'm_' + $name)
$last = $m.Index + $m.Length
$n++
}
[void]$out.Append($line.Substring($last))
if ($n -gt 0) {
$lines[$i] = $out.ToString()
$fileChanged = $true
$totalSubs += $n
}
}
}
if ($fileChanged) {
Write-TextFile $file.FullName ([string]::Join("`n", $lines))
$totalFilesChanged++
}
}
Write-Host "Rewrote $totalSubs event read(s) across $totalFilesChanged file(s)."
}
# --- value-type constructor pattern: `TYPE val = default(TYPE); val._002Ector(args);`
# -> `TYPE val = new TYPE(args);`. Value-type sibling of the ref-cast pattern
# handled inline further down; needs its own paren/brace-matching pass since it
# has no `((Type)(ref var))` wrapper for a regex to anchor on. ---
function Repair-ValueTypeConstructorCalls {
param([string[]]$Roots)
$declRe = [regex]'([ \t]*)([\w<>,.\s]+?)\s+(\w+)\s*=\s*default\(\2\);\n'
function local:Find-MatchingParen([string]$s, [int]$openIdx) {
$depth = 1
$j = $openIdx + 1
while ($depth -gt 0) {
if ($s[$j] -eq '(') { $depth++ }
elseif ($s[$j] -eq ')') { $depth-- }
$j++
}
return $j
}
$files = @()
foreach ($root in $Roots) {
if (Test-Path $root) { $files += Get-ChildItem -Path $root -Recurse -Filter '*.cs' -File }
}
$total = 0
foreach ($file in $files) {
$text = Read-TextFile $file.FullName
if (-not $text.Contains('_002Ector(')) { continue }
$sb = New-Object System.Text.StringBuilder
$pos = 0
$changed = $false
foreach ($m in $declRe.Matches($text)) {
if ($m.Index -lt $pos) { continue }
$indent = $m.Groups[1].Value
$typename = $m.Groups[2].Value
$varname = $m.Groups[3].Value
$callMarker = "$varname._002Ector("
$afterStart = $m.Index + $m.Length
$after = $text.Substring($afterStart)
$stripped = $after.TrimStart("`t", ' ')
if (-not $stripped.StartsWith($callMarker)) { continue }
$callStart = $afterStart + ($after.Length - $stripped.Length)
$parenOpen = $text.IndexOf('(', $callStart)
$parenClose = Find-MatchingParen $text $parenOpen
if ($text[$parenClose] -ne ';') { continue }
$ctorArgs = $text.Substring($parenOpen + 1, $parenClose - 1 - ($parenOpen + 1))
[void]$sb.Append($text.Substring($pos, $m.Index - $pos))
[void]$sb.Append("$indent$typename $varname = new $typename($ctorArgs);`n")
$pos = $parenClose + 2
$changed = $true
$total++
}
if ($changed) {
[void]$sb.Append($text.Substring($pos))
Write-TextFile $file.FullName $sb.ToString()
}
}
Write-Host "Rewrote $total value-type constructor call(s)."
}
function Invoke-GitApplyOptimumPatch {
param([string]$PatchPath, [string]$DirArg)
function local:Invoke-Apply([string[]]$ExtraArgs) {
$applyArgs = @('apply', '--whitespace=nowarn')
if ($DirArg) { $applyArgs += $DirArg }
$applyArgs += $ExtraArgs
$applyArgs += $PatchPath
$prevEAP = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
$out = & git @applyArgs 2>&1
$code = $LASTEXITCODE
$ErrorActionPreference = $prevEAP
return , @($code, ($out -join "`n"))
}
$r = Invoke-Apply @()
if ($r[0] -eq 0) { return @{ Success = $true; Output = '' } }
$firstOutput = $r[1]
$r2 = Invoke-Apply @('-p0')
if ($r2[0] -eq 0) { return @{ Success = $true; Output = 'applied with -p0' } }
if ($DirArg) {
$applyArgs = @('apply', '--whitespace=nowarn', '-p0', $PatchPath)
$prevEAP = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
$out3 = & git @applyArgs 2>&1
$code3 = $LASTEXITCODE
$ErrorActionPreference = $prevEAP
if ($code3 -eq 0) { return @{ Success = $true; Output = 'applied with root -p0' } }
}
return @{ Success = $false; Output = $firstOutput }
}
function Test-PatchSyntax([string]$PatchPath) {
$lines = Get-Content -LiteralPath $PatchPath
$hasOldHeader = [bool]($lines | Where-Object { $_.StartsWith('--- ') } | Select-Object -First 1)
$hasNewHeader = [bool]($lines | Where-Object { $_.StartsWith('+++ ') } | Select-Object -First 1)
if (-not $hasOldHeader -or -not $hasNewHeader) {
return @{ Success = $false; Output = 'missing unified-diff file header (expected --- and +++)' }
}
$prevEAP = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
$output = & git apply --stat $PatchPath 2>&1 | Out-String
$code = $LASTEXITCODE
$ErrorActionPreference = $prevEAP
return @{ Success = ($code -eq 0); Output = $output.Trim() }
}
# ===========================================================================
# Main
# ===========================================================================
Push-Location $repoRoot
try {
if (-not (Get-Command git -ErrorAction SilentlyContinue)) {
throw "Git not found. Install Git for Windows from $gitInstallUrl and run bootstrap again."
}
# Vanilla client files always live under .vanilla/win-x64/, matching the
# convention used by bootstrap.sh, install-windows.ps1, package.ps1, and
# _hostcaps.ps1.
$vanillaDir = Join-Path $repoRoot '.vanilla/win-x64'
$winVanillaDir = Join-Path $vanillaDir 'vintagestory'
$snapshotDir = Join-Path $repoRoot 'build/snapshot'
$zipCacheDir = Join-Path $vanillaDir '../archives'
$sourcesDir = Join-Path $repoRoot 'sources'
$runtimeDonorDir = Join-Path $vanillaDir 'runtime-donors'
if ($Refresh -and (Test-Path $vanillaDir)) { Remove-Item -Recurse -Force $vanillaDir }
if ($Refresh -and (Test-Path $snapshotDir)) { Remove-Item -Recurse -Force $snapshotDir }
# --- 1. Obtain vanilla client files ---
# Three modes:
# a) .vanilla/win-x64/vintagestory already has Vintagestory.exe -> skip
# b) -ClientArchive '__skip__' -> the caller (install-windows.ps1) already
# placed .vanilla via junction; verify it exists and move on
# c) Normal: download the installer and extract with innounp
$skipDownload = ($ClientArchive -eq '__skip__')
$freshExtract = $false
# Re-extract when the cached client's own version marker doesn't match
# what we're building - a directory left over from bootstrapping a
# different -Version looks present but silently keeps building against
# the wrong VintagestoryLib.exe/dll underneath (same class of bug fixed
# in bootstrap.sh's .vanilla/win-x64 handling).
$extractedVersion = $null
$vanillaAssetsCheck = Join-Path $winVanillaDir 'assets'
if (Test-Path $vanillaAssetsCheck) {
$marker = Get-ChildItem -Path $vanillaAssetsCheck -Filter 'version-*.txt' -File -ErrorAction SilentlyContinue | Select-Object -First 1
if ($marker -and $marker.BaseName -match '^version-(.+)$') { $extractedVersion = $Matches[1] }
}
if ($extractedVersion -and $extractedVersion -ne $Version -and -not $skipDownload) {
Write-Host "Cached win-x64 client is $extractedVersion, requested $Version - re-extracting"
Remove-Item -Recurse -Force $winVanillaDir -ErrorAction SilentlyContinue
}
if (Test-Path (Join-Path $winVanillaDir 'Vintagestory.exe')) {
Write-Host "Using existing $winVanillaDir"
} elseif ($skipDownload) {
if (-not (Test-Path (Join-Path $winVanillaDir 'Vintagestory.exe'))) {
throw ".vanilla/win-x64/vintagestory not found and download was skipped. Provide a VS install path."
}
} else {
New-Item -ItemType Directory -Force -Path $zipCacheDir | Out-Null
$exeName = "vs_install_win-x64_$Version.exe"
if (-not $ClientArchive) {
$ClientArchive = Join-Path $zipCacheDir $exeName
}
if (-not (Test-Path $ClientArchive)) {
$url = "https://cdn.vintagestory.at/gamefiles/stable/$exeName"
Write-Host "Downloading $url (~570MB)"
# Written under a temporary name and moved into place only once curl has
# succeeded, so an interrupted download leaves nothing rather than a short file
# at the cache path. Without this, stopping the bootstrap during the ~570 MB
# download poisons the cache: the next run finds the file, reports "Using
# cached", and fails in innounp instead.
$partial = "$ClientArchive.partial"
Remove-Item -Force -ErrorAction SilentlyContinue $partial
Invoke-NativeStep { curl.exe -L --fail --progress-bar -o $partial $url }
if ($LASTEXITCODE -ne 0) {
Remove-Item -Force -ErrorAction SilentlyContinue $partial
throw "Download failed: $url"
}
Move-Item -Force $partial $ClientArchive
} else {
Write-Host "Using cached $ClientArchive"
}
# Extract using innounp (download if missing). Supports InnoSetup 6.x.
$toolsDir = Join-Path $repoRoot '.tools'
$innounp = Join-Path $toolsDir 'innounp.exe'
if (-not (Test-Path $innounp)) {
New-Item -ItemType Directory -Force -Path $toolsDir | Out-Null
$innounpZip = Join-Path $toolsDir 'innounp-2.zip'
Write-Host "Downloading innounp"
# Same reasoning as the client archive above: small enough that the window is
# narrow, and a short zip here fails in Expand-Archive on every later run.
$innounpPartial = "$innounpZip.partial"
Remove-Item -Force -ErrorAction SilentlyContinue $innounpPartial
Invoke-NativeStep { curl.exe -L --fail --silent -o $innounpPartial "https://github.com/jrathlev/InnoUnpacker-Windows-GUI/releases/download/ui_2_2_9/innounp-2.zip" }
if ($LASTEXITCODE -ne 0) {
Remove-Item -Force -ErrorAction SilentlyContinue $innounpPartial
throw "Download failed: innounp-2.zip"
}
Move-Item -Force $innounpPartial $innounpZip
Expand-Archive -Path $innounpZip -DestinationPath $toolsDir -Force
$found = Get-ChildItem -Path $toolsDir -Recurse -Filter 'innounp.exe' | Select-Object -First 1
if ($found -and $found.FullName -ne $innounp) {
Copy-Item -Force $found.FullName $innounp
}
Remove-Item -Force $innounpZip -ErrorAction SilentlyContinue
}
$extractTarget = $winVanillaDir
New-Item -ItemType Directory -Force -Path $extractTarget | Out-Null
Write-Host "Extracting with innounp to $extractTarget"
Get-Process -Name 'innounp' -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
$innounpProc = Start-Process -FilePath $innounp -ArgumentList "-x -d`"$extractTarget`" -c`"{app}`" `"$ClientArchive`"" -NoNewWindow -PassThru
$exited = $innounpProc.WaitForExit(300000)
if (-not $exited) {
$innounpProc.Kill()
Get-Process -Name 'innounp' -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
throw "innounp timed out after 5 minutes. Kill any innounp.exe in Task Manager and retry."
}
$innounpExitCode = $innounpProc.ExitCode
$appDir = Join-Path $extractTarget '{app}'
if (Test-Path $appDir) {
Get-ChildItem -Path $appDir | Move-Item -Destination $extractTarget -Force
Remove-Item -Force $appDir
}
if ($innounpExitCode -ne 0 -and -not (Test-Path (Join-Path $extractTarget 'Vintagestory.exe'))) {
throw "innounp failed (exit $innounpExitCode)."
}
if ($innounpExitCode -ne 0) {
Write-Warning "innounp exited with code $innounpExitCode after extracting Vintagestory.exe; continuing."
}
if (-not (Test-Path (Join-Path $extractTarget 'Vintagestory.exe'))) {
throw "Extraction failed: Vintagestory.exe not found"
}
$freshExtract = $true
Write-Host "Extraction complete."
}
# Validate the vanilla tree before building against it. A tolerated
# partial innounp extraction (nonzero exit above) or a stale .vanilla
# cache left by an older failed run carries zero-byte or truncated
# assets that only surface later, in-game, as opaque GL crashes
# ("blur.vsh ... unexpected $end at <EOF>"). Catch them here instead.
$vanillaAssets = Join-Path $winVanillaDir 'assets'
$corrupt = @(Get-ChildItem -Path $vanillaAssets -Recurse -File -ErrorAction SilentlyContinue |
Where-Object { $_.Length -eq 0 -and $_.Name -notlike 'version-*.txt' })
$vanillaShaders = Join-Path $vanillaAssets 'game/shaders'
if (Test-Path $vanillaShaders) {
$corrupt += @(Get-ChildItem -Path $vanillaShaders -File |
Where-Object { $_.Extension -in '.vsh', '.fsh', '.gsh' } |
Where-Object { (Get-Content $_.FullName -Raw) -notmatch 'void\s+main' })
} else {
throw "Vanilla client at $winVanillaDir has no assets/game/shaders; the extraction or install is incomplete."
}
if ($corrupt.Count -gt 0) {
$names = ($corrupt | Select-Object -First 10 | ForEach-Object { $_.FullName }) -join "`n "
if ($freshExtract) {
# Wipe the poisoned extraction so the next run re-extracts
# instead of reusing it via the "Using existing" fast path.
Remove-Item -Recurse -Force $winVanillaDir -ErrorAction SilentlyContinue
throw "innounp produced $($corrupt.Count) empty/truncated file(s); the extraction was discarded. Re-run to retry.`n $names"
}
throw "Vanilla client files are corrupt ($($corrupt.Count) empty/truncated file(s)):`n $names`nIf $winVanillaDir is Optimum's own cache, delete it and retry; if it points at your Vintage Story install, repair or reinstall Vintage Story $Version first."
}
if ($freshExtract -or ($skipDownload -and -not (Test-Path (Join-Path $runtimeDonorDir 'runtime-donor-manifest.sha256')))) {
New-RuntimeDonorSnapshot $winVanillaDir $runtimeDonorDir
} elseif (-not (Test-Path (Join-Path $runtimeDonorDir 'runtime-donor-manifest.sha256'))) {
Write-Warning 'Protected runtime-donor snapshot is missing. Run bootstrap.ps1 -Refresh before check-patches.ps1.'
}
# --- 2. Decompile closed-source DLLs ---
Install-IlspycmdIfMissing
# Produces .csproj projects in build/snapshot/{name}/ copied to build/{name}/.
$decompileTargets = [ordered]@{
'VintagestoryLib' = 'build/VintagestoryLib'
'Vintagestory' = 'build/Vintagestory'
}
foreach ($dllBase in $decompileTargets.Keys) {
$workDir = $decompileTargets[$dllBase]
$dllPath = Get-ChildItem -Path $winVanillaDir -Recurse -Filter "$dllBase.dll" -ErrorAction SilentlyContinue | Select-Object -First 1
if (-not $dllPath) { Write-Warning "Skipping $dllBase.dll (not found)"; continue }
$out = Join-Path $snapshotDir $dllBase
if (-not (Test-Path $out) -or $Refresh) {
$verLine = Invoke-NativeStep { & ilspycmd --version 2>$null | Select-Object -First 1 }
Write-Host "Decompiling $dllBase.dll with $verLine"
if (Test-Path $out) { Remove-Item -Recurse -Force $out }
New-Item -ItemType Directory -Force -Path $out | Out-Null
Invoke-NativeStep { ilspycmd $dllPath.FullName --project -o $out 2>$null | Out-Null }
# Don't trust ilspycmd's exit code alone: it has a known bug
# (icsharpcode/ILSpy#3101) where it reports failure via a bogus
# "not using the latest version" self-check even after a fully
# successful decompile. Verify the real artifact instead.
$producedProjects = @(Get-ChildItem -Path $out -Filter '*.csproj' -File -ErrorAction SilentlyContinue)
if ($producedProjects.Count -eq 0) {
throw "ilspycmd produced no .csproj for $dllBase.dll (exit code $LASTEXITCODE). Delete $out and retry, or reinstall ilspycmd."
}
$producedProjects | ForEach-Object {
Update-FileInPlace $_.FullName { param($t) $t -creplace '<LangVersion>15\.0</LangVersion>', '<LangVersion>latest</LangVersion>' }
}
}
Convert-ToLf $out
Copy-TreeFresh $out (Join-Path $repoRoot $workDir)
Convert-ToLf (Join-Path $repoRoot $workDir)
}
# --- 3. Clone compile-target forks (VintagestoryApi, Cairo, ...) ---
$forksFile = Join-Path $repoRoot 'forks.json'
if (Test-Path $forksFile) {
$cfg = Get-Content $forksFile -Raw | ConvertFrom-Json
$forks = @($cfg.compile | Where-Object { $_.source -eq 'clone' })
foreach ($fork in $forks) {
$name = $fork.name
$base = Join-Path $snapshotDir $name
if (-not (Test-Path $base) -or $Refresh) {
if (Test-Path $base) { Remove-Item -Recurse -Force $base }
Write-Host "Cloning $name at $($fork.ref)"
Invoke-NativeStep { git -c core.autocrlf=false -c core.eol=lf clone --quiet $fork.url $base 2>$null }
if ($LASTEXITCODE -ne 0) { throw "git clone failed for $name ($($fork.url))." }
Invoke-NativeStep { Invoke-GitInClone $base config core.autocrlf false }
Invoke-NativeStep { Invoke-GitInClone $base config core.eol lf }
Invoke-NativeStep { Invoke-GitInClone $base checkout --quiet $fork.ref }
if ($LASTEXITCODE -ne 0) { throw "git checkout $($fork.ref) failed for $name." }
Remove-Item -Recurse -Force (Join-Path $base '.git')
Convert-ToLf $base
}
$dst = Join-Path $repoRoot $name
Copy-TreeFresh $base $dst
Convert-ToLf $dst
}
# --- 3b. Clone reference repos (for code reading, not compilation). ---
$refRoots = @($cfg.reference | Where-Object { $_ })
if ($refRoots.Count -gt 0) {
$refDir = Join-Path $repoRoot 'ref/source'
foreach ($r in $refRoots) {
$dest = Join-Path $refDir $r.name
if (-not (Test-Path $dest)) {
Write-Host "Cloning reference: $($r.name)"
Invoke-NativeStep { git -c core.autocrlf=false -c core.eol=lf clone --quiet --depth=1 $r.url $dest 2>$null }
Invoke-NativeStep { Invoke-GitInClone $dest checkout --quiet $r.ref 2>$null }
}
}
}
}
# --- 6. Post-decompile fixups (csproj rewrites, ambiguity resolution). ---
Write-Host "Applying post-decompile fixups..."
Convert-ToLf (Join-Path $repoRoot 'build')
# Normalize CRLF across all decompiled .cs files FIRST (ilspycmd on Windows
# emits CRLF, and several fixups below anchor on `^`/`\n` which assumes LF).
Get-ChildItem -Path (Join-Path $repoRoot 'build') -Recurse -Filter '*.cs' -File | ForEach-Object {
$bytes = [IO.File]::ReadAllBytes($_.FullName)
$hasCR = $false
foreach ($b in $bytes) { if ($b -eq 13) { $hasCR = $true; break } }
if ($hasCR) {
$t = [Text.Encoding]::UTF8.GetString($bytes) -creplace "`r`n", "`n" -creplace "`r", "`n"
[IO.File]::WriteAllBytes($_.FullName, [Text.Encoding]::UTF8.GetBytes($t))
}
}
# 6a. Rewrite VintagestoryLib.csproj with HintPaths to .vanilla DLLs.
$libCsproj = Join-Path $repoRoot 'build/VintagestoryLib/VintagestoryLib.csproj'
$libCsprojContent = @'
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AssemblyName>VintagestoryLib</AssemblyName>
<GenerateAssemblyInfo>False</GenerateAssemblyInfo>
<TargetFramework>net10.0</TargetFramework>
</PropertyGroup>
<PropertyGroup>
<LangVersion>latest</LangVersion>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\VintagestoryApi\VintagestoryAPI.csproj" />
</ItemGroup>
<ItemGroup>
<Reference Include="cairo-sharp"><HintPath>..\..\.vanilla\win-x64\vintagestory\Lib\cairo-sharp.dll</HintPath></Reference>
<Reference Include="protobuf-net"><HintPath>..\..\.vanilla\win-x64\vintagestory\Lib\protobuf-net.dll</HintPath></Reference>
<Reference Include="Newtonsoft.Json"><HintPath>..\..\.vanilla\win-x64\vintagestory\Lib\Newtonsoft.Json.dll</HintPath></Reference>
<Reference Include="CommandLine"><HintPath>..\..\.vanilla\win-x64\vintagestory\Lib\CommandLine.dll</HintPath></Reference>
<Reference Include="SkiaSharp"><HintPath>..\..\.vanilla\win-x64\vintagestory\Lib\SkiaSharp.dll</HintPath></Reference>
<Reference Include="Open.Nat"><HintPath>..\..\.vanilla\win-x64\vintagestory\Lib\Open.Nat.dll</HintPath></Reference>
<Reference Include="Mono.Nat"><HintPath>..\..\.vanilla\win-x64\vintagestory\Lib\Mono.Nat.dll</HintPath></Reference>
<Reference Include="Mono.Cecil"><HintPath>..\..\.vanilla\win-x64\vintagestory\Lib\Mono.Cecil.dll</HintPath></Reference>
<Reference Include="Microsoft.CodeAnalysis"><HintPath>..\..\.vanilla\win-x64\vintagestory\Lib\Microsoft.CodeAnalysis.dll</HintPath></Reference>
<Reference Include="Microsoft.CodeAnalysis.CSharp"><HintPath>..\..\.vanilla\win-x64\vintagestory\Lib\Microsoft.CodeAnalysis.CSharp.dll</HintPath></Reference>
<Reference Include="ICSharpCode.SharpZipLib"><HintPath>..\..\.vanilla\win-x64\vintagestory\Lib\ICSharpCode.SharpZipLib.dll</HintPath></Reference>
<Reference Include="Microsoft.Data.Sqlite"><HintPath>..\..\.vanilla\win-x64\vintagestory\Lib\Microsoft.Data.Sqlite.dll</HintPath></Reference>
<Reference Include="0Harmony"><HintPath>..\..\.vanilla\win-x64\vintagestory\Lib\0Harmony.dll</HintPath></Reference>
<Reference Include="OpenTK.Windowing.Desktop"><HintPath>..\..\.vanilla\win-x64\vintagestory\Lib\OpenTK.Windowing.Desktop.dll</HintPath></Reference>
<Reference Include="OpenTK.Audio.OpenAL"><HintPath>..\..\.vanilla\win-x64\vintagestory\Lib\OpenTK.Audio.OpenAL.dll</HintPath></Reference>
<Reference Include="OpenTK.Mathematics"><HintPath>..\..\.vanilla\win-x64\vintagestory\Lib\OpenTK.Mathematics.dll</HintPath></Reference>
<Reference Include="OpenTK.Windowing.Common"><HintPath>..\..\.vanilla\win-x64\vintagestory\Lib\OpenTK.Windowing.Common.dll</HintPath></Reference>
<Reference Include="OpenTK.Windowing.GraphicsLibraryFramework"><HintPath>..\..\.vanilla\win-x64\vintagestory\Lib\OpenTK.Windowing.GraphicsLibraryFramework.dll</HintPath></Reference>
<Reference Include="DnsClient"><HintPath>..\..\.vanilla\win-x64\vintagestory\Lib\DnsClient.dll</HintPath></Reference>
<Reference Include="OpenTK.Graphics"><HintPath>..\..\.vanilla\win-x64\vintagestory\Lib\OpenTK.Graphics.dll</HintPath></Reference>
<Reference Include="csvorbis"><HintPath>..\..\.vanilla\win-x64\vintagestory\Lib\csvorbis.dll</HintPath></Reference>
<Reference Include="csogg"><HintPath>..\..\.vanilla\win-x64\vintagestory\Lib\csogg.dll</HintPath></Reference>
<Reference Include="xplatforminterface"><HintPath>..\..\.vanilla\win-x64\vintagestory\Lib\xplatforminterface.dll</HintPath></Reference>
</ItemGroup>
</Project>
'@
Write-TextFile $libCsproj ($libCsprojContent + "`n")
# 6b. Fix VSEssentials/VSSurvivalMod: Tavis.JsonPatch PackageReference -> local DLL Reference.
foreach ($proj in @('VSEssentials/VSEssentialsMod.csproj', 'VSSurvivalMod/VSSurvivalMod.csproj')) {
Update-FileInPlace (Join-Path $repoRoot $proj) {
param($t)
$t -creplace '<PackageReference Include="Tavis\.JsonPatch" Version="[^"]*"\s*/>', '<Reference Include="Tavis.JsonPatch"><HintPath>..\.vanilla\win-x64\vintagestory\Lib\Tavis.JsonPatch.dll</HintPath><Private>false</Private></Reference>'
}
}
# 6c. Fix Mapping ambiguity in ServerSystemUpnp.
$upnp = Join-Path $repoRoot 'build/VintagestoryLib/Vintagestory.Server/ServerSystemUpnp.cs'
Update-FileInPlace $upnp {
param($t)
$t = [regex]::Replace($t, '(?m)^\tprivate Mapping mapping;', "`tprivate Open.Nat.Mapping mapping;")
$t = [regex]::Replace($t, '(?m)^\tprivate Mapping mappingUdp;', "`tprivate Open.Nat.Mapping mappingUdp;")
$t = [regex]::Replace($t, '(?m)^\tprivate Mapping monoNatMapping;', "`tprivate Mono.Nat.Mapping monoNatMapping;")
$t = [regex]::Replace($t, '(?m)^\tprivate Mapping monoNatMappingUdp;', "`tprivate Mono.Nat.Mapping monoNatMappingUdp;")
$t = $t -creplace 'mapping = new Mapping\(\(Protocol\)0', 'mapping = new Open.Nat.Mapping((Open.Nat.Protocol)0'
$t = $t -creplace 'mappingUdp = new Mapping\(\(Protocol\)1', 'mappingUdp = new Open.Nat.Mapping((Open.Nat.Protocol)1'
$t = $t -creplace 'monoNatMapping = new Mapping\(\(Protocol\)0', 'monoNatMapping = new Mono.Nat.Mapping((Mono.Nat.Protocol)0'
$t = $t -creplace 'monoNatMappingUdp = new Mapping\(\(Protocol\)1', 'monoNatMappingUdp = new Mono.Nat.Mapping((Mono.Nat.Protocol)1'
$t
}
# 6d. Fix ModContainer CustomAttributeNamedArgument ambiguity.
$modcont = Join-Path $repoRoot 'build/VintagestoryLib/Vintagestory.Common/ModContainer.cs'
Update-FileInPlace $modcont {
param($t)
[regex]::Replace($t, '(?<!\.)(?<!Mono\.Cecil\.)(?<!System\.Reflection\.)CustomAttributeNamedArgument(?!\w)', 'Mono.Cecil.CustomAttributeNamedArgument')
}
Write-Host "Post-decompile fixups done."
# 6e. Final pass: catch remaining decompiler artifacts (ref-casts, op_Implicit,
# ambiguous types, GeneratedRegex) across the entire build tree.
Update-TreeInPlace @((Join-Path $repoRoot 'build')) {
param($t)
$t = [regex]::Replace($t, '\(\(([\w.]+)\)\(ref (\w+)\)\)\._002Ector\(', '$2 = new $1(')
$t = [regex]::Replace($t, '\(\(([\w.]+)\)\(ref ([\w.]+)\)\)', '$2')
$t = [regex]::Replace($t, '\([^)]*<[^>]+>\)\(ref (\w+)\)', '$1')
$t = [regex]::Replace($t, 'JToken\.op_Implicit\((.+?)\)', '(JToken)($1)')
$t
}
# Fix GeneratedRegex: replace decompiled source-generator stubs with new Regex().
$generatedRegexPattern = "\t\[GeneratedRegex\(""([^""]+)""\)\]\n\t\[GeneratedCode\([^\]]+\)\]\n\tprivate static Regex (\w+)\(\)\n\t\{\n\t\treturn [^;]+;\n\t\}"
Update-TreeInPlace @((Join-Path $repoRoot 'build')) {
param($t)
[regex]::Replace($t, $generatedRegexPattern, {
param($m)
"`tprivate static Regex $($m.Groups[2].Value)()`n`t{`n`t`treturn new Regex(""$($m.Groups[1].Value)"", RegexOptions.Compiled);`n`t}"
})
}
# The fixup above bypasses every [GeneratedRegex] stub, so the source-generated
# regex-matching implementation classes ILSpy decompiles alongside them are now
# 100% dead code, never referenced from anywhere. Delete rather than fix artifacts
# in code nothing calls.
Get-ChildItem -Path (Join-Path $repoRoot 'build') -Recurse -Directory -Filter 'System.Text.RegularExpressions.Generated' -ErrorAction SilentlyContinue |
ForEach-Object { Remove-Item -Recurse -Force $_.FullName }
# Fix MouseWheelEventArgs ambiguity (OpenTK vs Vintagestory.API.Client).
$cpw = Join-Path $repoRoot 'build/VintagestoryLib/Vintagestory.Client.NoObf/ClientPlatformWindows.cs'
Update-FileInPlace $cpw {
param($t)
$t = $t -creplace 'private void Mouse_WheelChanged\(MouseWheelEventArgs e\)', 'private void Mouse_WheelChanged(OpenTK.Windowing.Common.MouseWheelEventArgs e)'
$t = $t -creplace 'MouseWheelEventArgs e2 = new MouseWheelEventArgs', 'Vintagestory.API.Client.MouseWheelEventArgs e2 = new Vintagestory.API.Client.MouseWheelEventArgs'
$t
}
# 6g. Additional ILSpy artifacts not covered by the generic regex passes.
$lib = Join-Path $repoRoot 'build/VintagestoryLib'
# Path ambiguity (Cairo.Path vs System.IO.Path) in GUI screens.
Get-ChildItem -Path (Join-Path $lib 'Vintagestory.Client') -Filter 'GuiScreen*.cs' -File -ErrorAction SilentlyContinue | ForEach-Object {
Update-FileInPlace $_.FullName { param($t) [regex]::Replace($t, '(?<![.\w])Path\.(?=DirectorySeparatorChar|Combine|GetTempPath|GetFileName|GetExtension|GetDirectoryName|GetFullPath)', 'System.IO.Path.') }
}
Update-FileInPlace (Join-Path $lib 'Vintagestory.Client/ScreenManager.cs') {
param($t) [regex]::Replace($t, '(?<![.\w])Path\.(?=DirectorySeparatorChar|Combine|GetTempPath|GetFileName|GetExtension|GetDirectoryName|GetFullPath)', 'System.IO.Path.')
}
# csvorbis.Block ambiguity in OggDecoder.
Update-FileInPlace (Join-Path $lib 'Vintagestory.Client.NoObf/OggDecoder.cs') {
param($t)
$t = $t -creplace '\bBlock val', 'csvorbis.Block val'
$t = $t -creplace '\bnew Block\(', 'new csvorbis.Block('
$t
}
# SystemRenderSunMoon: GL.GenQueries/GetQueryObject needs out not ref.
Update-FileInPlace (Join-Path $lib 'Vintagestory.Client.NoObf/SystemRenderSunMoon.cs') {
param($t)
$t = [regex]::Replace($t, 'GL\.GenQueries\((\d+), ref (\w+)\)', 'GL.GenQueries($1, out $2)')
$t = [regex]::Replace($t, 'GL\.GetQueryObject\(([^,]+), ([^,]+), ref (\w+)\)', 'GL.GetQueryObject($1, $2, out $3)')
$t
}
# SystemRenderOITLayers: RuntimeFieldHandle (ILSpy cannot decompile inline array init).
$oit = Join-Path $lib 'Vintagestory.Client.NoObf/SystemRenderOITLayers.cs'
Update-FileInPlace $oit {
param($t) [regex]::Replace($t, 'RuntimeHelpers\.InitializeArray.*RuntimeFieldHandle.*LdMemberToken.*', '// ILSpy: inline array init not supported')
}
# DrawBuffersEnum inline array fixups: ILSpy emits zeroed arrays because it cannot
# decompile RuntimeFieldHandle-based array initializers. Inject the correct enum
# values from vanilla.
Update-FileInPlace $oit {
param($t)
[regex]::Replace($t, 'DrawBuffersEnum\[\] array = new DrawBuffersEnum\[6\];\s*// ILSpy: inline array init not supported\s*DrawBuffersEnum\[\] array2 = \(DrawBuffersEnum\[\]\)\(object\)array;', 'DrawBuffersEnum[] array2 = new DrawBuffersEnum[6] { DrawBuffersEnum.ColorAttachment0, DrawBuffersEnum.ColorAttachment1, DrawBuffersEnum.ColorAttachment2, DrawBuffersEnum.ColorAttachment3, DrawBuffersEnum.ColorAttachment4, DrawBuffersEnum.ColorAttachment5 };')
}
# ClientPlatformWindows: remaining RuntimeFieldHandle occurrences + VSyncMode bool cast
# + ErrorCode ambiguity + BufferAccessMask|int cast + Keys->int cast + FramebufferErrorCode
# int cast + ref->out GL calls + Path ambiguity.
Update-FileInPlace $cpw {
param($t)
$t = [regex]::Replace($t, 'RuntimeHelpers\.InitializeArray\(array[0-9]*, \(RuntimeFieldHandle\)/\*OpCode not supported: LdMemberToken\*/\);', '// ILSpy: inline array init not supported')
# DrawBuffersEnum inline array fixups: replace zeroed arrays with correct initializers.
$t = [regex]::Replace($t, 'DrawBuffersEnum\[\] (\w+) = new DrawBuffersEnum\[4\];\s*// ILSpy: inline array init not supported\s*DrawBuffersEnum\[\] (\w+) = \(DrawBuffersEnum\[\]\)\(object\)\1;', 'DrawBuffersEnum[] $2 = new DrawBuffersEnum[4] { DrawBuffersEnum.ColorAttachment0, DrawBuffersEnum.ColorAttachment1, DrawBuffersEnum.ColorAttachment2, DrawBuffersEnum.ColorAttachment3 };')
$t = [regex]::Replace($t, 'DrawBuffersEnum\[\] (\w+) = new DrawBuffersEnum\[3\];\s*// ILSpy: inline array init not supported\s*DrawBuffersEnum\[\] (\w+) = \(DrawBuffersEnum\[\]\)\(object\)\1;', 'DrawBuffersEnum[] $2 = new DrawBuffersEnum[3] { DrawBuffersEnum.ColorAttachment0, DrawBuffersEnum.ColorAttachment1, DrawBuffersEnum.ColorAttachment2 };')
$t = [regex]::Replace($t, 'DrawBuffersEnum\[\] (\w+) = new DrawBuffersEnum\[4\];\s*// ILSpy: inline array init not supported\s*(\w+) = \(DrawBuffersEnum\[\]\)\(object\)\1;', '$2 = new DrawBuffersEnum[4] { DrawBuffersEnum.ColorAttachment0, DrawBuffersEnum.ColorAttachment1, DrawBuffersEnum.ColorAttachment2, DrawBuffersEnum.ColorAttachment3 };')
$t = $t -creplace '\(VSyncMode\)enabled', 'enabled ? VSyncMode.On : VSyncMode.Off'
$t = [regex]::Replace($t, '(?<![.\w])ErrorCode(?= error| val)', 'OpenTK.Graphics.OpenGL.ErrorCode')
$t = $t -creplace 'error != ErrorCode\.NoError', 'error != OpenTK.Graphics.OpenGL.ErrorCode.NoError'
# FramebufferErrorCode: cast int result and fix switch subtraction
$t = $t -creplace '\*\(FramebufferErrorCode\*\)\(&val\)', '((FramebufferErrorCode)val)'
$t = $t -creplace 'switch \(val - 36053\)', 'switch ((int)val - 36053)'
# GL ref -> out: for query/gen methods with nested casts in args (not ClearBuffer which uses ref as input)
$t = [regex]::Replace($t, '(GL\.(?:Get\w+|Gen\w+)\(.*?), ref (\w+)\)', '$1, out $2)')
# Path ambiguity in ClientPlatformWindows
$t = [regex]::Replace($t, '(?<![.\w])Path\.(?=DirectorySeparatorChar|Combine|GetTempPath|GetFileName|GetExtension|GetDirectoryName|GetFullPath)', 'System.IO.Path.')
# BufferAccessMask: val | int needs cast on the int literal or wrap in (int)val
$t = [regex]::Replace($t, '\(BufferAccessMask\)\(val \| (0x[0-9a-fA-F]+)\)', '(BufferAccessMask)((int)val | $1)')
# Keys enum to int: both the dictionary result AND the indexer need casts
$t = $t -creplace '= KeyConverter\.NewKeysToGlKeys\[e\.Key\]', '= (int)KeyConverter.NewKeysToGlKeys[(int)e.Key]'
$t
}
# LoadedSoundNative.cs + AudioOpenAl.cs - OpenTK AL ref->out, EFX using alias,
# ALFormat int cast. AL.GetSource/GetBuffer use 'out' not 'ref'; EFX needs a
# using alias; soundFormat arithmetic needs (int) cast; Vector3 constructors
# use 'new' not _002Ector.
$lsn = Join-Path $lib 'Vintagestory.Client/LoadedSoundNative.cs'
Update-FileInPlace $lsn {
param($t)
if ($t -cnotmatch 'using EFX = ') {
$t = $t -creplace '(?m)^using OpenTK\.Audio\.OpenAL;$', "using OpenTK.Audio.OpenAL;`nusing EFX = OpenTK.Audio.OpenAL.ALC.EFX;"
}
$t = [regex]::Replace($t, 'AL\.GetSource\(([^,]+), ([^,]+), ref ', 'AL.GetSource($1, $2, out ')
$t = [regex]::Replace($t, 'AL\.GetBuffer\(([^,]+), ([^,]+), ref ', 'AL.GetBuffer($1, $2, out ')
$t = $t -creplace 'soundFormat - 4354', '((int)soundFormat - 4354)'
$t = [regex]::Replace($t, '\(\(Vector3\)\(ref (\w+)\)\)\._002Ector\(', '$1 = new Vector3(')
$t
}
# AudioOpenAl.cs also uses EFX but the decompiler drops the using alias.
$aoa = Join-Path $lib 'Vintagestory.Client/AudioOpenAl.cs'
Update-FileInPlace $aoa {
param($t)
if ($t -cnotmatch 'using EFX = ') {
$t = $t -creplace '(?m)^using OpenTK\.Audio\.OpenAL;$', "using OpenTK.Audio.OpenAL;`nusing EFX = OpenTK.Audio.OpenAL.ALC.EFX;"
}
$t
}
# ClientProgram.cs - VSyncMode bool cast + ErrorCallback type alias.
$cprog = Join-Path $lib 'Vintagestory.Client/ClientProgram.cs'
Update-FileInPlace $cprog {
param($t)
if ($t -cnotmatch 'using ErrorCallback = ') {
$t = $t -creplace '(?m)^using OpenTK\.Windowing\.GraphicsLibraryFramework;$', "using OpenTK.Windowing.GraphicsLibraryFramework;`nusing ErrorCallback = OpenTK.Windowing.GraphicsLibraryFramework.GLFWCallbacks.ErrorCallback;"
}
$t = $t -creplace '\(VSyncMode\)\(ClientSettings\.VsyncMode != 0\)', 'ClientSettings.VsyncMode != 0 ? VSyncMode.On : VSyncMode.Off'
$t
}
# ClientPlatformWindows.cs - Ext.CheckFramebufferStatus -> GL.CheckFramebufferStatus,
# pointer cast simplification, FramebufferErrorCode subtraction needs (int) cast.
Update-FileInPlace $cpw {
param($t)
$t = $t -creplace 'Ext\.CheckFramebufferStatus', 'GL.CheckFramebufferStatus'
$t = $t -creplace '\(\(object\)\(\*\(FramebufferErrorCode\*\)\(&val\)\)/\*cast due to constrained\. prefix\*/\)\.ToString\(\)', 'val.ToString()'
$t = $t -creplace 'switch \(val - 36053\)', 'switch ((int)val - 36053)'
$t = $t -creplace '\*\(ErrorCode\*\)\(&error\)\)', '*(OpenTK.Graphics.OpenGL.ErrorCode*)(&error))'
$t