-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathToastPRP.ps1
More file actions
1196 lines (1064 loc) · 43.9 KB
/
Copy pathToastPRP.ps1
File metadata and controls
1196 lines (1064 loc) · 43.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
param(
[switch]$Debug,
[string]$OneOff = $null,
[switch]$iknowwhatimdoing,
[switch]$toast
)
Write-Information "Running ToastPRP.ps1"
Add-Type -AssemblyName System.Windows.Forms
# If you have multiple installs of fallout 4 on one machine (You masochist....) make a copy of this script and change the $fo4 variable to the path of the second install and delete the regkey variable.
$script:regkey = 'HKLM:\Software\Wow6432Node\Bethesda Softworks\Fallout4'
if (!(Test-Path 'HKLM:\Software\Wow6432Node\Bethesda Softworks\Fallout4')) {
Write-Error "Registry key for Fallout 4 could not be found, please run the fallout 4 launcher executable before trying to run this script again."
return
}
$script:fo4 = Get-ItemPropertyValue -Path $script:regkey -Name 'installed path' -ErrorAction Stop
$script:data = Join-Path $fo4 "data"
$script:CK = "ckpe_loader.exe", "f4ck_loader.exe", "creationkit.exe" | Where-Object { Test-Path $_ } | Select-Object -First 1
$script:Archive2 = Join-Path $script:data "tools\archive2\archive2.exe"
$script:previsESP = Join-Path $script:data "PreVis.esp"
$script:PrevisDIR = Join-Path $script:data "vis"
$script:CombinedESP = Join-Path $script:data "CombinedObjects.esp"
$script:workingdir = Join-Path $script:data "workingdir"
$script:Meshesdir = Join-Path $script:data "Meshes"
$script:jsonFileName = "ToastPRP.json"
$script:jsonFilePath = Join-Path $script:fo4 $script:jsonFileName
$script:bsarch = Join-Path $script:fo4 "bsarch.exe"
$script:done = "$([char]27)[32mDone!$([char]27)[0m"
$script:PJMLog = "Toast-PJM-{0:MM-dd-yyyy-HH-mm}.log" -f (Get-Date)
#PEBKAC
switch ($true) {
($toast -eq $true) {
Write-Host "Toast mode enabled. Skipping confirmations and warnings." -ForegroundColor Blue
$iknowwhatimdoing = $true
$debug = $true
break
}
($iknowwhatimdoing -eq $false) {
if ((Get-ChildItem -Path (Join-Path $script:Meshesdir "Precombined") -ErrorAction SilentlyContinue) -or (Get-ChildItem -Path $script:workingdir -ErrorAction SilentlyContinue)) {
Write-Host "[UNKNOWN PRECOMBINED FILES DETECTED]" -ForegroundColor Red
Write-Output "This may be due to currently loaded mods which have unpacked precombines, or leftover files from previous script failure(s)."
Write-Host "THIS WILL MOST LIKELY CAUSE ISSUES DOWN THE LINE, HEED THIS WARNING!!!!" -ForegroundColor Red
$script:yn = Read-Host "Do you wish to continue(Y) or close the script(N)?"
If ($yn -eq "n") {
Write-Host "Please find the origin of these files and either pack them into an archive or remove them to prevent any issues during generation." -ForegroundColor Red
if ($host.Name -eq "ConsoleHost") {
Stop-Transcript
exit
}
else {
exit
}
}
}
}
($iknowwhatimdoing -eq $true) {
$confirmation = Read-Host "Please type 'I know what I'm doing' to continue, caps don't matter"
if ($confirmation -eq "I know what I'm doing" -or $confirmation -eq "i know what i'm doing") {
Write-Host "Confirmation received. Continuing..."
$iknowwhatimdoing = $true
$debug = $true
Write-Host "iknowwhatimdoing mode enabled" -ForegroundColor Yellow
Set-PSReadLineOption -ContinuationPrompt "=> "
}
else {
Write-Host "Incorrect confirmation. Exiting script."
exit
}
break
}
}
# Check for debug mode after the switch
if ($iknowwhatimdoing -or $Debug -or $toast) {
Write-Host "Debug mode enabled, all debug output will be displayed in the color Yellow" -ForegroundColor Yellow
}
function Log2Transcript {
param(
[string]$sourceFilePath
)
# Get the full path of the source file
$fullSourcePath = Join-Path $PWD $sourceFilePath
# Check if the source file exists
if (-not (Test-Path $fullSourcePath)) {
Write-Error "Source file not found: $fullSourcePath"
return
}
# Read the specified file
$fileContent = Get-Content -Path $fullSourcePath -Raw
# Set InformationPreference to Continue to ensure Write-Information works
$oldInfoPref = $InformationPreference
$InformationPreference = 'Continue'
try {
# Write the log entry using Write-Information and redirect output
& { Write-Information "$(Get-Date): $fileContent" } 6>&1 > $null -Wait
Write-Host "Log entry added to transcript." -ForegroundColor Green
} catch {
Write-Error "Failed to write to transcript: $_"
} finally {
# Restore the original InformationPreference
$InformationPreference = $oldInfoPref
}
}
function Write-CustomDebug {
param (
[object]$Message
)
if ($iknowwhatimdoing -eq $true) {
if ($Message -is [hashtable]) {
$tableData = @()
foreach ($key in $Message.Keys) {
$tableData += [PSCustomObject]@{
Key = $key
Value = $Message[$key]
}
}
$tableData | Format-Table -AutoSize
}
else {
Write-Output "$([char]27)[33m$Message$([char]27)[0m"
}
}
}
function Rename-Texture {
param (
[string]$Caller,
[switch]$BA2, # Parameter to indicate conversion to .ba2
[switch]$BA22, # Parameter to indicate conversion to .ba22
[switch]$SkipRename,
[switch]$Wait # Parameter to indicate if the function should wait for renaming to complete
)
if ($SkipRename) {
Write-Output "Skipping file renaming due to SkipRename flag."
return
}
if ($BA2 -and $BA22) {
Write-Error "Cannot convert both ways simultaneously. Choose either -BA2 or -BA22."
return
}
switch ($true) {
$BA2.IsPresent {
$sourceFileType = ".ba22"
$targetFileType = ".ba2"
}
$BA22.IsPresent {
$sourceFileType = ".ba2"
$targetFileType = ".ba22"
}
default {
Write-Error "No conversion direction specified. Use either -BA2 or -BA22."
return
}
}
# Define the regex pattern for specific files and patterns
$specificFilesPattern = "^DLC.* - Textures.*$"
$ccPattern = "^cc.* - Textures.*$"
$fallout4Pattern = "^Fallout4 - Textures*.*$"
$voicesPattern = "^(Fallout4|DLC.*|cc.*) - Voices.*$" # Added pattern for Voices
# Get all relevant files
$sourceFiles = Get-ChildItem -Path $script:data -Filter "*$sourceFileType" -Recurse -File | Where-Object {
$_.Name -match $specificFilesPattern -or $_.Name -match $ccPattern -or $_.Name -match $fallout4Pattern -or $_.Name -match $voicesPattern
}
if (!($sourceFiles)) {
Write-Output "No $sourceFileType files found. Skipping renaming."
return
}
# Collect file information for the table
$fileTable = @()
try {
Write-Output "Converting files to $targetFileType..."
$sourceFiles | ForEach-Object {
$newName = $_.BaseName + $targetFileType
Rename-Item -Path $_.FullName -NewName $newName
# Add file information to the table
if ($Debug -or $iknowwhatimdoing) {
$fileTable += [PSCustomObject]@{
OriginalName = $_.Name
NewName = $newName
}
}
}
Write-Output "Renamed BA2 files"
# Display the table
$fileTable | Format-Table -AutoSize
if ($Wait) {
Write-Output "Waiting for renaming operations to complete..."
# Wait for all renaming operations to complete
while ($true) {
$remainingFiles = Get-ChildItem -Path $script:data -Filter "*$sourceFileType" -Recurse -File | Where-Object {
$_.Name -match $specificFilesPattern -or $_.Name -match $ccPattern -or $_.Name -match $fallout4Pattern -or $_.Name -match $voicesPattern
}
if (-not $remainingFiles) {
break
}
Start-Sleep 1
}
Write-Output "All renaming operations completed."
}
}
catch {
Write-Error "An error occurred while converting files: $_"
Write-Output "Please ensure that you have the necessary permissions to rename files and that the files are not in use by another process."
Write-Output "Aborting script execution."
exit 1
}
}
if (!('WindowHelper' -as [Type])) {
Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
using System.Text;
public struct INPUT
{
public uint Type;
public KEYBDINPUT Data;
}
[StructLayout(LayoutKind.Sequential)]
public struct KEYBDINPUT
{
public ushort wVk;
public ushort wScan;
public uint dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
public class WindowHelper {
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);
}
"@
}
function QueryESP {
if ((Test-Path $script:bsarch) -and ($scriptPath -eq (Join-Path $script:fo4 (Split-Path $PSCommandPath -Leaf)))) {
Write-Host "All Systems Green" -ForegroundColor Green
}
else {
Write-Error "Something went wrong during script setup. Either this script is not in the fallout 4 directory or bsarch is labeled in the .json file as used and the bsarch executable could not be found. Please fix these errors before attempting another run of this script." -ForegroundColor Red
return
}
$useOwnEsp = Read-Host "Are you using your own .esp file? (IF NOT PRESS `N` TO PATCH ALL LOADED PLUGINS) (y/n)"
switch ($useOwnEsp.ToLower()) {
"y" {
$prompt = New-Object System.Windows.Forms.OpenFileDialog -Property @{
InitialDirectory = $script:data
Filter = "Elder Scrolls Plugin (*.esp)|*.esp"
}
if ($prompt.ShowDialog() -eq 'OK') {
$script:ESP = [System.IO.Path]::GetFileName($prompt.FileName)
if (![string]::IsNullOrEmpty($script:ESP)) {
Write-Output "Using ESP: $script:ESP"
}
}
else {
Write-Error "No ESP file selected. Exiting script."
exit
}
}
"n" {
$pluginprompt = Read-Host "
Please select one of the following:
1. patch all loaded plugins?
2. patch one specific plugin?
3. don't patch anything (quit)?"
switch ($pluginprompt) {
"1" {
Write-Output "Patching all loaded plugins"
$seedName = Read-Host "Enter a name for your output ESP (without .esp extension)"
$script:mod = ""
$script:ESP = "ToastPRP-$seedName.esp" # This will be used later in the script
$script:pas = "FO4Check_PreVisbines.pas"
Invoke-xEdit -caller 'QueryESP' -mod "" -seed:`"$seedName`" # Pass the seedName to Invoke-xEdit
}
"2" {
Write-Output "What ESP file would you like to patch?"
$prompt = New-Object System.Windows.Forms.OpenFileDialog -Property @{
InitialDirectory = $script:data
Filter = "Elder Scrolls Plugin (*.esp; *.esl; *.esm)|*.esp; *.esl; *.esm"
}
if ($prompt.ShowDialog() -eq 'OK') {
$script:mod = [System.IO.Path]::GetFileName($prompt.FileName)
$script:ESP = "ToastPRP-" + [System.IO.Path]::GetFileNameWithoutExtension($script:mod) + ".esp"
$script:pas = "FO4Check_PreVisbines.pas"
Write-Output "Patching ESP: $script:mod"
Write-CustomDebug "Calling Invoke-xEdit with caller='QueryESP' and mod='$script:mod'"
Invoke-xEdit -caller 'QueryESP' -mod $script:mod
}
else {
Write-Error "No ESP file selected. Exiting script."
exit
}
}
"3" {
Write-Output "Goodbye!"
exit
}
default {
Write-Error "Invalid option selected. Exiting script."
exit
}
}
}
default {
Write-Error "Invalid input. Exiting script."
exit
}
}
# Set common variables after ESP is determined
$script:EXT = [System.IO.Path]::GetFileNameWithoutExtension($script:ESP)
$script:PSG = "$script:data\$($script:EXT) - Geometry.psg"
$script:CSG = "$script:data\$($script:EXT) - Geometry.csg"
$script:workingdir = Join-Path $script:data "workingdir"
$script:ba2 = Join-Path $script:data "$script:EXT - Main.ba2"
if ($debug -or $iknowwhatimdoing) {
Write-CustomDebug -Message @{
"Bsarch" = $script:bsarch
"PWD" = $PSCommandPath
"Fallout 4 Path" = $script:fo4
"FO4 Data Path" = $script:data
"ESP" = $script:ESP
"EXT" = $script:EXT
"PSG" = $script:PSG
"CSG" = $script:CSG
"Working Directory" = $script:workingdir
"BA2 Path" = $script:ba2
}
}
# Create a unique folder for this attempt
$logFolder = Join-Path $script:data "ToastPRP\Logs\"
if (!(Test-Path $logFolder)) {
New-Item -ItemType Directory -Path $logFolder -Force | Out-Null
}
$script:mainLogPath = "$script:data\ToastPRP\Logs\$script:EXT-{0:MM-dd-yyyy-HH-mm}.log" -f (Get-Date)
Start-Transcript -Path $script:mainLogPath
$script:logPath = "$logFolder"
if (Test-Path *pack*.log) {
Remove-Item *pack*.log -Force -ErrorAction SilentlyContinue
Write-Output "Removing undeleted orphan logs in path"
}
try {
Log2Transcript $script:PJMLog
} catch {
Write-Error "Error in Log2Transcript: $_"
}
Write-Output "ESP setup completed successfully."
}
function Invoke-xEdit {
param (
[string]$caller,
[string]$mod = $null
)
# Get ESP path
$espPath = Join-Path $script:data $script:ESP
# Initialize checksum
$initialChecksum = $null
switch (Test-Path $espPath) {
$true {
$initialChecksum = Get-FileHash -Path $espPath -Algorithm SHA256
if ($debug -or $iknowwhatimdoing) {
Write-CustomDebug -Message @{
"Caller:" = $caller
"Mod:" = $mod
"xEdit:" = $xEdit
"Script:" = $script
"Initial Checksum" = $initialChecksum.Hash
}
}
}
$false {
if ($debug -or $iknowwhatimdoing) {
Write-CustomDebug -Message "New ESP file will be created: $script:ESP"
}
}
}
# Determine script arguments based on caller
switch ($caller) {
'QueryESP' {
switch ($mod) {
'' {
$scriptArgument = "-script:`"$script:pas`" -Full -nobuildrefs -mod -seed:`"ToastPRP-$seedName.esp`" -log:$script:PJMLog"
$KeysToSend = "Enter"
}
default {
$modWithoutExtension = [System.IO.Path]::GetFileNameWithoutExtension($mod)
$modWithEspExtension = "ToastPRP-$modWithoutExtension.esp"
$scriptArgument = "-script:`"$script:pas`" -Full -nobuildrefs -Mod:`"$mod`" -seed:`"$modWithEspExtension`" -log:$script:PJMLog"
$KeysToSend = "Enter"
}
}
}
default {
$scriptArgument = "-script:`"$script:pas`" -nobuildrefs -Mod:`"$script:ESP`" -log:$script:PJMLog"
$KeysToSend = "PageDown", "Space", "Enter"
}
}
if ($debug -or $iknowwhatimdoing) { Write-CustomDebug -Message "Argument is $scriptArgument" }
# Start xEdit process
$xEditProcess = Start-Process -FilePath $xEdit -ArgumentList $scriptArgument -PassThru -NoNewWindow
Start-Sleep -Seconds 3
# Initialize state variables
$script:firstFO4ScriptDetected = $false
$script:seenApplyingScript = $false
$script:alreadyReportedApplyingScript = $false
$script:exitLoop = $false
$currentTitle = ""
$lastTitle = ""
$startTime = Get-Date
$timeout = 900 # 15 minute timeout
# Send initial keystrokes
if ($KeysToSend) {
Keypress -KeysToSend $KeysToSend
}
# Window title monitoring loop
while (-not $script:exitLoop) {
$titleBuilder = New-Object System.Text.StringBuilder 256
[WindowHelper]::GetWindowText($xEditProcess.MainWindowHandle, $titleBuilder, $titleBuilder.Capacity) | Out-Null
$currentTitle = $titleBuilder.ToString()
# Check for timeout
switch ((Get-Date) - $startTime) {
{ $_.TotalSeconds -gt $timeout } {
Write-Error "Operation timed out after $timeout seconds"
$xEditProcess.CloseMainWindow()
return $false
}
}
# Title change detection
switch ($currentTitle -ne $lastTitle) {
$true {
if ($debug -or $iknowwhatimdoing) {
Write-CustomDebug -Message "Title changed from '$lastTitle' to '$currentTitle'"
}
# Process title states
switch -Regex ($currentTitle) {
"FO4Script" {
$script:firstFO4ScriptDetected = $true
switch ($script:seenApplyingScript) {
$true {
Write-Output "xEdit script completed, closing..."
Start-Sleep -Seconds 2
$xEditProcess.CloseMainWindow()
$xEditProcess.WaitForExit(5000)
$script:exitLoop = $true
}
$false {
if ($debug -or $iknowwhatimdoing) {
Write-CustomDebug -Message "Initial FO4Script state detected"
}
}
}
}
"Applying script" {
switch ($script:alreadyReportedApplyingScript) {
$false {
Write-Output "Waiting for script completion"
$script:seenApplyingScript = $true
$script:alreadyReportedApplyingScript = $true
Start-Sleep -Milliseconds 500
}
}
}
default {
if ($debug -or $iknowwhatimdoing) {
Write-CustomDebug -Message "Unhandled window title: $currentTitle"
}
}
}
$lastTitle = $currentTitle
}
}
Start-Sleep -Milliseconds 50
}
# Verify script execution
switch ($script:firstFO4ScriptDetected) {
$false {
Write-Error "xEdit script did not run successfully"
return $false
}
}
# Checksum verification
switch ($initialChecksum) {
{ $null -ne $_ } {
Start-Sleep -Seconds 2
$finalChecksum = Get-FileHash -Path $espPath -Algorithm SHA256
if ($debug -or $iknowwhatimdoing) {
Write-CustomDebug -Message @{
"Initial Checksum" = $initialChecksum.Hash
"Final Checksum" = $finalChecksum.Hash
}
}
switch ($initialChecksum.Hash -eq $finalChecksum.Hash) {
$true {
Write-Error "ESP file was not modified by xEdit script! Checksums match, indicating no changes were made."
Write-Error "Initial: $($initialChecksum.Hash)"
Write-Error "Final: $($finalChecksum.Hash)"
$backupPath = Join-Path "$script:data\ToastPRP\ESP_Backups" $script:ESP
switch (Test-Path $backupPath) {
$true {
Write-Output "Attempting to restore from backup..."
try {
Copy-Item -Path $backupPath -Destination $espPath -Force
Write-Output "Backup restored successfully"
}
catch {
Write-Error "Failed to restore backup: $_"
}
}
}
throw "xEdit script failed to modify ESP file. Script execution aborted."
}
$false {
Write-Output "ESP file was successfully modified (checksums differ)"
Log2Transcript $script:PJMLog
if ($caller -eq 'Precombines') {
Remove-Item $script:CombinedESP
}
if ($caller -eq 'Previs') {
Remove-Item $script:previsESP
}
return $true
}
}
}
default {
switch (Test-Path $espPath) {
$true {
Write-Output "New ESP file was successfully created"
Log2Transcript $script:PJMLog
return $true
}
$false {
Write-Error "Failed to create new ESP file"
throw "xEdit script failed to create new ESP file. Script execution aborted."
}
}
}
}
}
function Invoke-CK ([string]$Argument) {
if ($debug -or $iknowwhatimdoing) {
# Table of arguments for debugging
# Create an array of custom objects
$tableData = @(
[PSCustomObject]@{ Function = "Precombines"; Argument = "-GeneratePrecombined:`"$ESP`"" }
[PSCustomObject]@{ Function = "PSGCompression"; Argument = "-CompressPSG:`"$ESP`"" }
[PSCustomObject]@{ Function = "GenerateCDX"; Argument = "-buildcdx:`"$ESP`"" }
[PSCustomObject]@{ Function = "Previs"; Argument = "-GeneratePreVisdata:`"$ESP`"" }
)
# Display the table using Format-Table
$tableData | Format-Table -AutoSize
}
# Switch statement to handle different arguments
switch ($Argument) {
"Precombines" {
Rename-Texture -ba2
Write-Output "Generating Precombines..."
$ckArgument = "-GeneratePrecombined:`"$script:ESP`" clean all"
$script:pas = "Batch_FO4MergeCombinedObjectsandCheck.pas"
}
"PSGCompression" {
Rename-Texture -ba22
Write-Output "Compressing PSG..."
$ckArgument = "-CompressPSG:`"$script:ESP`""
Wait-Process "ckpe_loader" -ErrorAction SilentlyContinue
}
"GenerateCDX" {
Write-Output "Generating Cell Index (CDX)..."
$ckArgument = "-buildcdx:`"$script:ESP`""
}
"Previs" {
Rename-Texture -BA22
Write-Output "Generating Previs Data..."
$ckArgument = "-GeneratePreVisdata:`"$script:ESP`" clean all"
$script:pas = "Batch_FO4MergePreVisandCleanRefr.pas"
}
default {
Write-Error "Unknown argument: $Argument"
return
}
}
if ($debug -or $iknowwhatimdoing) { Write-CustomDebug -Message "Starting Creation Kit with arguments: $ckArgument" }
$startTime = Get-Date
Start-Process -FilePath $script:CK -ArgumentList $ckArgument -Wait
#Log2Transcript "CKLOG.log"
Write-Output "Completed in $(New-TimeSpan -Start $startTime -End (Get-Date))."
}
#PEBKAC
function Keypress {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, Position = 0)]
[ValidateSet("PageDown", "Space", "Enter")]
[String[]]$KeysToSend
)
# Send each key in the array
foreach ($Key in $KeysToSend) {
switch ($Key) {
"PageDown" { [System.Windows.Forms.SendKeys]::SendWait("{PGDN}") }
"Space" { [System.Windows.Forms.SendKeys]::SendWait(" ") }
"Enter" { [System.Windows.Forms.SendKeys]::SendWait("{ENTER}") }
}
# Wait for 100 milliseconds after each keypress
Start-Sleep -Milliseconds 100
}
}
#PEBKAC
function Wait-ForFile {
param(
[Parameter(Mandatory = $true)]
[string]$FileName,
[int]$TimeoutSeconds = 10,
[string]$Caller
)
$filePath = $FileName
if (!(Test-Path -Path $script:data)) {
Write-Error "Base directory $script:data does not exist."
return
}
Write-output "Waiting for $filePath to appear..."
$startTime = Get-Date
$fileFound = $false
$pollInterval = 100 # Start with a short initial poll interval (milliseconds)
do {
$fileExists = Test-Path $filePath
if ($fileExists) {
$fileFound = $true
break
}
$elapsedTime = (Get-Date) - $startTime
if ($elapsedTime.TotalSeconds -ge $TimeoutSeconds) {
Write-Warning "Timeout reached while waiting for $FileName to appear, aborting."
exit
}
Start-Sleep -Milliseconds $pollInterval
$pollInterval *= 2 # Gradually increase the poll interval to reduce system load
} while ($true)
if ($fileFound) {
Write-output "File found: $filePath"
# Caller-specific actions
switch ($Caller) {
'PSGCompression' {
Remove-Item $script:PSG
}
'Precombines' {
Write-output "Calling Invoke-xEdit with caller='Precombines' and mod='$SelectedFile'"
Invoke-xEdit -caller 'Precombines' # Moved before removing CombinedObjects.esp
}
'CreateZIP' {
Remove-Item $filesToCompress
}
'Previs' {
Write-output "Calling Invoke-xEdit with caller='Previs' and mod='$SelectedFile'"
Invoke-xEdit -caller 'Previs' # Moved before removing CombinedObjects.esp
}
# Add more cases as needed
default {
if ($debug -or $iknowwhatimdoing) { Write-Output "No action taken for caller: $Caller" }
}
}
}
else {
Write-Error "File $FileName not found within the timeout period."
}
}
#PEBKAC
function Backup-ESP {
$backupPath = "$script:data\ToastPRP\ESP_Backups"
# Ensure the backup directory exists
New-Item -ItemType Directory -Path $backupPath -Force | Out-Null
$backupFilePath = Join-Path -Path $backupPath -ChildPath $ESP
$oldFilePath = Join-Path -Path $script:data -ChildPath $ESP
try {
Copy-Item -LiteralPath "$oldFilePath" -Destination "$backupFilePath" -Force -ErrorAction Stop
Write-Output "Backup of $ESP created in $backupPath"
}
catch {
Write-Error "Backup of $ESP failed: $_"
}
}
function ManageJson {
param (
[switch]$CalledByPrecombines
)
try {
$jsonFilePath = Join-Path $script:fo4 $script:jsonFileName
$jsonContent = if (Test-Path $jsonFilePath) {
Get-Content $jsonFilePath -Raw | ConvertFrom-Json
}
else {
@{
'ESP-WIP' = @()
'xEdit' = $null
'Bsarch' = $false
'BsarchPath' = $null
}
}
if (-not $jsonContent.xEdit) {
$fileDialog = New-Object System.Windows.Forms.OpenFileDialog
$fileDialog.Title = "Select FO4Edit file"
$fileDialog.Filter = "FO4Edit (*.exe)|FO4Edit.exe;FO4Edit64.exe;fo4edit.exe;xEdit.exe;xEdit64.exe"
if ($fileDialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {
$selectedFile = $fileDialog.FileName
if ($selectedFile -match '(?i)(fo4edit|fo4edit64|xedit|xedit64)\.exe$') {
$jsonContent.xEdit = $selectedFile
$script:xEdit = $selectedFile
}
}
}
if ($CalledByPrecombines -and $script:ESP -and ($script:ESP -notin $jsonContent.'ESP-WIP')) {
$jsonContent.'ESP-WIP' += $script:ESP
}
if (Test-Path $script:bsarch) {
$jsonContent.Bsarch = $true
$jsonContent.BsarchPath = $script:bsarch
}
else {
$jsonContent.Bsarch = $false
$jsonContent.BsarchPath = $null
}
$jsonString = $jsonContent | ConvertTo-Json -Depth 100
Set-Content $jsonFilePath -Value $jsonString
$script:xEdit = $jsonContent.xEdit
$script:BSArchive = $jsonContent.BsarchPath
return $jsonContent
}
catch {
Write-Output "Error managing JSON file: $_"
}
}
#PEBKAC
function DLBSArch {
param (
[string]$BsarchUrl = "https://github.com/TES5Edit/TES5Edit/raw/dev/Tools/BSArchive/bsarch.exe",
[string]$PredefinedChecksum = "97FB589E0542806F105C28FF005C8DD51EEB118E0A18497247590A3BBA73D865D3956B769E6128ED63A3D5333017949EA26AC6DC87570E05FE50CBB3E7C51CC3"
)
# Helper function to download bsarch.exe and validate checksum
function DownloadAndValidateBsarch {
Invoke-WebRequest -Uri $BsarchUrl -OutFile $script:bsarch
$hash = (Get-FileHash $script:bsarch -Algorithm SHA512).Hash
if ($hash -eq $PredefinedChecksum) {
Write-output "bsarch.exe downloaded and validated successfully."
return $true
}
else {
Write-output "Downloaded bsarch.exe failed checksum validation. Either download failed or the executable was updated on the github repo."
Remove-Item -Path $script:bsarch -ErrorAction SilentlyContinue
return $false
}
}
# Check if bsarch.exe exists and validate checksum, download if necessary
if (!(Test-Path $script:bsarch) -or -not (DownloadAndValidateBsarch)) {
Write-output "Attempting to download and validate bsarch.exe..."
if (!(DownloadAndValidateBsarch)) {
Write-output "Failed to obtain a valid bsarch.exe after download attempt. Please check the source or try again later."
return
}
}
Write-Host "BSArch validated" -ForegroundColor Green
# Update the JSON content with the bsarch path if it has changed
$jsonContent = ManageJson
if ($jsonContent.Bsarch -ne $true -or $jsonContent.BsarchPath -ne $script:bsarch) {
$jsonContent.Bsarch = $true
$jsonContent.BsarchPath = $script:bsarch
$jsonContent | ConvertTo-Json -Depth 10 | Set-Content $script:jsonFilePath
Write-output "ToastPRP.json has been updated with the bsarch path."
}
}
function Invoke-Archiver {
param (
[bool]$CheckBa2Path = $false,
[string]$CallingFunction
)
$script:ba2 = Join-Path $script:data "$script:EXT - Main.ba2"
try {
# Check if BA2 path is valid
if ($CheckBa2Path -and (!(Test-Path $script:ba2))) {
Write-Error "The BA2 path is invalid or does not exist: $script:ba2"
return
}
# Ensure working directory exists
if (!(Test-Path $script:workingdir)) {
New-Item -ItemType Directory -Path $script:workingdir -Force | Out-Null
}
$script:visSubdir = Join-Path $script:workingdir "vis"
$script:MeshesSubdir = Join-Path $script:workingdir "Meshes"
# Handle different calling functions
switch ($CallingFunction) {
"PackMesh" {
if (Test-Path $script:Meshesdir) {
Move-Item -Path $script:Meshesdir -Destination $script:workingdir -Force -ErrorAction SilentlyContinue
}
else {
Write-Warning "The source directory '$script:Meshesdir' does not exist."
}
}
"PackMeshVis" {
if (Test-Path $script:Meshesdir) {
Move-Item -Path $script:Meshesdir -Destination $script:workingdir -Force -ErrorAction SilentlyContinue
}
else {
Write-Warning "The source directory '$script:Meshesdir' does not exist."
}
if (Test-Path $script:PrevisDIR) {
Move-Item -Path $script:PrevisDIR -Destination $script:workingdir -Force -ErrorAction SilentlyContinue
}
else {
Write-Warning "The source directory '$script:PrevisDIR' does not exist."
}
}
}
# Define the log file paths for this attempt
$unpackLogPath = Join-Path $script:logPath "Unpack.log"
$packLogPath = Join-Path $script:logPath "Pack1.log"
if (Test-Path $packLogPath) {
$packLogPath = Join-Path $script:logPath "Pack2.log"
}
# Unpacking operation
if ($CheckBa2Path) {
Write-CustomDebug -Message "Unpacking archive: $script:ba2 to $script:workingdir"
$unpackOutput = & $script:bsarch "unpack" "$script:ba2" "$script:workingdir" "-mt" 2>&1
$unpackOutput | Tee-Object -FilePath $unpackLogPath
Write-Output "Unpacking log saved to $unpackLogPath"
#Add-Content -Path $mainLogPath -Value (Get-Content $unpackLogPath)
Remove-Item $unpackLogPath
}
if ((Get-ChildItem -Path $meshesSubdir) -or (Get-ChildItem -Path $meshesSubdir -Recurse)) {
# Packing operation
Write-CustomDebug -Message "Packing directory: $script:workingdir into archive: $script:ba2"
$packOutput = & $script:bsarch "pack" "$script:workingdir" "$script:ba2" "-fo4" "-z" "-mt" "-share" 2>&1
$packOutput | Tee-Object -FilePath $packLogPath
Write-Output "Packing log saved to $packLogPath"
#Add-Content -Path $mainLogPath -Value (Get-Content $packLogPath)
Remove-Item $packLogPath
}
else {
Write-Error "The source directory '$script:workingdir' is empty. No packing operation performed."
}
# Clean up working directory if needed
if ($CheckBa2Path) {
Remove-Item -Path $script:workingdir -Recurse -Force -ErrorAction SilentlyContinue
}
}
catch {
Write-Error "An error occurred during unpacking: $_"
Write-Output "Error Details: $_"
throw # Re-throw the error to be caught by the calling function if needed
}
}
#PEBKAC
function MoveScriptToCorrectDirectory {
if ([string]::IsNullOrWhiteSpace($script:fo4)) {
Write-output "The 'installed path' is empty or null."
return
}
$script:scriptPath = Join-Path $script:fo4 (Split-Path $PSCommandPath -Leaf)
if ($PSCommandPath -eq $scriptPath) {
Write-Host "Script directory vindicated" -ForegroundColor Green
return
}
$filesToMove = @(
@{
Source = $PSCommandPath
Destination = $scriptPath
Name = "Script"
},
@{
Source = $script:jsonFilePath
Destination = $jsonFileDestinationPath
Name = $script:jsonFileName
}
)
foreach ($file in $filesToMove) {
try {
if (!(Test-Path -Path $file.Source)) {
Write-output "Source file $file.Source does not exist."
continue
}
if (!(Test-Path -Path $file.Destination)) {
Write-output "Destination directory $file.Destination does not exist."
continue
}
Copy-Item -Path $file.Source -Destination $file.Destination -ErrorAction Stop
Write-output "$($file.Name) has been copied to the correct directory: $($file.Destination)"
Remove-Item -Path $file.Source -Force -ErrorAction Stop
Write-output "Old $($file.Name) has been deleted."
}
catch {
Write-output "Failed to copy or delete $($file.Name): $_"
return
}
}
}
#Beginning of execution