-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathbuild_common.ps1
1577 lines (1287 loc) · 51.7 KB
/
build_common.ps1
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
Write-Host "Build Common Loading"
$ErrorActionPreference = "Stop"
Set-StrictMode -Version 3.0
$global:buildCommonSelfPath = split-path -parent $MyInvocation.MyCommand.Definition
$cleanCookerOutput = Join-Path -Path $global:buildCommonSelfPath "clean_cooker_output.ps1"
Write-Host "Sourcing $cleanCookerOutput"
. $cleanCookerOutput
# list of all native script packages
$global:nativescriptpackages = @("XComGame", "Core", "Engine", "GFxUI", "AkAudio", "GameFramework", "UnrealEd", "GFxUIEditor", "IpDrv", "OnlineSubsystemPC", "OnlineSubsystemLive", "OnlineSubsystemSteamworks", "OnlineSubsystemPSN")
$global:def_robocopy_args = @("/S", "/E", "/COPY:DAT", "/PURGE", "/MIR", "/NP", "/R:1000000", "/W:30")
$global:invarCulture = [System.Globalization.CultureInfo]::InvariantCulture
class BuildProject {
[string] $modNameCanonical
[string] $modNameFull
[string] $projectRoot
[string] $sdkPath
[string] $gamePath
[string] $finalModPath
[string] $contentOptionsJsonFilename
[long] $publishID = -1
[bool] $debug = $false
[bool] $final_release = $false
[string[]] $include = @()
[string[]] $clean = @()
[object[]] $preMakeHooks = @()
# internals
[hashtable] $macroDefs = @{}
[object[]] $timings = @()
# lazily set
[string] $modSrcRoot
[string] $modX2projPath
[string] $devSrcRoot
[string] $stagingPath
[string] $xcomModPath
[string] $commandletHostPath
[string] $buildCachePath
[string] $cookerOutputPath
[string] $makeFingerprintsPath
[string[]] $modScriptPackages
[bool] $isHl
[bool] $cookHL
[PSCustomObject] $contentOptions
[string] $sdkEngineIniPath
[string] $sdkEngineIniContent
BuildProject(
[string]$mod,
[string]$projectRoot,
[string]$sdkPath,
[string]$gamePath
){
$this.modNameFull = $mod
$this.modNameCanonical = $mod -Replace '[\s;]',''
$this.projectRoot = $projectRoot
$this.sdkPath = $sdkPath
$this.gamePath = $gamePath
}
[void]SetContentOptionsJsonFilename($filename) {
$this.contentOptionsJsonFilename = $filename
}
[void]SetWorkshopID([long] $publishID) {
if ($publishID -le 0) { ThrowFailure "publishID must be >0" }
$this.publishID = $publishID
}
[void]EnableFinalRelease() {
$this.final_release = $true
$this._CheckFlags()
}
[void]EnableDebug() {
$this.debug = $true
$this._CheckFlags()
}
[void]AddPreMakeHook([Action[]] $action) {
$this.preMakeHooks += $action
}
[void]AddToClean([string] $modName) {
$this.clean += $modName
}
[void]IncludeSrc([string] $src) {
if (!(Test-Path $src)) { ThrowFailure "include path $src doesn't exist" }
$this.include += $src
}
[void]InvokeBuild() {
try {
$fullStopwatch = [Diagnostics.Stopwatch]::StartNew()
$this._ConfirmPaths()
$this._SetupUtils()
$this._LoadContentOptions()
if ($this._HasScriptPackages()) {
$this._PerformStep({ ($_)._CleanAdditional() }, "Cleaning", "Cleaned", "additional mods")
}
$this._PerformStep({ ($_)._CopyModToSdk() }, "Mirroring", "Mirrored", "mod to SDK")
$this._PerformStep({ ($_)._ConvertLocalization() }, "Converting", "Converted", "Localization UTF-8 -> UTF-16")
if ($this._ShouldCompileBase()) {
$this._PerformStep({ ($_)._CopyToSrc() }, "Populating", "Populated", "Development\Src folder")
$this._PerformStep({ ($_)._RunPreMakeHooks() }, "Running", "Ran", "Pre-Make hooks")
$this._PerformStep({ ($_)._CheckCleanCompiled() }, "Verifying", "Verified", "compiled script packages")
$this._PerformStep({ ($_)._RunMakeBase() }, "Compiling", "Compiled", "base-game script packages")
}
if ($this._HasScriptPackages()) {
$this._PerformStep({ ($_)._RunMakeMod() }, "Compiling", "Compiled", "mod script packages")
}
if ($this._ShouldCompileBase()) {
$this._RecordCoreTimestamp()
}
if ($this._HasScriptPackages()) {
if ($this.isHl) {
if (-not $this.debug) {
$this._PerformStep({ ($_)._RunCookHL() }, "Cooking", "Cooked", "Highlander packages")
} else {
Write-Host "Skipping HL cooking as debug build"
}
}
$this._PerformStep({ ($_)._CopyScriptPackages() }, "Copying", "Copied", "compiled script packages")
}
# The shader step needs to happen before asset cooking - precompiler gets confused by some inlined materials
$this._PerformStep({ ($_)._PrecompileShaders() }, "Precompiling", "Precompiled", "shaders")
$this._PerformStep({ ($_)._RunCookAssets() }, "Cooking", "Cooked", "mod assets")
# Do this last as there is no need for it earlier - the cooker obviously has access to the game assets
# and precompiling shaders seems to do nothing (I assume they are included in the game's GlobalShaderCache)
$this._PerformStep({ ($_)._CopyMissingUncooked() }, "Copying", "Copied", "requested uncooked packages")
$this._PerformStep({ ($_)._FinalCopy() }, "Copying", "Copied", "built mod to game directory")
$fullStopwatch.Stop()
$this._ReportTimings($fullStopwatch)
SuccessMessage "*** SUCCESS! ($(FormatElapsed $fullStopwatch.Elapsed)) ***" $this.modNameCanonical
}
catch {
[System.Media.SystemSounds]::Hand.Play()
throw
}
}
[void]_PerformStep([scriptblock]$stepCallback, [string]$progressWord, [string]$completedWord, [string]$description) {
Write-Host "$($progressWord) $($description)..."
$sw = [Diagnostics.Stopwatch]::StartNew()
# HACK: Set $_ for $stepCallback with Foreach-Object on only one object
$this | ForEach-Object $stepCallback
$sw.Stop()
$record = [PSCustomObject]@{
Description = "$($progressWord) $($description)"
Seconds = $sw.Elapsed.TotalSeconds
}
$this.timings += $record
Write-Host -ForegroundColor DarkGreen "$($completedWord) $($description) in $(FormatElapsed $sw.Elapsed)"
}
[void]_ReportTimings([Diagnostics.Stopwatch]$fullStopwatch) {
if (-not [string]::IsNullOrEmpty($env:X2MBC_REPORT_TIMINGS)) {
$fullTime = $fullStopwatch.Elapsed.TotalSeconds
$accountedTime = $this.timings | Measure-Object -Sum -Property Seconds | Select-Object -ExpandProperty Sum
$this.timings += [PSCustomObject]@{
Description = "Total Duration"
Seconds = $fullTime
}
$this.timings += [PSCustomObject]@{
Description = "Unaccounted time"
Seconds = $fullTime - $accountedTime
}
$this.timings | Sort-Object -Descending -Property { $_.Seconds } | ForEach-Object {
$_ | Add-Member -NotePropertyName "Share" -NotePropertyValue ($_.Seconds / $fullTime).ToString("0.00%", $global:invarCulture)
$_.Seconds = $_.Seconds.ToString("0.00s", $global:invarCulture)
$_
} | Format-Table | Out-String | Write-Host
}
}
[void]_CheckFlags() {
if ($this.debug -eq $true -and $this.final_release -eq $true)
{
ThrowFailure "-debug and -final_release cannot be used together"
}
}
[void]_ConfirmPaths() {
Write-Host "SDK Path: $($this.sdkPath)"
Write-Host "Game Path: $($this.gamePath)"
# Check if the user config is set up correctly
if (([string]::IsNullOrEmpty($this.sdkPath) -or $this.sdkPath -eq '${config:xcom.highlander.sdkroot}') -or ([string]::IsNullOrEmpty($this.gamePath) -or $this.gamePath -eq '${config:xcom.highlander.gameroot}'))
{
ThrowFailure "Please set up user config xcom.highlander.sdkroot and xcom.highlander.gameroot"
}
elseif (!(Test-Path $this.sdkPath)) # Verify the SDK and game paths exist before proceeding
{
ThrowFailure ("The path '{}' doesn't exist. Please adjust the xcom.highlander.sdkroot variable in your user config and retry." -f $this.sdkPath)
}
elseif (!(Test-Path $this.gamePath))
{
ThrowFailure ("The path '{}' doesn't exist. Please adjust the xcom.highlander.gameroot variable in your user config and retry." -f $this.gamePath)
}
}
[void]_SetupUtils() {
$this.modSrcRoot = "$($this.projectRoot)\$($this.modNameFull)"
$this.modX2projPath = "$($this.modSrcRoot)\$($this.modNameFull).x2proj"
$this.stagingPath = "$($this.sdkPath)\XComGame\Mods\$($this.modNameCanonical)"
$this.xcomModPath = "$($this.stagingPath)\$($this.modNameCanonical).XComMod"
$this.finalModPath = "$($this.gamePath)\XComGame\Mods\$($this.modNameCanonical)"
$this.devSrcRoot = "$($this.sdkPath)\Development\Src"
$this.commandletHostPath = "$($this.sdkPath)/binaries/Win64/XComGame.com"
# build package lists we'll need later and delete as appropriate
# the mod's packages
$modSrcPath = "$($this.modSrcRoot)/Src"
if (Test-Path $modSrcPath) {
$this.modScriptPackages = @(Get-ChildItem "$($this.modSrcRoot)/Src" -Directory)
} else {
# No scripts to compile
$this.modScriptPackages = @()
}
if (!$this._HasScriptPackages()) {
if ($this.clean.Length -gt 0) {
ThrowFailure "AddToClean is not supported when no script packages to compile"
}
if ($this.include.Length -gt 0) {
ThrowFailure "IncludeSrc is not supported when no script packages to compile"
}
if ($this.preMakeHooks.Length -gt 0) {
ThrowFailure "AddPreMakeHook is not supported when no script packages to compile"
}
if ($this.debug) {
ThrowFailure "Debug build enabled but no script packages to compile"
}
}
$this.isHl = $this._HasNativePackages()
$this.cookHL = $this.isHl -and -not $this.debug
if (-not $this.isHl -and $this.final_release) {
ThrowFailure "-final_release only makes sense if the mod in question is a Highlander"
}
$this.cookerOutputPath = [io.path]::combine($this.sdkPath, 'XComGame', 'Published', 'CookedPCConsole')
$this.buildCachePath = [io.path]::combine($this.projectRoot, 'BuildCache')
if (!(Test-Path $this.buildCachePath))
{
New-Item -ItemType "directory" -Path $this.buildCachePath
}
$this.sdkEngineIniPath = "$($this.sdkPath)/XComGame/Config/DefaultEngine.ini"
$this.sdkEngineIniContent = Get-Content $this.sdkEngineIniPath | Out-String
$this.makeFingerprintsPath = "$($this.sdkPath)\XComGame\lastBuildDetails.json"
$lastBuildDetails = if (Test-Path $this.makeFingerprintsPath) {
Get-Content $this.makeFingerprintsPath | ConvertFrom-Json
} else {
[PSCustomObject]@{}
}
@("buildMode", "globalsHash", "coreTimestamp") | ForEach-Object {
if(-not (Get-Member -InputObject $lastBuildDetails -name $_ -Membertype Properties)) {
$lastBuildDetails | Add-Member -NotePropertyName $_ -NotePropertyValue "unknown"
}
}
$lastBuildDetails | ConvertTo-Json | Set-Content -Path $this.makeFingerprintsPath
}
[void]_LoadContentOptions() {
Write-Host "Preparing content options"
if ([string]::IsNullOrEmpty($this.contentOptionsJsonFilename))
{
$this.contentOptions = [PSCustomObject]@{}
}
else
{
$contentOptionsJsonPath = Join-Path $this.modSrcRoot $this.contentOptionsJsonFilename
if (!(Test-Path $contentOptionsJsonPath)) {
ThrowFailure "ContentOptionsJsonPath $contentOptionsJsonPath doesn't exist"
}
$this.contentOptions = Get-Content $contentOptionsJsonPath | ConvertFrom-Json
Write-Host "Loaded $($contentOptionsJsonPath)"
}
if (($this.contentOptions.PSobject.Properties | ForEach-Object {$_.Name}) -notcontains "missingUncooked")
{
Write-Host "No missing uncooked"
$this.contentOptions | Add-Member -MemberType NoteProperty -Name 'missingUncooked' -Value @()
}
if (($this.contentOptions.PSobject.Properties | ForEach-Object {$_.Name}) -notcontains "sfStandalone")
{
Write-Host "No packages to make SF"
$this.contentOptions | Add-Member -MemberType NoteProperty -Name 'sfStandalone' -Value @()
}
if (($this.contentOptions.PSobject.Properties | ForEach-Object {$_.Name}) -notcontains "sfMaps")
{
Write-Host "No umaps to cook"
$this.contentOptions | Add-Member -MemberType NoteProperty -Name 'sfMaps' -Value @()
}
if (($this.contentOptions.PSobject.Properties | ForEach-Object {$_.Name}) -notcontains "sfCollectionMaps")
{
Write-Host "No collection maps to cook"
$this.contentOptions | Add-Member -MemberType NoteProperty -Name 'sfCollectionMaps' -Value @()
}
}
[void]_CopyModToSdk() {
$xf = @("*.x2proj")
if (![string]::IsNullOrEmpty($this.contentOptionsJsonFilename)) {
$xf += $this.contentOptionsJsonFilename
}
Write-Host "Copying mod project to staging..."
Robocopy.exe "$($this.modSrcRoot)" "$($this.stagingPath)" *.* $global:def_robocopy_args /XF @xf /XD "ContentForCook"
Write-Host "Copied project to staging."
if ($this._HasScriptPackages()) {
New-Item "$($this.stagingPath)/Script" -ItemType Directory
}
# read mod metadata from the x2proj file
Write-Host "Reading mod metadata from $($this.modX2ProjPath)"
[xml]$x2projXml = Get-Content -Path "$($this.modX2ProjPath)"
$xmlPropertyGroup = $x2projXml.Project.PropertyGroup
$modProperties = if ($xmlPropertyGroup -is [array]) { $xmlPropertyGroup[0] } else { $xmlPropertyGroup }
$publishedId = $modProperties.SteamPublishID
if ($this.publishID -ne -1) {
$publishedId = $this.publishID
Write-Host "Using override workshop ID of $publishedId"
}
$title = $modProperties.Name
$description = $modProperties.Description
Write-Host "Read."
Write-Host "Writing mod metadata..."
Set-Content "$($this.xcomModPath)" "[mod]`npublishedFileId=$publishedId`nTitle=$title`nDescription=$description`nRequiresXPACK=true"
Write-Host "Written."
# Create CookedPCConsole folder for the mod
if ($this.cookHL) {
New-Item "$($this.stagingPath)/CookedPCConsole" -ItemType Directory
}
}
[void]_CleanAdditional() {
# clean
foreach ($modName in $this.clean) {
$cleanDir = "$($this.sdkPath)/XComGame/Mods/$($modName)"
if (Test-Path $cleanDir) {
Write-Host "Cleaning $($modName)..."
Remove-Item -Recurse -Force $cleanDir
}
}
}
[void]_ConvertLocalization() {
Get-ChildItem "$($this.stagingPath)\Localization" -Recurse -File |
Foreach-Object {
$content = Get-Content $_.FullName -Encoding UTF8
$content | Out-File $_.FullName -Encoding Unicode
}
}
[void]_CopyToSrc() {
# mirror the SDK's SrcOrig to its Src
Write-Host "Mirroring SrcOrig to Src..."
Robocopy.exe "$($this.sdkPath)\Development\SrcOrig" "$($this.devSrcRoot)" *.uc *.uci $global:def_robocopy_args
Write-Host "Mirrored SrcOrig to Src."
$this._ParseMacroFile("$($this.devSrcRoot)\Core\Globals.uci")
# Copy dependencies
Write-Host "Copying dependency sources to Src..."
foreach ($depfolder in $this.include) {
Get-ChildItem "$($depfolder)" -Directory -Name | Write-Host
$this._CopySrcFolder($depfolder)
}
Write-Host "Copied dependency sources to Src."
if ($this._HasScriptPackages()) {
# copying the mod's scripts to the script staging location
Write-Host "Copying the mod's sources to Src..."
$this._CopySrcFolder("$($this.modSrcRoot)\Src")
Write-Host "Copied mod sources to Src."
}
}
[void]_CopySrcFolder([string] $includeDir) {
Copy-Item "$($includeDir)\*" "$($this.devSrcRoot)\" -Force -Recurse -WarningAction SilentlyContinue
$extraGlobalsFile = "$($includeDir)\extra_globals.uci"
if (Test-Path $extraGlobalsFile) {
# append extra_globals.uci to globals.uci
"// Macros included from $($extraGlobalsFile)" | Add-Content "$($this.devSrcRoot)\Core\Globals.uci"
Get-Content $extraGlobalsFile | Add-Content "$($this.devSrcRoot)\Core\Globals.uci"
$this._ParseMacroFile($extraGlobalsFile)
}
}
[void]_ParseMacroFile([string]$file) {
$lines = Get-Content $file
# check for dupes
$redefine = $false
$lineNr = 1
foreach ($line in $lines) {
$defineMatch = $line | Select-String -Pattern '^\s*`define\s*([a-zA-Z][a-zA-Z0-9_]*)'
if ($null -ne $defineMatch -and $defineMatch.Matches.Success) {
[string]$macroName = $defineMatch.Matches.Groups[1]
$prevDef = $this.macroDefs[$macroName]
if ($null -ne $prevDef -and
-not $redefine -and
$prevDef.file -ne $file) {
Write-Host -ForegroundColor Red "Error: Implicit redefinition of macro $($macroName)"
$defineWord = if ($prevDef.redefine) { "redefined" } else { "defined" }
Write-Host " Note: Previously $($defineWord) at $($prevDef.file)($($prevDef.lineNr))"
Write-Host " Note: Implicitly redefined at $($file)($($lineNr))"
Write-Host " Help: Rename the macro, or add ``// X2MBC-Redefine`` above to explicitly redefine and silence this warning."
ThrowFailure "Implicit macro redefinition."
}
$macroDef = [PSCustomObject]@{
file = $file
lineNr = $lineNr
redefine = $redefine
}
$this.macroDefs[$macroName] = $macroDef
} elseif ($line -match '^\s*`define') {
ThrowFailure "Unrecognized macro at $($file)($($line)). This is a bug in X2ModBuildCommon."
}
$redefine = $line -match "X2MBC-Redefine"
$lineNr += 1
}
}
[void]_RunPreMakeHooks() {
foreach ($hook in $this.preMakeHooks) {
$hook.Invoke()
}
}
[string]_GetCoreMtime() {
if (Test-Path "$($this.sdkPath)/XComGame/Script/Core.u") {
return Get-Item "$($this.sdkPath)/XComGame/Script/Core.u" | Select-Object -ExpandProperty LastWriteTime
} else {
return "missing"
}
}
[void]_CheckCleanCompiled() {
# #16: Switching between debug and release causes an error in the make commandlet if script packages aren't deleted.
# #20: Changes to Globals.uci aren't tracked by UCC, so we must delete script packages if Globals.uci changes.
$lastBuildDetails = Get-Content $this.makeFingerprintsPath | ConvertFrom-Json
$buildMode = if ($this.debug -eq $true) { "debug" } else { "release" }
$globalsHash = Get-FileHash "$($this.sdkPath)\Development\Src\Core\Globals.uci" | Select-Object -ExpandProperty Hash
$coreTimeStamp = $this._GetCoreMtime()
$rebuild = if ($lastBuildDetails.buildMode -ne $buildMode) {
Write-Host "Detected switch between debug and non-debug build."
$true
} elseif ($lastBuildDetails.coreTimestamp -ne $coreTimeStamp) {
Write-Host "Detected previous external rebuild."
$true
} elseif ($lastBuildDetails.globalsHash -ne $globalsHash) {
Write-Host "Detected change in macros (Globals.uci)."
$true
} else {
$false
}
# Order: Deleting first cannot cause an issue because the compiler will just rebuild.
if ($rebuild) {
Write-Host "Cleaning all compiled scripts from $($this.sdkPath)/XComGame/Script to avoid compiler error..."
Remove-Item "$($this.sdkPath)/XComGame/Script/*.u"
Write-Host "Cleaned."
}
$lastBuildDetails.buildMode = $buildMode
$lastBuildDetails.globalsHash = $globalsHash
# Similarly, recording the previous invocation fingerprints before the build is complete
# cannot cause an issue because the compiler will simply continue an interrupted build.
$lastBuildDetails | ConvertTo-Json | Set-Content -Path $this.makeFingerprintsPath
}
[void]_RecordCoreTimestamp() {
# Unfortunately, ModBuddy with Fxs' plugin can rebuild the packages under our nose.
# As a last resort, record the Core.u timestamp
$lastBuildDetails = Get-Content $this.makeFingerprintsPath | ConvertFrom-Json
$lastBuildDetails.coreTimestamp = $this._GetCoreMtime()
$lastBuildDetails | ConvertTo-Json | Set-Content -Path $this.makeFingerprintsPath
}
[void]_RunMakeBase() {
# build the base game scripts
$scriptsMakeArguments = "make -nopause -unattended"
if ($this.final_release -eq $true)
{
$scriptsMakeArguments = "$scriptsMakeArguments -final_release"
}
if ($this.debug -eq $true)
{
$scriptsMakeArguments = "$scriptsMakeArguments -debug"
}
$handler = [MakeStdoutReceiver]::new($this)
$handler.processDescr = "compiling base game scripts"
$this._InvokeEditorCmdlet($handler, $scriptsMakeArguments, 50)
# If we build in final release, we must build the normal scripts too
if ($this.final_release -eq $true)
{
Write-Host "Compiling base game scripts without final_release..."
$scriptsMakeArguments = "make -nopause -unattended"
$handler = [MakeStdoutReceiver]::new($this)
$handler.processDescr = "compiling base game scripts"
$this._InvokeEditorCmdlet($handler, $scriptsMakeArguments, 50)
}
}
[void]_RunMakeMod() {
# build the mod's scripts
$scriptsMakeArguments = "make -nopause -mods $($this.modNameCanonical) $($this.stagingPath)"
if ($this.debug -eq $true)
{
$scriptsMakeArguments = "$scriptsMakeArguments -debug"
}
$handler = [MakeStdoutReceiver]::new($this)
$handler.processDescr = "compiling mod scripts"
$this._InvokeEditorCmdlet($handler, $scriptsMakeArguments, 50)
}
[bool]_HasNativePackages() {
# Check if this is a Highlander and we need to cook things
$anynative = $false
foreach ($name in $this.modScriptPackages)
{
if ($global:nativescriptpackages.Contains($name)) {
$anynative = $true
break
}
}
return $anynative
}
[bool] _HasScriptPackages () {
return $this.modScriptPackages.Length -gt 0
}
[bool] _ShouldCompileBase () {
if ($this._HasScriptPackages()) {
return $true
}
# We need to compile base game scripts if cooking assets, otherwise the cooker will just crash if the SDK was cleaned beforehand
if ($this._AnyAssetsToCook()) {
return $true
}
return $false
}
[void]_CopyScriptPackages() {
# copy packages to staging
foreach ($name in $this.modScriptPackages) {
if ($this.cookHL -and $global:nativescriptpackages.Contains($name))
{
# This is a native (cooked) script package -- copy important upks
Copy-Item "$($this.cookerOutputPath)\$name.upk" "$($this.stagingPath)\CookedPCConsole" -Force -WarningAction SilentlyContinue
Copy-Item "$($this.cookerOutputPath)\$name.upk.uncompressed_size" "$($this.stagingPath)\CookedPCConsole" -Force -WarningAction SilentlyContinue
Write-Host "$($this.cookerOutputPath)\$name.upk"
}
else
{
# Or this is a non-native package
Copy-Item "$($this.sdkPath)\XComGame\Script\$name.u" "$($this.stagingPath)\Script" -Force -WarningAction SilentlyContinue
Write-Host "$($this.sdkPath)\XComGame\Script\$name.u"
}
}
}
[void]_PrecompileShaders() {
Write-Host "Checking the need to PrecompileShaders"
$contentfiles = @()
# We don't need to consider
# .umaps - they will never contain material (instances) objects - only reference them
# ContentForCook - seekfree packages have an inlined shader cache
if (Test-Path "$($this.modSrcRoot)/Content")
{
$contentfiles += Get-ChildItem "$($this.modSrcRoot)/Content" -Include *.upk -Recurse -File
}
if ($contentfiles.length -eq 0) {
Write-Host "No content files, skipping PrecompileShaders."
return
}
# for ($i = 0; $i -lt $contentfiles.Length; $i++) {
# Write-Host $contentfiles[$i]
# }
$need_shader_precompile = $false
$shaderCacheName = "$($this.modNameCanonical)_ModShaderCache.upk"
$cachedShaderCachePath = "$($this.buildCachePath)/$($shaderCacheName)"
# Try to find a reason to precompile the shaders
if (!(Test-Path -Path $cachedShaderCachePath))
{
$need_shader_precompile = $true
}
elseif ($contentfiles.length -gt 0)
{
$shader_cache = Get-Item $cachedShaderCachePath
foreach ($file in $contentfiles)
{
if ($file.LastWriteTime -gt $shader_cache.LastWriteTime -Or $file.CreationTime -gt $shader_cache.LastWriteTime)
{
$need_shader_precompile = $true
break
}
}
}
if ($need_shader_precompile)
{
# build the mod's shader cache
Write-Host "Precompiling Shaders..."
$precompileShadersFlags = "precompileshaders -nopause platform=pc_sm4 DLC=$($this.modNameCanonical)"
$handler = [PassthroughReceiver]::new()
$handler.processDescr = "precompiling shaders"
$this._InvokeEditorCmdlet($handler, $precompileShadersFlags, 10)
Write-Host "Generated Shader Cache."
Copy-Item -Path "$($this.stagingPath)/Content/$shaderCacheName" -Destination $this.buildCachePath
}
else
{
Write-Host "No reason to precompile shaders, using existing"
Copy-Item -Path $cachedShaderCachePath -Destination "$($this.stagingPath)/Content"
}
}
[void]_RunCookAssets() {
$step = [ModAssetsCookStep]::new($this)
$step.Execute()
}
[void]_RunCookHL() {
$this._EnsureCookerOutputDirExists()
# Cook it
# Normally, the mod tools create a symlink in the SDK directory to the game CookedPCConsole directory,
# but we'll just be using the game one to make it more robust
$cookedpcconsoledir = [io.path]::combine($this.gamePath, 'XComGame', 'CookedPCConsole')
[System.String[]]$files = "GuidCache.upk", "GlobalPersistentCookerData.upk", "PersistentCookerShaderData.bin"
foreach ($name in $files) {
if(-not(Test-Path ([io.path]::combine($this.cookerOutputPath, $name))))
{
Write-Host "Copying $name..."
Copy-Item ([io.path]::combine($cookedpcconsoledir, $name)) $this.cookerOutputPath
}
}
# Ideally, the cooking process wouldn't modify the big *.tfc files, but it does, so we don't overwrite existing ones (/XC /XN /XO)
# In order to "reset" the cooking direcory, just delete it and let the script recreate them
Write-Host "Copying Texture File Caches..."
Robocopy.exe "$cookedpcconsoledir" "$($this.cookerOutputPath)" *.tfc /NJH /XC /XN /XO
Write-Host "Copied Texture File Caches."
# Prepare editor args
$cook_args = @("cookpackages", "-platform=pcconsole", "-quickanddirty", "-modcook", "-sha", "-multilanguagecook=INT+FRA+ITA+DEU+RUS+POL+KOR+ESN", "-singlethread", "-nopause")
if ($this.final_release -eq $true)
{
$cook_args += "-final_release"
}
# The CookPackages commandlet generally is super unhelpful. The output is basically always the same and errors
# don't occur -- it rather just crashes the game. Hence, we just buffer the output and present it to user only
# if something went wrong
# TODO: Filter more lines for HL cook? `Hashing`? `SHA: package not found`? `Couldn't find localized resource`?
# `Warning, Texture file cache waste exceeds`? `Warning, Package _ is not conformed`?
$handler = [BufferingReceiver]::new()
$handler.processDescr = "cooking native packages"
# Cook it!
Write-Host "Invoking CookPackages (this may take a while)"
$this._InvokeEditorCmdlet($handler, $cook_args, 10)
}
[void] _EnsureCookerOutputDirExists () {
if(-not(Test-Path $this.cookerOutputPath)) {
Write-Host "Creating Published/CookedPCConsole directory..."
New-Item $this.cookerOutputPath -ItemType Directory
}
}
[void]_CopyMissingUncooked() {
if ($this.contentOptions.missingUncooked.Length -lt 1)
{
Write-Host "Skipping Missing Uncooked logic"
return
}
Write-Host "Including MissingUncooked"
$missingUncookedPath = [io.path]::Combine($this.stagingPath, "Content", "MissingUncooked")
$sdkContentPath = [io.path]::Combine($this.sdkPath, "XComGame", "Content")
if (!(Test-Path $missingUncookedPath))
{
New-Item -ItemType "directory" -Path $missingUncookedPath
}
foreach ($fileName in $this.contentOptions.missingUncooked)
{
(Get-ChildItem -Path $sdkContentPath -Filter $fileName -Recurse).FullName | Copy-Item -Destination $missingUncookedPath
}
}
[void]_FinalCopy() {
# copy all staged files to the actual game's mods folder
# TODO: Is the string interpolation required in the robocopy calls?
Robocopy.exe "$($this.stagingPath)" "$($this.finalModPath)" *.* $global:def_robocopy_args
}
[string[]] _PrepareBuildCacheEngineIniWithAdditions ([string] $fileNamePrefix, [array] $lines) {
$localDefaultEngineIniPath = [io.path]::combine($this.buildCachePath, $fileNamePrefix + "_DefaultEngine.ini")
$localXComEngineIniPath = [io.path]::combine($this.buildCachePath, $fileNamePrefix + "_XComEngine.ini")
$newEngineIniContent = $this.sdkEngineIniContent + "`n" + ($lines -join "`n") + "`n"
$newEngineIniContent | Set-Content $localDefaultEngineIniPath -NoNewline
return @($localDefaultEngineIniPath, $localXComEngineIniPath)
}
[void]_InvokeEditorCmdlet([StdoutReceiver] $receiver, [string] $makeFlags, [int] $sleepMsDuration) {
# Create a ProcessStartInfo object to hold the details of the make command, its arguments, and set up
# stdout/stderr redirection.
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = $this.commandletHostPath
$pinfo.RedirectStandardOutput = $true
$pinfo.RedirectStandardError = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = $makeFlags
$pinfo.WorkingDirectory = $this.commandletHostPath | Split-Path
# Set the exited flag on our exit object on process exit.
# We need another object for the Exited event to set a flag we can monitor from this function.
$exitData = New-Object psobject -property @{ exited = $false }
$exitAction = {
$event.MessageData.exited = $true
}
# An action for handling data written to stderr. The Cmdlets don't seem to write anything here,
# or at least not diagnostics, so we can just pass it through.
$errAction = {
$errTxt = $Event.SourceEventArgs.Data
Write-Host $errTxt
}
$messageData = New-Object psobject -property @{
handler = $receiver
}
# Create an stdout filter action delegating to the actual implementation
$outAction = {
[StdoutReceiver] $handler = $event.MessageData.handler
[string] $outTxt = $Event.SourceEventArgs.Data
$handler.ParseLine($outTxt)
}
# Create the process and register for the various events we care about.
$process = New-Object System.Diagnostics.Process
Register-ObjectEvent -InputObject $process -EventName OutputDataReceived -Action $outAction -MessageData $messageData | Out-Null
Register-ObjectEvent -InputObject $process -EventName ErrorDataReceived -Action $errAction | Out-Null
Register-ObjectEvent -InputObject $process -EventName Exited -Action $exitAction -MessageData $exitData | Out-Null
$process.StartInfo = $pinfo
# All systems go!
$process.Start() | Out-Null
$process.BeginOutputReadLine()
$process.BeginErrorReadLine()
# Wait for the process to exit. This is horrible, but using $process.WaitForExit() blocks
# the powershell thread so we get no output from make echoed to the screen until the process finishes.
# By polling we get regular output as it goes.
try {
if ($sleepMsDuration -lt 1) {
while (!$exitData.exited) {
# Just spin
}
} else {
while (!$exitData.exited) {
Start-Sleep -m $sleepMsDuration
}
}
}
finally {
# If we are stopping MSBuild hosted build, we need to kill the editor manually
if (!$exitData.exited) {
Write-Host "Killing $($receiver.processDescr) tree"
KillProcessTree $process.Id
}
}
$exitCode = $process.ExitCode
$receiver.Finish($exitCode)
}
[bool] _AnyAssetsToCook () {
return ($this.contentOptions.sfStandalone.Length -gt 0) -or ($this.contentOptions.sfMaps.Length -gt 0) -or ($this.contentOptions.sfCollectionMaps.Length -gt 0)
}
}
class ModAssetsCookStep {
[BuildProject] $project
[string] $xpackTfcSuffix = '_XPACK_'
[string] $actualTfcSuffix
[string] $contentForCookPath
[string] $collectionMapsPath
[string] $sdkContentModsDir
[string] $sdkContentModsOurDir
[string[]] $dirtyMaps
[string[]] $cookedMaps
[string[]] $sfCollectionOnlyMaps
[string] $engineIniDefaultPath
[string] $engineIniXComPath
[string] $editorArgs
[string] $cookerOutputTrackerPath
[object] $cookerOutputTracker
ModAssetsCookStep ([BuildProject] $project) {
$this.project = $project
}
[void] Execute() {
if (!$this.project._AnyAssetsToCook()) {
Write-Host "No asset cooking is requested, skipping"
return
# TODO: Check if there are any assets in ContentForCook when no cooking is configured
}
Write-Host "Initializing assets cooking"
$this._Init()
$this._VerifyProjectAndSdk()
Write-Host "Preparing assets cooking"
$this._PrepareSdkFolders()
$this._PrepareProjectCache()
$this._VerifyCachedTfcsNotAltered() # Needs to be after _PrepareProjectCache (CollectionMaps are created) and _PrepareSdkFolders (otherwise Get-ChildItem for TFCs fails)
$this._VerifyCachedSfPackagesNotAltered()
$this._DetermineDirtyMaps()
$this._PrepareEngineIni()
$this._PrepareEditorArgs()
Write-Host "Starting assets cooking"
$this._ExecuteCore()
$this._WarnTfcGrowth()
$this._RecordCookerOutputTracker()
$this._StageArtifacts()
Write-Host "Assets cook completed"
}
[void] _Init() {
$this.actualTfcSuffix = "_$($this.project.modNameCanonical)_DLCTFC$($this.xpackTfcSuffix)"
$this.contentForCookPath = "$($this.project.modSrcRoot)\ContentForCook"
$this.collectionMapsPath = [io.path]::combine($this.project.buildCachePath, 'CollectionMaps')
$this.sdkContentModsDir = [io.path]::combine($this.project.sdkPath, 'XComGame', 'Content', 'Mods')
$this.sdkContentModsOurDir = [io.path]::combine($this.sdkContentModsDir, $this.project.modNameCanonical)
$this.cookedMaps = @($this.project.contentOptions.sfMaps)
foreach ($mapDef in $this.project.contentOptions.sfCollectionMaps) {
$this.cookedMaps += $mapDef.name
}
$this.sfCollectionOnlyMaps = @()
foreach ($mapDef in $this.project.contentOptions.sfCollectionMaps) {
if ($null -eq (Get-ChildItem -Path $this.contentForCookPath -Filter $mapDef.name -Recurse)) {
$this.sfCollectionOnlyMaps += $mapDef.name
}
}
$this.cookerOutputTrackerPath = [io.path]::combine($this.project.buildCachePath, 'AssetsCookerOutputTracker.json')
if (Test-Path $this.cookerOutputTrackerPath) {
$this.cookerOutputTracker = Get-Content $this.cookerOutputTrackerPath | ConvertFrom-Json
} else {
$this.cookerOutputTracker = [PSCustomObject]@{
tfcFiles = @() # Assume no TFCs if no info is stored. This will cause a full recook if any are found
sfPackages = @()
}
}
}
[void] _VerifyProjectAndSdk() {
# TODO: consider removing this requirement.
# It might be legitimate use case to cook a "secondary" vanilla package or a collection map that consists of only vanilla packages
if (-not(Test-Path $this.contentForCookPath))
{
ThrowFailure "Asset cooking is requested, but no ContentForCook folder is present"
}
if (Test-Path $this.sdkContentModsOurDir) {
# If we have any files, then something is happening here - abort
if ($null -ne (Get-ChildItem -Path $this.sdkContentModsOurDir -Force -Recurse)) {
ThrowFailure "$($this.sdkContentModsOurDir) is already in use (not empty)"
}
}
# The DLC cooker needs to read/copy the shipped GPCD
$shippedGpcdPath = [io.path]::combine($this.project.sdkPath, 'XComGame', 'CookedPCConsole', 'GlobalPersistentCookerData.upk')
if (!(Test-Path $shippedGpcdPath)) {
ThrowFailure "$shippedGpcdPath does not exist. Please verify your that your SDK is configured correctly"
}
}
[void] _PrepareProjectCache() {
# Prep the folder for the collection maps
# Not the most efficient approach, but there are bigger time saves to be had
Remove-Item $this.collectionMapsPath -Force -Recurse -WarningAction SilentlyContinue -ErrorAction SilentlyContinue
New-Item -ItemType "directory" -Path $this.collectionMapsPath
foreach ($map in $this.sfCollectionOnlyMaps) {
# Important: we cannot use .umap extension here - git lfs (if in use) gets confused during git subtree add
# See https://github.com/X2CommunityCore/X2ModBuildCommon/wiki/Do-not-use-.umap-for-files-in-this-repo
Copy-Item "$global:buildCommonSelfPath\EmptyUMap" "$($this.collectionMapsPath)\$map.umap"
}
}
[void] _VerifyCachedTfcsNotAltered () {
if (!$this._CheckCachedTfcsNotAltered()) {
Write-Host "Performing a full recook"
CleanModAssetCookerOutput $this.project.sdkPath $this.project.modNameCanonical @($this.contentForCookPath, $this.collectionMapsPath)
# Save that everything is deleted
$this.cookerOutputTracker.tfcFiles = @()
$this._RecordCookerOutputTracker()
}
}