Repository navigation
Expand file tree
/
Copy path3DXModKit.psm1
More file actions
425 lines (378 loc) · 16.2 KB
/
Copy path3DXModKit.psm1
File metadata and controls
425 lines (378 loc) · 16.2 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
# 3DXModKit - module entry point
#
# A modular, client-side-only mod framework for 3DXChat (Unity 2021.3.45f2, IL2CPP).
#
# Mod contract
# ------------
# A mod's entry script is *invoked* (not dot-sourced) and must return a hashtable:
#
# @{
# Initialize = { param($ctx) ... } # required - subscribe to events here
# Shutdown = { param($ctx) ... } # optional
# }
#
# Invoking rather than dot-sourcing keeps each mod in its own scope, so two mods
# defining a helper of the same name cannot clobber each other.
Set-StrictMode -Version Latest
$Script:ModKitRoot = $PSScriptRoot
$Script:ModKitRepo = 'Deaeath/3DXModKit'
function Get-ModKitVersion {
<#
.SYNOPSIS
The installed version, read from the module manifest - the single
source of truth so the CLI, GUI, and updater never disagree.
#>
[CmdletBinding()]
param()
(Test-ModuleManifest -Path (Join-Path $Script:ModKitRoot '3DXModKit.psd1')).Version.ToString()
}
# --- load native layer once -------------------------------------------------
if (-not ('ThreeDX.ModKit.Native.MemOps' -as [type])) {
$nativeSrc = Join-Path $PSScriptRoot 'src\Native\MemoryApi.cs'
if (-not (Test-Path -LiteralPath $nativeSrc)) {
throw "Native source missing: $nativeSrc"
}
Add-Type -TypeDefinition (Get-Content -LiteralPath $nativeSrc -Raw) -Language CSharp
}
# --- dot-source framework ---------------------------------------------------
. (Join-Path $PSScriptRoot 'src\Core\Manifest.ps1')
. (Join-Path $PSScriptRoot 'src\Core\Resolver.ps1')
. (Join-Path $PSScriptRoot 'src\Core\Config.ps1')
. (Join-Path $PSScriptRoot 'src\Host\Runtime.ps1')
# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------
function Get-ModKitInfo {
<#
.SYNOPSIS
Framework, game, and environment summary.
#>
[CmdletBinding()]
param()
$sys = [ThreeDX.ModKit.Native.MemOps]::GetSystemMemory()
$game = @(Get-Process -Name '3DXChat' -ErrorAction SilentlyContinue)
[pscustomobject]@{
ModKitVersion = Get-ModKitVersion
ModKitRoot = $Script:ModKitRoot
Elevated = [ThreeDX.ModKit.Native.MemOps]::IsElevated()
TotalRamGB = $sys.TotalPhysGB
AvailRamGB = $sys.AvailPhysGB
AvailPercent = $sys.AvailPercent
MemoryLoad = $sys.MemoryLoadPercent
GameRunning = ($game.Count -gt 0)
GamePid = $(if ($game.Count -gt 0) { $game[0].Id } else { 0 })
}
}
function Test-ModKitMods {
<#
.SYNOPSIS
Validates every installed mod and reports capability violations.
#>
[CmdletBinding()]
param(
[string]$ModsPath = (Join-Path $Script:ModKitRoot 'mods')
)
$all = Get-ModKitMods -ModsPath $ModsPath
foreach ($v in $all) {
[pscustomobject]@{
Id = $v.Manifest.Id
Name = $v.Manifest.Name
Version = $v.Manifest.Version
Tier = $v.Manifest.Tier
Valid = $v.IsValid
Errors = ($v.Errors -join '; ')
Warnings = ($v.Warnings -join '; ')
}
}
}
function Invoke-ModKitEmpty {
<#
.SYNOPSIS
Fires RAMMap's Empty operations on demand.
.DESCRIPTION
-Target Game trims only the 3DXChat working set (no elevation needed)
-Target All every system-wide Empty operation (needs admin)
-Target WorkingSets|SystemWorkingSet|ModifiedList|Standby|LowPriorityStandby
one specific operation
.EXAMPLE
Invoke-ModKitEmpty -Target Game
#>
[CmdletBinding()]
param(
[ValidateSet('Game','All','WorkingSets','SystemWorkingSet','ModifiedList','Standby','LowPriorityStandby')]
[string]$Target = 'Game'
)
$M = [ThreeDX.ModKit.Native.MemOps]
$before = $M::GetSystemMemory()
$results = switch ($Target) {
'Game' { @($M::TrimProcessesByName('3DXChat')) }
'All' { $M::EmptyAll() }
'WorkingSets' { @($M::EmptyAllWorkingSets()) }
'SystemWorkingSet' { @($M::EmptySystemWorkingSet()) }
'ModifiedList' { @($M::FlushModifiedPageList()) }
'Standby' { @($M::PurgeStandbyList()) }
'LowPriorityStandby' { @($M::PurgeLowPriorityStandby()) }
}
Start-Sleep -Milliseconds 250
$after = $M::GetSystemMemory()
foreach ($r in $results) {
[pscustomobject]@{
Operation = $r.Operation
Success = $r.Success
FreedMB = $r.FreedMB
Ms = $r.DurationMs
Error = $r.Error
}
}
Write-Host ''
Write-Host ("Available RAM: {0} GB -> {1} GB (net {2} MB)" -f `
$before.AvailPhysGB, $after.AvailPhysGB,
[math]::Round(($after.AvailPhysBytes - $before.AvailPhysBytes)/1MB,1)) -ForegroundColor Cyan
}
function Start-ModKit {
<#
.SYNOPSIS
Loads a profile's mods and runs the host loop.
.EXAMPLE
Start-ModKit -Profile default
#>
[CmdletBinding()]
param(
[string]$ProfileName = 'default',
[string]$ModsPath = (Join-Path $Script:ModKitRoot 'mods'),
[string]$ProfilesPath= (Join-Path $Script:ModKitRoot 'profiles'),
[int]$TickSeconds = 5,
[ValidateSet('Debug','Info','Warn','Error')][string]$LogLevel = 'Info',
# Overridable so the pipeline can be exercised against a stand-in
# process, and so a renamed or repackaged client still works.
[string]$GameProcessName = '3DXChat'
)
$logDir = Join-Path $Script:ModKitRoot 'logs'
if (-not (Test-Path -LiteralPath $logDir)) {
New-Item -ItemType Directory -Force -Path $logDir | Out-Null
}
$logPath = Join-Path $logDir ("modkit-{0}.log" -f (Get-Date -Format 'yyyyMMdd'))
$logger = New-ModKitLogger -LogPath $logPath -Level $LogLevel
$bus = New-ModKitEventBus
$hostObj= New-ModKitHost -RootPath $Script:ModKitRoot -Logger $logger -Bus $bus -GameProcessName $GameProcessName
$logger.Info('modkit', "3DXModKit $(Get-ModKitVersion) starting (profile '$ProfileName')")
if (-not [ThreeDX.ModKit.Native.MemOps]::IsElevated()) {
$logger.Warn('modkit', 'not elevated - system-wide purges unavailable, per-process trimming still works')
}
# --- profile ----------------------------------------------------------
$profileObj = Get-ModKitProfile -ProfilesPath $ProfilesPath -Name $ProfileName
$logger.Info('modkit', "profile: $($profileObj.Description)")
# --- discover + validate ---------------------------------------------
$discovered = Get-ModKitMods -ModsPath $ModsPath
$enabled = @()
foreach ($v in $discovered) {
if ($profileObj.Enabled -notcontains $v.Manifest.Id) {
$logger.Debug('modkit', "skipping '$($v.Manifest.Id)' (not in profile)")
continue
}
foreach ($w in $v.Warnings) { $logger.Warn($v.Manifest.Id, $w) }
if (-not $v.IsValid) {
foreach ($e in $v.Errors) { $logger.Error($v.Manifest.Id, $e) }
$logger.Error('modkit', "refusing to load '$($v.Manifest.Id)'")
continue
}
$enabled += $v.Manifest
}
if ($enabled.Count -eq 0) {
$logger.Error('modkit', 'no valid mods to load - exiting')
return
}
# --- order ------------------------------------------------------------
$resolved = Resolve-ModKitLoadOrder -Manifests $enabled
foreach ($w in $resolved.Warnings) { $logger.Warn('modkit', $w) }
if ($resolved.Errors.Count -gt 0) {
foreach ($e in $resolved.Errors) { $logger.Error('modkit', $e) }
return
}
$logger.Info('modkit', "load order: $(($resolved.Order | ForEach-Object { $_.Id }) -join ' -> ')")
# --- initialise -------------------------------------------------------
foreach ($manifest in $resolved.Order) {
$profileCfg = $null
if ($profileObj.ModConfigs.ContainsKey($manifest.Id)) {
$profileCfg = $profileObj.ModConfigs[$manifest.Id]
}
$cfg = Get-ModKitModConfig -Manifest $manifest -ConfigRoot $hostObj.ConfigRoot -ProfileConfig $profileCfg
$ctx = New-ModKitContext -Manifest $manifest -Config $cfg -Bus $bus -Logger $logger -HostObject $hostObj
try {
$entryPath = Join-Path $manifest.Root $manifest.Entry
$mod = & $entryPath
if ($null -eq $mod -or -not $mod.ContainsKey('Initialize')) {
throw "entry script did not return a hashtable with an Initialize block"
}
& $mod.Initialize $ctx
$hostObj.LoadedMods[$manifest.Id] = [pscustomobject]@{
Manifest = $manifest; Context = $ctx; Mod = $mod
}
$logger.Info('modkit', "loaded $($manifest.Id) v$($manifest.Version) [$($manifest.Capabilities -join ', ')]")
} catch {
$logger.Error($manifest.Id, "failed to load: $($_.Exception.Message)")
$bus.Unsubscribe($manifest.Id)
}
}
if ($hostObj.LoadedMods.Count -eq 0) {
$logger.Error('modkit', 'every mod failed to load - exiting')
return
}
# --- run --------------------------------------------------------------
try {
Start-ModKitLoop -HostObject $hostObj -TickSeconds $TickSeconds
} finally {
foreach ($entry in $hostObj.LoadedMods.Values) {
if ($entry.Mod.ContainsKey('Shutdown')) {
try { & $entry.Mod.Shutdown $entry.Context }
catch { $logger.Error($entry.Manifest.Id, "shutdown threw: $($_.Exception.Message)") }
}
}
$logger.Info('modkit', 'stopped')
}
}
function Test-ModKitUpdate {
<#
.SYNOPSIS
Checks GitHub Releases for a newer version. Never throws - a network
hiccup here must never take down the caller, since this runs
unattended in the background.
.OUTPUTS
PSCustomObject: UpdateAvailable, LocalVersion, RemoteVersion,
DownloadUrl, ReleaseUrl, Error.
#>
[CmdletBinding()]
param([int]$TimeoutSec = 10)
$local = Get-ModKitVersion
$result = [pscustomobject]@{
UpdateAvailable = $false
LocalVersion = $local
RemoteVersion = $null
DownloadUrl = $null
ReleaseUrl = $null
Error = $null
}
try {
$uri = "https://api.github.com/repos/$Script:ModKitRepo/releases/latest"
$resp = Invoke-RestMethod -Uri $uri -Headers @{
'User-Agent' = '3DXModKit-updater'
'Accept' = 'application/vnd.github+json'
} -TimeoutSec $TimeoutSec -UseBasicParsing
$tag = [string]$resp.tag_name
$remote = $tag.TrimStart('v', 'V')
$asset = $resp.assets | Where-Object { $_.name -like '3DXModKit-*.zip' } | Select-Object -First 1
if (-not $asset) {
$result.Error = "release '$tag' has no 3DXModKit-*.zip asset"
return $result
}
$result.RemoteVersion = $remote
$result.DownloadUrl = $asset.browser_download_url
$result.ReleaseUrl = $resp.html_url
try {
$result.UpdateAvailable = ([version]$remote) -gt ([version]$local)
} catch {
# Non-semver tag - fall back to a straight string inequality so a
# weird tag still surfaces as "different" rather than being
# silently treated as no-op.
$result.UpdateAvailable = ($remote -ne $local)
}
} catch {
$result.Error = $_.Exception.Message
}
return $result
}
# ---------------------------------------------------------------------------
# Companion apps
# ---------------------------------------------------------------------------
# Separate apps the modkit can install and open: they run on their own, never
# inside the game. The control panel's Mods tab and the matching mods use this.
$Script:ProfileStudioDir = Join-Path $env:LOCALAPPDATA 'Programs\3DX Profile Studio'
$Script:WorldEditorDir = Join-Path $env:LOCALAPPDATA 'Programs\3DX World Editor'
function Get-ModKitCompanions {
<#
.SYNOPSIS
3DX Radio Streamer, 3DX Profile Studio and 3DX World Editor: whether each is installed,
where, which version, and the script that installs it.
#>
[CmdletBinding()]
param()
$radioExe = $null
$uninstallRoots = @('HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall',
'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall',
'HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall')
foreach ($root in $uninstallRoots) {
try {
$dir = (Get-ItemProperty -Path (Join-Path $root '{6F1C2B7A-3D58-4E8B-9A57-2C41E7A0B3D9}_is1') -Name 'InstallLocation' -ErrorAction Stop).InstallLocation
$exe = Join-Path $dir '3DX Radio Streamer.exe'
if (Test-Path -LiteralPath $exe -PathType Leaf) { $radioExe = $exe; break }
} catch { }
}
if (-not $radioExe) {
foreach ($dir in @((Join-Path $env:LOCALAPPDATA 'Programs\3DX Radio Streamer'), (Join-Path $env:ProgramFiles '3DX Radio Streamer'))) {
$exe = Join-Path $dir '3DX Radio Streamer.exe'
if (Test-Path -LiteralPath $exe -PathType Leaf) { $radioExe = $exe; break }
}
}
$radioVersion = $null
if ($radioExe) { $radioVersion = (Get-Item -LiteralPath $radioExe).VersionInfo.ProductVersion }
$page = Join-Path $Script:ProfileStudioDir '3DX Profile Studio.html'
$pageVersion = $null
$versionFile = Join-Path $Script:ProfileStudioDir 'version.txt'
if (Test-Path -LiteralPath $versionFile) { $pageVersion = (Get-Content -LiteralPath $versionFile -TotalCount 1).Trim() }
$worldExe = Join-Path $Script:WorldEditorDir '3DXWorldEditor.exe'
$worldVersion = $null
$worldVersionFile = Join-Path $Script:WorldEditorDir 'version.txt'
if (Test-Path -LiteralPath $worldVersionFile) { $worldVersion = (Get-Content -LiteralPath $worldVersionFile -TotalCount 1).Trim() }
@(
[pscustomobject]@{
Id = 'radio-streamer'
Name = '3DX Radio Streamer'
Kind = 'app'
Path = $radioExe
Installed = [bool]$radioExe
Version = $radioVersion
Running = @(Get-Process -Name '3DX Radio Streamer' -ErrorAction SilentlyContinue).Count -gt 0
Installer = Join-Path $Script:ModKitRoot 'mods\radio-streamer\bootstrap\Install-RadioStreamer.ps1'
WebUrl = $null
Repo = 'https://github.com/Deaeath/3dx-radio-streamer'
}
[pscustomobject]@{
Id = 'profile-studio'
Name = '3DX Profile Studio'
Kind = 'page'
Path = $(if (Test-Path -LiteralPath $page -PathType Leaf) { $page } else { $null })
Installed = (Test-Path -LiteralPath $page -PathType Leaf)
Version = $pageVersion
Running = $false
Installer = Join-Path $Script:ModKitRoot 'mods\profile-studio\bootstrap\Install-ProfileStudio.ps1'
WebUrl = 'https://deaeath.github.io/3dx-profile-studio/'
Repo = 'https://github.com/Deaeath/3dx-profile-studio'
}
[pscustomobject]@{
Id = 'world-editor'
Name = '3DX World Editor'
Kind = 'app'
Path = $(if (Test-Path -LiteralPath $worldExe -PathType Leaf) { $worldExe } else { $null })
Installed = (Test-Path -LiteralPath $worldExe -PathType Leaf)
Version = $worldVersion
Running = @(Get-Process -Name '3DXWorldEditor' -ErrorAction SilentlyContinue).Count -gt 0
Installer = Join-Path $Script:ModKitRoot 'mods\world-editor\bootstrap\Install-WorldEditor.ps1'
WebUrl = 'https://deaeath.github.io/3dx-world-editor/'
Repo = 'https://github.com/Deaeath/3dx-world-editor'
}
)
}
Export-ModuleMember -Function @(
'Get-ModKitCompanions'
'Get-ModKitInfo'
'Get-ModKitVersion'
'Test-ModKitUpdate'
'Test-ModKitMods'
'Invoke-ModKitEmpty'
'Start-ModKit'
'Get-ModKitCapabilityCatalog'
'Get-ModKitMods'
'Resolve-ModKitLoadOrder'
'ConvertTo-ModKitManifest'
'Test-ModKitManifest'
)