Skip to content

armgit / soju

Public Imported from GitHub
0

Play Windows games on Apple Silicon Macs. Free, open-source app that installs the official Battle.net, Steam, Epic and GOG launchers and lists your games in one library.

D2R in VR or first person on the Mac, from a VR badge on its card (#196)

Mikek7ff4cfe71bb3
diff --git a/README.md b/README.md
index 11856b1a7d1..59669b8dba0 100644
--- a/README.md
+++ b/README.md
@@ -56,7 +56,7 @@ Tested by us on an M4 Pro with macOS 26.5, unless a row says it is a player's re
| The Witcher 3 (Remastered) | Steam | 🟡 reaches its menu (player's report) | needs Apple GPTK 4.0 beta 3, which Soju accepts since 1.14.10 ([#112](https://github.com/BCD1210/soju/issues/112)) |
| Diablo II: Resurrected (Steam edition) | Steam | 🟡 runs (user report) | in DirectX 12 mode; a player reported it running on Discord (2026-11-17). Not checked by us: we don't own the Steam edition |
| Diablo IV (Steam edition) | Steam | ✅ in-game (player's report) | M5 Pro 48 GB, macOS 27.2.1: about 60 FPS at 1800×1169, ray tracing works, some slowdown in busy scenes; about 5 hours played. Play switches Steam to DirectX 12 mode by itself from 1.14.44 ([#186](https://github.com/BCD1210/soju/issues/186)) |
-| Diablo II: Resurrected in VR (offline) | Battle.net | 🧪 simulator only | `soju vr setup`, then `soju vr play`; [docs/VR.md](docs/VR.md) |
+| Diablo II: Resurrected in VR or first person on the Mac (offline) | Battle.net | 🧪 simulator only (VR); ✅ Mac screen | the **VR** badge on its card; [docs/VR.md](docs/VR.md) |
**Will not run:** anything with kernel anti-cheat (EAC, BattlEye, Vanguard).
diff --git a/app/Library.swift b/app/Library.swift
index 717a92f7a0c..3bdec2017bd 100644
--- a/app/Library.swift
+++ b/app/Library.swift
@@ -190,11 +190,11 @@ extension SojuModel {
}
}
/// D2R VR Unleashed in the VR copy of the Battle.net bottle (`soju vr play`, offline).
- /// `flat` opens the same copy without VR so offline characters can be made with the mouse.
- func playVR(_ game: InstalledGame, flat: Bool = false) {
+ /// `flat` plays the same copy on the Mac screen (mouse look, W A S D) in `view`: first, third or classic.
+ func playVR(_ game: InstalledGame, flat: Bool = false, view: String = "first") {
guard !busy, !launchingGames.contains(game.id) else { return }
do {
- let (p, url) = try task(["vr", flat ? "flat" : "play"], logName: "d2r-vr")
+ let (p, url) = try task(flat ? ["vr", "flat", view] : ["vr", "play"], logName: "d2r-vr")
launchingGames.insert(game.id); gameLaunches[game.id] = p
p.terminationHandler = { [weak self] process in
DispatchQueue.main.async {
@@ -213,7 +213,7 @@ extension SojuModel {
}
}
try p.run()
- activity = flat ? "Opening the VR copy of " + game.title + " without VR (create offline characters)…"
+ activity = flat ? "Starting " + game.title + " on the Mac screen (" + (view == "classic" ? "game camera" : view + " person") + ", offline characters)…"
: "Starting " + game.title + " in VR (offline characters)…"
DispatchQueue.main.asyncAfter(deadline: .now() + 8) { [weak self, weak p] in
guard let self, let p, self.gameLaunches[game.id] === p else { return }
@@ -257,6 +257,7 @@ struct LibraryView: View {
@State private var order = "name"
@State private var availability = "all"
@State private var selected: InstalledGame?
+ @State private var vrGame: InstalledGame?
@State private var showDiagnostics = false
@Environment(\.colorScheme) private var scheme
private var green: Color { scheme == .dark ? Color(red: 0.42, green: 0.83, blue: 0.67) : Color(red: 0.12, green: 0.34, blue: 0.28) }
@@ -290,6 +291,7 @@ struct LibraryView: View {
.frame(minWidth: 1010, minHeight: 710)
.background(Color(nsColor: .windowBackgroundColor))
.sheet(item: $selected) { game in detail(game) }
+ .sheet(item: $vrGame) { game in D2RVRSheet(model: model, game: game, close: { vrGame = nil }) }
.sheet(isPresented: $showDiagnostics) { diagnostics }
.alert(model.issueTitle, isPresented: Binding(get: { model.libraryIssue != nil }, set: { if !$0 { model.libraryIssue = nil; model.issueTitle = "Game needs attention" } })) {
// A launcher that is not installed yet: take the player to where it is installed.
@@ -454,6 +456,13 @@ struct LibraryView: View {
HStack(spacing: 5) {
Circle().fill(game.platform.accent).frame(width: 5, height: 5)
Text(game.platform.title.uppercased()).font(.system(size: 10, weight: .bold)).tracking(0.7).foregroundStyle(.secondary)
+ if game.id == "battlenet:osi" && game.isInstalled {
+ Button { vrGame = game } label: {
+ Text("VR").font(.system(size: 9, weight: .heavy)).padding(.horizontal, 5).padding(.vertical, 1.5)
+ .background(Color.purple.opacity(0.18), in: Capsule()).foregroundStyle(.purple)
+ }.buttonStyle(.plain).help("Play in VR or in first person on this Mac")
+ .accessibilityLabel("VR and first person for " + game.title)
+ }
Spacer()
Button { model.favorite(game) } label: {
Image(systemName: model.preferences.favorites.contains(game.id) ? "star.fill" : "star")
@@ -509,11 +518,7 @@ struct LibraryView: View {
Button("Report How It Ran…") { model.report(game) }
if game.id == "battlenet:osi" && game.isInstalled {
Divider()
- Button("Set Up VR (offline)") { model.run(["vr", "setup"], title: "Setting up D2R VR…") }
- .disabled(model.busy)
- Button("Play in VR") { model.playVR(game) }.disabled(model.busy)
- Button("Create Offline Character (without VR)") { model.playVR(game, flat: true) }
- .disabled(model.busy)
+ Button("VR and First Person…") { vrGame = game }
}
}
}
@@ -586,6 +591,11 @@ struct LibraryView: View {
}
if game.isInstalled { Button("Report How It Ran…") { model.report(game) } }
Spacer()
+ if game.id == "battlenet:osi" && game.isInstalled {
+ Button { selected = nil; DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { vrGame = game } } label: {
+ Label("VR and First Person", systemImage: "eyeglasses")
+ }
+ }
}
Divider()
HStack {
diff --git a/app/VRSheet.swift b/app/VRSheet.swift
new file mode 100644
index 00000000000..d22720ad093
--- /dev/null
+++ b/app/VRSheet.swift
@@ -0,0 +1,150 @@
+import SwiftUI
+
+/// `soju vr status --json` (scripts/d2r-vr.py status).
+struct VRStatus: Decodable {
+ var installed: Bool
+ var current: Bool
+ var game_build: String?
+ var supported_build: String
+ var source_build: String?
+ var source_supported: Bool?
+ var ready: Bool { installed && current }
+}
+
+extension SojuModel {
+ /// Reads the D2R VR state in the background; nil when it cannot be read.
+ func vrStatus(_ done: @escaping (VRStatus?) -> Void) {
+ do {
+ let (p, url) = try task(["vr", "status"], logName: "d2r-vr-status")
+ p.terminationHandler = { _ in
+ let text = (try? String(contentsOf: url, encoding: .utf8)) ?? ""
+ let line = text.split(separator: "\n").last(where: { $0.hasPrefix("{") }).map(String.init) ?? ""
+ let status = try? JSONDecoder().decode(VRStatus.self, from: Data(line.utf8))
+ DispatchQueue.main.async { done(status) }
+ }
+ try p.run()
+ } catch {
+ done(nil)
+ }
+ }
+}
+
+/// D2R in VR and in first person on the Mac screen, step by step (D2R VR Unleashed, offline characters).
+struct D2RVRSheet: View {
+ @ObservedObject var model: SojuModel
+ let game: InstalledGame
+ let close: () -> Void
+ @AppStorage("vrHeadsetAppReady") private var headsetReady = false
+ @AppStorage("vrHeadset") private var headset = "quest"
+ @AppStorage("vrFlatView") private var flatView = "first"
+ @State private var status: VRStatus?
+ @State private var loading = true
+ private let green = Color(red: 0.16, green: 0.62, blue: 0.38)
+ static let questGuide = URL(string: "https://github.com/anoshmisiosdev/oxrsys/blob/main/docs/platforms/quest.md")!
+ static let oxrsys = URL(string: "https://github.com/anoshmisiosdev/oxrsys")!
+
+ private var setUp: Bool { status?.ready == true }
+ private var blocked: String? {
+ guard let status, status.source_supported == false, let build = status.source_build else { return nil }
+ return "D2R updated to " + build + ". VR support is being updated for it."
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 18) {
+ HStack(alignment: .firstTextBaseline) {
+ Text("D2R in VR").font(.system(size: 22, weight: .bold, design: .rounded))
+ Spacer()
+ Button { close() } label: { Image(systemName: "xmark.circle.fill").font(.system(size: 18)) }
+ .buttonStyle(.plain).foregroundStyle(.secondary).keyboardShortcut(.cancelAction)
+ }
+ Text("Experimental · offline characters only · not yet tried on a real headset. Your normal D2R and its online play are not changed.")
+ .font(.system(size: 12)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
+
+ step(1, "Headset app", done: headsetReady) {
+ Picker("", selection: $headset) {
+ Text("Meta Quest").tag("quest")
+ Text("PICO").tag("pico")
+ }.pickerStyle(.segmented).labelsHidden().frame(width: 220)
+ Text("Install the free OXRSys app on the headset (sideloaded), on the same Wi-Fi as this Mac.")
+ .font(.system(size: 12)).foregroundStyle(.secondary)
+ HStack {
+ Button("How to install ›") { NSWorkspace.shared.open(headset == "quest" ? Self.questGuide : Self.oxrsys) }
+ Spacer()
+ Button(headsetReady ? "Installed ✓" : "I installed it") { headsetReady.toggle() }
+ }
+ }
+
+ step(2, "Set up VR on this Mac", done: setUp) {
+ if let blocked {
+ Label(blocked, systemImage: "exclamationmark.triangle").font(.system(size: 12)).foregroundStyle(.orange)
+ } else {
+ Text(setUp ? "Ready. Set it up again after a D2R update." : "About 2 minutes and 125 MB. Copies your Battle.net D2R; the original is left as it is.")
+ .font(.system(size: 12)).foregroundStyle(.secondary)
+ }
+ HStack {
+ if model.busy && model.activity.contains("D2R VR") { ProgressView().controlSize(.small) }
+ Spacer()
+ Button(setUp ? "Set Up Again" : "Set Up") {
+ model.run(["vr", "setup"], title: "Setting up D2R VR…")
+ }.disabled(model.busy || blocked != nil)
+ }
+ }
+
+ step(3, "Connect and play", done: false) {
+ Text("Open OXRSys on the headset and press Connect, then press Play in VR. Make an offline character with the stick and A.")
+ .font(.system(size: 12)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
+ HStack {
+ Spacer()
+ Button { close(); model.playVR(game) } label: { Label("Play in VR", systemImage: "eyeglasses") }
+ .buttonStyle(.borderedProminent).tint(green)
+ .disabled(!setUp || !headsetReady || model.busy || model.launchingGames.contains(game.id))
+ }
+ }
+
+ Divider()
+ VStack(alignment: .leading, spacing: 8) {
+ Text("No headset? Play on this Mac").font(.system(size: 14, weight: .semibold))
+ Text("The same copy on the Mac screen: mouse to look, W A S D to walk. fn+F1 / fn+F2 / fn+F3 switch the view in the game.")
+ .font(.system(size: 12)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
+ HStack {
+ Picker("", selection: $flatView) {
+ Text("First person").tag("first")
+ Text("Third person").tag("third")
+ Text("Classic").tag("classic")
+ }.pickerStyle(.segmented).labelsHidden().frame(width: 300)
+ Spacer()
+ Button { close(); model.playVR(game, flat: true, view: flatView) } label: { Label("Play on Mac", systemImage: "display") }
+ .disabled(!setUp || model.busy || model.launchingGames.contains(game.id))
+ }
+ if !setUp && !loading {
+ Text("Set up VR first (step 2); it is the same copy.").font(.system(size: 11)).foregroundStyle(.secondary)
+ }
+ }
+ }
+ .padding(26).frame(width: 560)
+ .onAppear(perform: reload)
+ .onChange(of: model.busy) { _, busy in if !busy { reload() } }
+ }
+
+ private func reload() {
+ loading = true
+ model.vrStatus { s in status = s; loading = false }
+ }
+
+ private func step<Content: View>(_ number: Int, _ title: String, done: Bool,
+ @ViewBuilder content: () -> Content) -> some View {
+ HStack(alignment: .top, spacing: 12) {
+ ZStack {
+ Circle().fill(done ? green : Color.primary.opacity(0.08)).frame(width: 26, height: 26)
+ if done { Image(systemName: "checkmark").font(.system(size: 12, weight: .bold)).foregroundStyle(.white) }
+ else { Text(String(number)).font(.system(size: 13, weight: .semibold)) }
+ }
+ VStack(alignment: .leading, spacing: 8) {
+ Text(title).font(.system(size: 14, weight: .semibold))
+ content()
+ }
+ }
+ .padding(12).frame(maxWidth: .infinity, alignment: .leading)
+ .background(Color.primary.opacity(0.035), in: RoundedRectangle(cornerRadius: 11))
+ }
+}
diff --git a/docs/VR.md b/docs/VR.md
index a9544d7b2fa..2d8a3d4128b 100644
--- a/docs/VR.md
+++ b/docs/VR.md
@@ -6,14 +6,41 @@ first-person VR mod for **offline characters**, and stream it to a headset from
```bash
soju vr setup # once (about 2 minutes, ~125 MB of downloads)
soju vr play # after connecting the headset or simulator
-soju vr play --flat # optional desktop mode
+soju vr play --flat # no headset: first person on the Mac screen
+soju vr play --flat --view third # or third person, or --view classic (the game's own camera)
soju vr status
soju vr setup --refresh # after a D2R update or when the 30-day check appears
soju vr remove --yes
```
-In the app: right-click Diablo II: Resurrected in the library, then **Set Up VR (offline)** and **Play in VR**.
-**Create Offline Character (without VR)** opens the same copy on the Mac screen.
+In the app: the **VR** badge on the Battle.net Diablo II: Resurrected card (or **VR and First Person** in its details
+or right-click menu) opens a three-step sheet: the headset app, Set Up, Connect and Play in VR. Its lower part,
+**No headset? Play on this Mac**, starts the same copy on the Mac screen in first person, third person or the classic
+camera, with mouse look and W A S D.
+
+## On the Mac screen (no headset)
+
+The mod's flat mode (`[mode] platform = 0` in `d2r_pcvr.ini`, view in `flat_view`: 1 classic, 2 third person,
+3 first person) is set before each start, because Mac keyboards send F1 - F3 as brightness keys unless fn is held
+(fn+F1 / fn+F2 / fn+F3 still switch in the game). Checked 2026-11-25 on D2R 3.4.95032: first and third person in the
+Rogue Encampment, offline character select with the mouse.
+
+On the Mac screen the game keeps your own resolution and window mode (in VR it is fixed at windowed 1920x1080).
+
+NVIDIA DLSS works in the copy through Apple's MetalFX bridge, like normal D2R, when the engine has Apple's NGX shim.
+Two things were in the way and are fixed by Soju (2026-11-25, D2R 3.4.95032, GPTK 3.0, M4 Pro):
+
+- The mod runs the game under ReShade, which hands it wrappers of the D3D12 device and command lists. Apple's shim
+ treats the command list as its own object, so it crashed in `NVSDK_NGX_D3D12_CreateFeature` and the game hung at the
+ title. Soju's `nvngx.dll` (`tools/ngx-unwrap`, built into the `vr-mod-v2` release) sits in front of the shim in the
+ copy's system32 and passes it the original objects; the shim itself is loaded as `nvngx_metalfx.dll`.
+- The mod reads the depth buffer from the part DLSS draws into (2/3 of the screen at Quality), found from the depth
+ buffer binds. Under D3DMetal the game binds it with D3D12 render passes, which the mod did not watch, so fog and sky
+ were drawn over a 2/3 box. The mod patch (`patches/d2r-pcvr`) now watches render passes too.
+
+Measured in the Rogue Encampment, first person, fog and sky on: at 3440x1440 full screen 51 - 66 fps without DLSS and
+63 - 74 fps with DLSS Quality (MetalFX 2293x960 -> 3440x1440). In a 1920x1080 window the GPU is not the limit and DLSS
+gives no gain (about 130 fps either way). The headset path with DLSS is not checked yet.
## What it does
diff --git a/patches/d2r-pcvr/README.md b/patches/d2r-pcvr/README.md
index f9a33e69ae5..b79c9af0e47 100644
--- a/patches/d2r-pcvr/README.md
+++ b/patches/d2r-pcvr/README.md
@@ -23,6 +23,10 @@ modifier state; they never activate the desktop window. Physical typing stays on
the original input path. Front-end, native-panel, composition and atlas tests cover
the portable state and layout rules; name entry is also verified live.
+With NVIDIA DLSS (MetalFX on macOS) the render-scale tracking also watches D3D12
+render passes: under D3DMetal the game binds its depth buffer that way, and the fog
+and sky read the wrong part of it otherwise (2026-11-25).
+
## Rebuild
Use local copies of the upstream source and SDK checkouts. The script archives
@@ -47,7 +51,7 @@ built DLL that will be published. No game assets are included.
No artifact has been uploaded by this change. After simulator qualification (real Quest remains unverified):
-1. Publish the staged DLL at the `vr-mod-v1` URL in resources/d2r-vr.json. Confirm
+1. Publish the staged DLL at the `vr-mod-v2` URL in resources/d2r-vr.json (with soju-nvngx.dll from tools/ngx-unwrap/build.sh). Confirm
its size and SHA-256 match `mod_patch`; never replace a published artifact.
2. Publish `d2r-pcvr-soju-source.tar.xz`, LICENSE, and the patch alongside it.
Keep the source available for recipients under MPL-2.0, and publish this repo's
diff --git a/patches/d2r-pcvr/vr-character-create.patch b/patches/d2r-pcvr/vr-character-create.patch
index d86003c15b9..37a4742fb6f 100644
--- a/patches/d2r-pcvr/vr-character-create.patch
+++ b/patches/d2r-pcvr/vr-character-create.patch
@@ -635,7 +635,7 @@ index 1251de1..8fd4589 100644
bool NoticeText(int kind,char* out,uint32_t size) {
if(kind<0||kind>=framevr::notice::Kinds||!out||!size)return false;
diff --git a/vr/vrcam.cpp b/vr/vrcam.cpp
-index 6dcd253..a151351 100644
+index 6dcd253..3becc42 100644
--- a/vr/vrcam.cpp
+++ b/vr/vrcam.cpp
@@ -21,6 +21,8 @@
@@ -708,3 +708,28 @@ index 6dcd253..a151351 100644
#ifdef D2RVR_NATIVE_OPENXR
LRESULT resolutionResult=0;
if(framevr::resolution::Handle(h,msg,w,l,g_gameWndProc,resolutionResult))return resolutionResult;
+@@ -9691,6 +9727,16 @@ void OnBind(command_list* cl, uint32_t count, const resource_view* rtvs, resourc
+ }
+ Note();
+ }
++// The game can bind its targets with D3D12 render passes instead (it does under
++// D3DMetal on macOS): the same depth buffer, so the same bookkeeping (2026-11-25).
++bool OnBeginPass(command_list* cl, uint32_t count, const render_pass_render_target_desc* rts,
++ const render_pass_depth_stencil_desc* ds, render_pass_flags) {
++ resource_view rtvs[8] = {};
++ const uint32_t n = rts ? std::min<uint32_t>(count, 8) : 0;
++ for (uint32_t i = 0; i < n; ++i) rtvs[i] = rts[i].view;
++ OnBind(cl, n, rtvs, ds ? ds->view : resource_view{0});
++ return false;
++}
+ void OnViewports(command_list* cl, uint32_t first, uint32_t count, const viewport* vps) {
+ if (first != 0 || count == 0) return;
+ if (cl != t_cl) { t_cl = cl; t_dsW = t_dsH = 0; }
+@@ -10489,6 +10535,7 @@ void TryRegister() {
+ #endif
+ #ifdef D2RVR_NATIVE_OPENXR
+ reshade::register_event<reshade::addon_event::bind_render_targets_and_depth_stencil>(&d2rvr::D3D12Only<&renderscale::OnBind>::Call);
++ reshade::register_event<reshade::addon_event::begin_render_pass>(&d2rvr::D3D12Only<&renderscale::OnBeginPass>::Call);
+ #else
+ reshade::register_event<reshade::addon_event::bind_render_targets_and_depth_stencil>(&renderscale::OnBind);
+ #endif
diff --git a/resources/d2r-vr.json b/resources/d2r-vr.json
index 25cd84b3ae4..ebec7c3c2e5 100644
--- a/resources/d2r-vr.json
+++ b/resources/d2r-vr.json
@@ -48,13 +48,20 @@
}
},
"mod_patch": {
- "url": "https://github.com/BCD1210/soju/releases/download/vr-mod-v1/d2rl-pcvr-soju.dll",
- "size": 15577088,
- "sha256": "5d88447228efcc7d51288909c252fe0719318bacd6be92a8ef5ae18c9d41812a",
+ "url": "https://github.com/BCD1210/soju/releases/download/vr-mod-v2/d2rl-pcvr-soju.dll",
+ "size": 15577600,
+ "sha256": "0ab10137f6c6037826b1becd30d6268affffede6cafc1f0bad9e9320a0a8775d",
"patch": "patches/d2r-pcvr/vr-character-create.patch",
- "patch_sha256": "7317ee23b03238b8bff580352d1648da040fccca7cf68d9e9fc3c227994acbbb",
+ "patch_sha256": "31046a4f941c90e51efc1912f3ff1a79119ed379482509463e8cadaadfe3109e",
"base_commit": "70ad0e665952f1bd829176ba461a85ebb974c3f0",
"source_url": "https://github.com/bearstonem/d2r-pcvr/tree/70ad0e665952f1bd829176ba461a85ebb974c3f0",
"license": "MPL-2.0; source patch and license in patches/d2r-pcvr; rebuild with scripts/build-vr-mod.py"
+ },
+ "ngx_unwrap": {
+ "url": "https://github.com/BCD1210/soju/releases/download/vr-mod-v2/soju-nvngx.dll",
+ "size": 16896,
+ "sha256": "279d8b4320c921021fb986b3ec421a772e4364db1bac6cb0fc8fb4f4814c1596",
+ "source": "tools/ngx-unwrap (build.sh)",
+ "note": "nvngx.dll in front of Apple NGX shim: passes it the real D3D12 objects instead of ReShade wrappers"
}
}
diff --git a/scripts/build-app.sh b/scripts/build-app.sh
index 3640c58c270..387d7bb314e 100755
--- a/scripts/build-app.sh
+++ b/scripts/build-app.sh
@@ -10,7 +10,7 @@ trap 'rm -rf "$STAGE"' EXIT
APP="$STAGE/Soju.app"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources/soju"
swiftc -swift-version 5 -parse-as-library -O -target arm64-apple-macosx14.0 \
- "$ROOT/app/Soju.swift" "$ROOT/app/Library.swift" "$ROOT/app/GameSettings.swift" "$ROOT/app/Accounts.swift" "$ROOT/app/Discover.swift" "$ROOT/app/PurchaseLinks.swift" "$ROOT/app/SteamLogin.swift" "$ROOT/app/Store.swift" "$ROOT/app/GoatCatalog.swift" "$ROOT/app/GoatShelf.swift" "$ROOT/app/Feed.swift" "$ROOT/app/Sponsor.swift" "$ROOT/app/Notify.swift" "$ROOT/app/TV.swift" "$ROOT/app/UpdateCheck.swift" "$ROOT/app/Update.swift" "$ROOT/app/StarAsk.swift" "$ROOT/app/DownloadMeter.swift" "$ROOT/app/GardenStats.swift" "$ROOT/app/SojuGarden.swift" -o "$APP/Contents/MacOS/Soju"
+ "$ROOT/app/Soju.swift" "$ROOT/app/Library.swift" "$ROOT/app/GameSettings.swift" "$ROOT/app/Accounts.swift" "$ROOT/app/Discover.swift" "$ROOT/app/PurchaseLinks.swift" "$ROOT/app/SteamLogin.swift" "$ROOT/app/Store.swift" "$ROOT/app/GoatCatalog.swift" "$ROOT/app/GoatShelf.swift" "$ROOT/app/Feed.swift" "$ROOT/app/Sponsor.swift" "$ROOT/app/Notify.swift" "$ROOT/app/TV.swift" "$ROOT/app/UpdateCheck.swift" "$ROOT/app/Update.swift" "$ROOT/app/StarAsk.swift" "$ROOT/app/DownloadMeter.swift" "$ROOT/app/GardenStats.swift" "$ROOT/app/SojuGarden.swift" "$ROOT/app/VRSheet.swift" -o "$APP/Contents/MacOS/Soju"
for dir in scripts tools patches third_party resources; do
ditto "$ROOT/$dir" "$APP/Contents/Resources/soju/$dir"
done
diff --git a/scripts/d2r-vr.py b/scripts/d2r-vr.py
index 03338a31233..15171468332 100644
--- a/scripts/d2r-vr.py
+++ b/scripts/d2r-vr.py
@@ -18,8 +18,12 @@ Python inside the copy, with the dependencies passed in already checked.
Three things the mod needs on Soju's engine, all inside the copy:
- the game folder's d3d12.dll is renamed, so D3D12 loads from system32, where
ReShade watches for it (Wine already uses its builtin d3d12 either way);
-- the windowed resolution is fixed at 1920x1080, the size the game first creates
- its swapchain at, so it never resizes it;
+- in VR the windowed resolution is fixed at 1920x1080, the size the game first
+ creates its swapchain at, so it never resizes it (on the Mac screen it is the
+ player's own setting);
+- NVIDIA DLSS goes through Apple's MetalFX bridge like normal D2R, with a small
+ nvngx.dll in front (tools/ngx-unwrap) that hands the bridge the real D3D12
+ objects instead of ReShade's wrappers;
- one jump in ReShade64.dll skips work on a resource D3DMetal already destroyed
(resources/d2r-vr.json, reshade.patch).
"""
@@ -71,6 +75,18 @@ def recipe(m):
return hashlib.sha256(json.dumps(m, sort_keys=True).encode()).hexdigest()
+def read_raw(path):
+ """Text with its line endings as they are (Path.read_text has no newline= before Python 3.13,
+ and the app runs this with macOS's /usr/bin/python3, 3.9)."""
+ with open(path, encoding='utf-8', newline='') as f:
+ return f.read()
+
+
+def write_raw(path, text):
+ with open(path, 'w', encoding='utf-8', newline='') as f:
+ f.write(text)
+
+
def fetch(entry, name, label):
"""Download entry['url'] into the cache unless a checked copy is there."""
cache = VR / 'downloads'
@@ -239,16 +255,65 @@ def isolate_user_folders(bottle):
return changed
-def fix_settings(saves):
+def fix_settings(saves, flat=False, dlss=False):
+ """In VR: windowed 1920x1080 (above). On the Mac screen the player's own resolution stays.
+ NVIDIA DLSS stays as chosen when the MetalFX bridge is ready, else it is turned off."""
settings = saves / 'Settings.json'
data = json.loads(settings.read_text(encoding='utf-8-sig'))
- if data.get('Screen Resolution (Windowed)') == '1920x1080' and str(data.get('Window Mode')) == '0':
+ want = {} if flat else {'Screen Resolution (Windowed)': '1920x1080', 'Window Mode': 0}
+ if not dlss:
+ want['NVIDIA DLSS'] = 0
+ if all(str(data.get(k)) == str(v) for k, v in want.items()):
return
- data['Screen Resolution (Windowed)'] = '1920x1080'
- data['Window Mode'] = 0
+ data.update(want)
settings.write_text(json.dumps(data, indent=4), encoding='utf-8')
+def apple_shim(path):
+ try:
+ return path.is_file() and b'D3DMetalDLLsBase' in path.read_bytes()
+ except OSError:
+ return False
+
+
+def dlss_bridge(m):
+ """NVIDIA DLSS in the copy through Apple's NGX shim (as scripts/gptk-dlss.sh does for normal
+ games), with Soju's nvngx.dll in front of it. The modded game runs under ReShade, whose
+ D3D12 wrappers crash the shim when they reach it directly (hang at the title, 2026-11-25).
+ True when ready; False on an engine without Apple's shim, where DLSS stays off."""
+ win, unix = ENGINE / 'lib/wine/x86_64-windows', ENGINE / 'lib/wine/x86_64-unix'
+ shim = next((p for p in (win / 'nvngx-on-metalfx.dll', win / 'nvngx.dll') if apple_shim(p)), None)
+ unwrap = VR / 'dlss/nvngx.dll'
+ spec = m.get('ngx_unwrap') or {}
+ if (shim is None or not (ENGINE / 'lib/external/libd3dshared.dylib').is_file() or not unwrap.is_file()
+ or digest(unwrap) != spec.get('sha256')):
+ return False
+ system32 = BOTTLE / 'drive_c/windows/system32'
+ try:
+ # The shim under its own name, loaded by the unwrapper. Wine finds its unixlib by that
+ # name, so the engine gets the same copy and link next to its nvngx.dll.
+ for target in (win / 'nvngx_metalfx.dll', system32 / 'nvngx_metalfx.dll'):
+ if not target.is_file() or digest(target) != digest(shim):
+ shutil.copy2(shim, target)
+ link = unix / 'nvngx_metalfx.so'
+ if (os.readlink(link) if link.is_symlink() else None) != '../../external/libd3dshared.dylib':
+ link.unlink(missing_ok=True)
+ link.symlink_to('../../external/libd3dshared.dylib')
+ if not (system32 / 'nvngx.dll').is_file() or digest(system32 / 'nvngx.dll') != spec['sha256']:
+ shutil.copy2(unwrap, system32 / 'nvngx.dll')
+ except OSError:
+ return False
+ reg = BOTTLE / 'system.reg'
+ try:
+ has_key = '[Software\\\\NVIDIA Corporation\\\\Global\\\\NGXCore]' in reg.read_text(errors='replace')
+ except OSError:
+ return False
+ if not has_key:
+ wine(BOTTLE, ['reg', 'add', 'HKLM\\SOFTWARE\\NVIDIA Corporation\\Global\\NGXCore', '/v', 'FullPath',
+ '/t', 'REG_SZ', '/d', 'C:\\Windows\\System32', '/f'], capture_output=True)
+ return True
+
+
def write_runtime_routing(m):
runtime = VR / 'runtime'
openxr = BOTTLE / 'drive_c/openxr'
@@ -278,11 +343,10 @@ def allow_installer_build(mod, build):
"""The mod's own installer (0.3.31) refuses every Battle.net build but 3.3.93847 before it
installs anything. For a build listed in extra_builds, add it to that list in the extracted copy."""
gate = mod / 'steamvr/game_install.py'
- text = gate.read_text(encoding='utf-8', newline='')
+ text = read_raw(gate)
old = "BATTLENET_VERSIONS = ('3.3.93847',)"
if build and build not in text and old in text:
- gate.write_text(text.replace(old, "BATTLENET_VERSIONS = ('" + build + "', '3.3.93847',)"),
- encoding='utf-8', newline='')
+ write_raw(gate, text.replace(old, "BATTLENET_VERSIONS = ('" + build + "', '3.3.93847',)"))
def quiet_loader_warning(game, build):
@@ -376,6 +440,7 @@ def setup(refresh=False):
python_zip = fetch(m['python'], 'python-embed-amd64.zip', 'Windows Python (python.org)')
mod_zip = fetch(m['mod'], 'd2r-pcvr-windows.zip', m['mod']['name'])
patched_plugin = fetch(m['mod_patch'], 'd2rl-pcvr-soju.dll', 'the VR character creation fix')
+ ngx_unwrap = fetch(m['ngx_unwrap'], 'soju-nvngx.dll', 'the DLSS fix for the VR copy')
loader_zip = fetch(m['loader'], m['loader']['file'], 'D2RLoader (d2rloader.net)')
reshade_exe = fetch(m['reshade'], 'ReShade_Setup_Addon.exe', 'ReShade (reshade.me)')
@@ -426,7 +491,9 @@ def setup(refresh=False):
(game / 'd3d12.dll').rename(off)
if game_build(BOTTLE) != m['game_build']:
quiet_loader_warning(game, game_build(BOTTLE))
- fix_settings(BOTTLE / SAVES_REL)
+ (VR / 'dlss').mkdir(exist_ok=True)
+ shutil.copy2(ngx_unwrap, VR / 'dlss/nvngx.dll')
+ fix_settings(BOTTLE / SAVES_REL, dlss=dlss_bridge(m))
isolate_user_folders(BOTTLE)
write_runtime_routing(m)
stop_bottle(BOTTLE)
@@ -453,6 +520,7 @@ def status():
'game_build': game_build(BOTTLE) if BOTTLE.is_dir() else None,
'supported_build': ', '.join(builds(m)),
'source_build': game_build(SOURCE),
+ 'source_supported': game_build(SOURCE) in builds(m),
'mod': m['mod']['name'],
'path': str(VR),
}
@@ -477,8 +545,42 @@ def stage_mod_patch(mod, plugin, spec):
'Apply the accompanying patch to this base.\n')
-def play_env(flat):
+VIEWS = {'classic': 1, 'third': 2, 'first': 3} # the mod's flat views, F1 - F3
+
+
+def set_mode(game, flat, view='first'):
+ """The mod plays to the headset ([mode] platform = 1) or to the Mac screen with mouse look and
+ W A S D (platform = 0), in the view flat_view names. Mac keyboards send F1 - F3 as brightness keys
+ unless fn is held, so the view is chosen before the game starts."""
+ ini = game / 'mods' / 'D2R-PCVR' / 'd2rloader/plugins/d2r_pcvr.ini'
+ try:
+ text = read_raw(ini)
+ except OSError:
+ return
+ want = {'platform': '0' if flat else '1'}
+ if flat:
+ want['flat_view'] = str(VIEWS.get(view, 3))
+ out, section = [], ''
+ for line in text.splitlines(keepends=True):
+ stripped = line.strip()
+ if stripped.startswith('['):
+ section = stripped
+ elif section == '[mode]' and '=' in stripped:
+ key = stripped.split('=', 1)[0].strip()
+ if key in want:
+ end = '\r\n' if line.endswith('\r\n') else '\n'
+ line = key + ' = ' + want[key] + end
+ out.append(line)
+ new = ''.join(out)
+ if new != text:
+ write_raw(ini, new)
+
+
+def play_env(flat, dlss=False):
env = wine_env(BOTTLE)
+ if dlss:
+ env['D3DM_ENABLE_METALFX'] = '1'
+ env['WINEDLLOVERRIDES'] = 'nvngx=n' # Soju's nvngx.dll in system32, not the engine's shim
if not flat:
env['WINEDLLPATH'] = str(VR / 'runtime/wine')
env['OXR_BRIDGE_ENV_FILE'] = str(VR / 'bridge.env')
@@ -488,16 +590,24 @@ def play_env(flat):
return env
-def play(extra, flat=False):
+def play(extra, flat=False, view='first'):
info = status()
if not info['installed'] or not info['current']:
raise VRError('D2R VR is not set up for this Soju version. Run: soju vr setup')
if running(['D2R.exe', 'D2RLoader.exe']):
raise VRError('Diablo II: Resurrected is already running.')
isolate_user_folders(BOTTLE) # copies set up by 1.8.0/1.8.1 still have the links
- env = play_env(flat)
+ dlss = dlss_bridge(manifest())
+ env = play_env(flat, dlss)
+ set_mode(BOTTLE / GAME_REL, flat, view)
+ try:
+ fix_settings(BOTTLE / SAVES_REL, flat, dlss)
+ except (OSError, ValueError):
+ pass
if flat:
- say('Opening the VR copy without VR. Create or check offline characters, then quit and run: soju vr play')
+ label = {'first': 'first person', 'third': 'third person', 'classic': "the game's own camera"}[view]
+ say('Opening the VR copy on the Mac screen in ' + label + ': mouse look, W A S D walk. '
+ 'In the game fn+F1 / fn+F2 / fn+F3 switch between the game camera, third and first person.')
if not flat:
say('Connect the OXRSys headset/Simulator before the title screen. Use stick + A for offline character creation.')
say('Use the VR name keyboard: stick + A types, X erases, Y changes case; select Create + A. B goes back.')
@@ -530,7 +640,9 @@ def main(argv):
p.add_argument('--refresh', action='store_true', help='copy the Battle.net bottle again (after a game update)')
p = sub.add_parser('play')
p.add_argument('--flat', action='store_true',
- help='open the VR copy on the Mac screen without VR (optional desktop mode)')
+ help='play the VR copy on the Mac screen: mouse look and W A S D, no headset')
+ p.add_argument('--view', choices=sorted(VIEWS), default='first',
+ help='with --flat: first or third person, or classic (the game\'s own camera)')
p = sub.add_parser('status')
p.add_argument('--json', action='store_true')
p = sub.add_parser('remove')
@@ -540,7 +652,7 @@ def main(argv):
if args.command == 'setup':
return setup(args.refresh)
if args.command == 'play':
- return play(extra, args.flat)
+ return play(extra, args.flat, args.view)
if args.command == 'status':
info = status()
if args.json:
diff --git a/scripts/desktop-action.sh b/scripts/desktop-action.sh
index b3bb40a859a..e3c93ace307 100755
--- a/scripts/desktop-action.sh
+++ b/scripts/desktop-action.sh
@@ -35,8 +35,10 @@ case "$ACTION" in
steam|epic|gog|ea|rockstar|ubisoft) exec bash "$ROOT/scripts/play.sh" "$1-kill" ;;
*) echo "Choose one of the launchers."; exit 64 ;; esac ;;
vr)
- case "${1:-}" in setup|play|status) exec python3 "$ROOT/scripts/d2r-vr.py" "$1" ;;
- flat) exec python3 "$ROOT/scripts/d2r-vr.py" play --flat ;;
+ case "${1:-}" in setup|play) exec python3 "$ROOT/scripts/d2r-vr.py" "$1" ;;
+ status) exec python3 "$ROOT/scripts/d2r-vr.py" status --json ;;
+ flat) case "${2:-first}" in first|third|classic) ;; *) echo "soju vr: unknown view" >&2; exit 64 ;; esac
+ exec python3 "$ROOT/scripts/d2r-vr.py" play --flat --view "${2:-first}" ;;
*) echo "Unknown VR action."; exit 64 ;; esac ;;
tv)
case "${1:-}" in setup|start|stop|status) exec python3 "$ROOT/scripts/stream_tv.py" "$1" ;;
diff --git a/tests/test_d2r_vr.py b/tests/test_d2r_vr.py
index 2e2ef425a4a..33100fd49c0 100644
--- a/tests/test_d2r_vr.py
+++ b/tests/test_d2r_vr.py
@@ -1,6 +1,7 @@
import hashlib
import importlib.util
import json
+import os
from pathlib import Path
import tempfile
import unittest
@@ -60,12 +61,76 @@ class ManifestTests(unittest.TestCase):
def test_app_actions_are_routed(self):
action = (ROOT / 'scripts/desktop-action.sh').read_text()
- self.assertIn('setup|play|status) exec python3 "$ROOT/scripts/d2r-vr.py" "$1"', action)
+ self.assertIn('setup|play) exec python3 "$ROOT/scripts/d2r-vr.py" "$1"', action)
+ self.assertIn('status) exec python3 "$ROOT/scripts/d2r-vr.py" status --json', action)
+ self.assertIn('play --flat --view "${2:-first}"', action)
library = (ROOT / 'app/Library.swift').read_text()
- self.assertIn('model.run(["vr", "setup"]', library)
- self.assertIn('task(["vr", flat ? "flat" : "play"]', library)
- self.assertIn('flat) exec python3 "$ROOT/scripts/d2r-vr.py" play --flat', action)
- self.assertIn('model.playVR(game, flat: true)', library)
+ sheet = (ROOT / 'app/VRSheet.swift').read_text()
+ self.assertIn('model.run(["vr", "setup"]', sheet)
+ self.assertIn('task(flat ? ["vr", "flat", view] : ["vr", "play"]', library)
+ self.assertIn('model.playVR(game, flat: true, view: flatView)', sheet)
+ self.assertIn('D2RVRSheet(model: model, game: game', library)
+ self.assertIn('VRSheet.swift', (ROOT / 'scripts/build-app.sh').read_text())
+ # the sheet reads these fields from `soju vr status --json`
+ for field in ('installed', 'current', 'source_build', 'source_supported'):
+ self.assertIn(field, sheet)
+
+ def test_flat_play_sets_the_mods_mode_and_view(self):
+ with tempfile.TemporaryDirectory() as d:
+ game = Path(d)
+ ini = game / 'mods/D2R-PCVR/d2rloader/plugins/d2r_pcvr.ini'
+ ini.parent.mkdir(parents=True)
+ ini.write_bytes(b'[stereo]\r\nplatform = 9\r\n[mode]\r\nplatform = 1\r\nflat_view = 3\r\nvr_mode = 4\r\n')
+ vr.set_mode(game, True, 'third')
+ self.assertEqual(ini.read_bytes(),
+ b'[stereo]\r\nplatform = 9\r\n[mode]\r\nplatform = 0\r\nflat_view = 2\r\nvr_mode = 4\r\n')
+ vr.set_mode(game, True, 'classic')
+ self.assertIn(b'flat_view = 1\r\n', ini.read_bytes())
+ vr.set_mode(game, False) # VR again: the headset, the flat view kept for next time
+ self.assertIn(b'[mode]\r\nplatform = 1\r\nflat_view = 1\r\n', ini.read_bytes())
+ vr.set_mode(Path(d) / 'missing', True) # no mod installed: nothing to do, no error
+
+ def test_dlss_follows_the_metalfx_bridge(self):
+ with tempfile.TemporaryDirectory() as d:
+ saves = Path(d)
+ settings = saves / 'Settings.json'
+ settings.write_text(json.dumps({'Screen Resolution (Windowed)': '3440x1440', 'Window Mode': 2, 'NVIDIA DLSS': 2}))
+ vr.fix_settings(saves, flat=True, dlss=True) # Mac screen, bridge ready: all as the player chose
+ self.assertEqual(json.loads(settings.read_text()),
+ {'Screen Resolution (Windowed)': '3440x1440', 'Window Mode': 2, 'NVIDIA DLSS': 2})
+ vr.fix_settings(saves, flat=True, dlss=False) # no Apple shim on this engine: DLSS off
+ self.assertEqual(json.loads(settings.read_text())['NVIDIA DLSS'], 0)
+ self.assertEqual(json.loads(settings.read_text())['Window Mode'], 2)
+
+ def test_dlss_bridge_puts_the_unwrapper_in_front_of_apples_shim(self):
+ from unittest import mock
+ with tempfile.TemporaryDirectory() as d:
+ base = Path(d)
+ engine, vrdir = base / 'engine', base / 'd2r-vr'
+ win, unix = engine / 'lib/wine/x86_64-windows', engine / 'lib/wine/x86_64-unix'
+ for folder in (win, unix, engine / 'lib/external', vrdir / 'dlss', vrdir / 'bottle/drive_c/windows/system32'):
+ folder.mkdir(parents=True)
+ (engine / 'lib/external/libd3dshared.dylib').write_bytes(b'x')
+ (win / 'nvngx.dll').write_bytes(b'MZ apple D3DMetalDLLsBase shim')
+ (vrdir / 'dlss/nvngx.dll').write_bytes(b'MZ soju unwrapper')
+ (vrdir / 'bottle/system.reg').write_text('[Software\\\\NVIDIA Corporation\\\\Global\\\\NGXCore] 1\n')
+ m = {'ngx_unwrap': {'sha256': vr.digest(vrdir / 'dlss/nvngx.dll')}}
+ with mock.patch.multiple(vr, ENGINE=engine, VR=vrdir, BOTTLE=vrdir / 'bottle'), \
+ mock.patch.object(vr, 'wine') as wine:
+ self.assertTrue(vr.dlss_bridge(m))
+ wine.assert_not_called() # the copy already has the NGXCore key
+ system32 = vrdir / 'bottle/drive_c/windows/system32'
+ self.assertEqual((system32 / 'nvngx.dll').read_bytes(), b'MZ soju unwrapper')
+ self.assertEqual((system32 / 'nvngx_metalfx.dll').read_bytes(), b'MZ apple D3DMetalDLLsBase shim')
+ self.assertEqual((win / 'nvngx_metalfx.dll').read_bytes(), b'MZ apple D3DMetalDLLsBase shim')
+ self.assertEqual(os.readlink(unix / 'nvngx_metalfx.so'), '../../external/libd3dshared.dylib')
+ (win / 'nvngx.dll').write_bytes(b'MZ wine placeholder') # no Apple shim: no DLSS
+ with mock.patch.multiple(vr, ENGINE=engine, VR=vrdir, BOTTLE=vrdir / 'bottle'):
+ self.assertFalse(vr.dlss_bridge(m))
+ env = vr.play_env(True, dlss=True)
+ self.assertEqual(env['D3DM_ENABLE_METALFX'], '1')
+ self.assertEqual(env['WINEDLLOVERRIDES'], 'nvngx=n')
+ self.assertNotIn('D3DM_ENABLE_METALFX', vr.play_env(True))
def test_user_folder_links_become_folders_in_the_copy(self):
with tempfile.TemporaryDirectory() as d:
diff --git a/tools/ngx-unwrap/build.sh b/tools/ngx-unwrap/build.sh
new file mode 100755
index 00000000000..7f78f52aed6
--- /dev/null
+++ b/tools/ngx-unwrap/build.sh
@@ -0,0 +1,11 @@
+#!/bin/sh
+# Build nvngx.dll (the ReShade unwrapper for the D2R VR copy) with a MinGW-w64 x86_64 compiler:
+# tools/ngx-unwrap/build.sh [compiler] [output]
+# Default compiler: x86_64-w64-mingw32-gcc (Homebrew mingw-w64) or llvm-mingw's clang.
+set -eu
+here=$(cd "$(dirname "$0")" && pwd)
+cc=${1:-x86_64-w64-mingw32-gcc}
+out=${2:-$here/../../dist/vr-mod/soju-nvngx.dll}
+mkdir -p "$(dirname "$out")"
+"$cc" -O2 -Wall -shared -s -Wl,--no-insert-timestamp -o "$out" "$here/ngx_unwrap.c" "$here/nvngx.def"
+shasum -a 256 "$out"; wc -c < "$out"
diff --git a/tools/ngx-unwrap/ngx_unwrap.c b/tools/ngx-unwrap/ngx_unwrap.c
new file mode 100644
index 00000000000..7a60a9147a7
--- /dev/null
+++ b/tools/ngx-unwrap/ngx_unwrap.c
@@ -0,0 +1,107 @@
+/* nvngx.dll for the D2R VR copy (scripts/d2r-vr.py).
+ *
+ * The VR mod runs the game under ReShade, which hands the game its own wrappers of the
+ * D3D12 device and command lists. Apple's NGX shim (D3DMetal's DLSS -> MetalFX bridge)
+ * treats the command list it is given as D3DMetal's own object, so a ReShade wrapper
+ * crashes NVSDK_NGX_D3D12_CreateFeature and the game hangs in its crash handler at the
+ * title (seen 2026-11-25, D2R 3.4, ReShade 6.8.0, GPTK 3.0).
+ *
+ * This DLL sits in front of the shim (installed as nvngx_metalfx.dll) and passes it the
+ * original objects. A ReShade 6 proxy starts with its COM vtable, then the
+ * reshade::api object vtable, both inside ReShade64.dll, then the original pointer.
+ * Anything that does not look like that is passed through unchanged. Every other
+ * export is forwarded as is. */
+#include <windows.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+static HMODULE real, reshade;
+
+static HMODULE owner(const void *p)
+{
+ HMODULE m = NULL;
+ if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, p, &m))
+ return NULL;
+ return m;
+}
+
+static BOOL readable(const void *p, SIZE_T n)
+{
+ MEMORY_BASIC_INFORMATION mbi;
+ if (!p || !VirtualQuery(p, &mbi, sizeof(mbi)) || mbi.State != MEM_COMMIT) return FALSE;
+ if (mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD)) return FALSE;
+ return (const char *)p + n <= (const char *)mbi.BaseAddress + mbi.RegionSize;
+}
+
+static void *unwrap(void *obj)
+{
+ void *orig;
+ if (!reshade) reshade = GetModuleHandleW(L"ReShade64.dll");
+ if (!reshade || !readable(obj, 3 * sizeof(void *))) return obj;
+ if (owner(*(void **)obj) != reshade) return obj; /* not a ReShade proxy */
+ if (owner(((void **)obj)[1]) != reshade) return obj; /* not the layout above */
+ orig = ((void **)obj)[2];
+ /* D3DMetal's objects live in host memory outside the Windows address map, so
+ * VirtualQuery cannot vouch for them: only reject what clearly is not one. */
+ if ((uintptr_t)orig < 0x10000 || owner(orig) == reshade) return obj;
+ if (readable(orig, sizeof(void *)) && owner(*(void **)orig) == reshade) return obj;
+ return orig;
+}
+
+static void note(const char *what, void *in, void *out)
+{
+ FILE *f;
+ if (!getenv("SOJU_NGX_LOG") || !(f = fopen("C:\\soju-ngx.log", "a"))) return;
+ fprintf(f, "%s %p -> %p%s\n", what, in, out, in == out ? " (passed through)" : "");
+ fclose(f);
+}
+
+static FARPROC get(const char *name)
+{
+ if (!real) real = LoadLibraryW(L"nvngx_metalfx.dll");
+ return real ? GetProcAddress(real, name) : NULL;
+}
+
+#define NGX_FAIL 0xBAD00000u /* NVSDK_NGX_Result_Fail */
+typedef unsigned int (*f4)(void *, uintptr_t, uintptr_t, uintptr_t);
+typedef unsigned int (*f5)(uintptr_t, uintptr_t, void *, uintptr_t, uintptr_t);
+typedef unsigned int (*f7)(uintptr_t, uintptr_t, uintptr_t, uintptr_t, void *, uintptr_t, uintptr_t);
+#define REAL(name) static FARPROC p; void *u; if (!p && !(p = get(#name))) return NGX_FAIL
+
+__declspec(dllexport) unsigned int NVSDK_NGX_D3D12_Init(uintptr_t a, uintptr_t b, void *dev, uintptr_t d, uintptr_t e)
+{
+ REAL(NVSDK_NGX_D3D12_Init);
+ u = unwrap(dev); note(__func__, dev, u);
+ return ((f5)p)(a, b, u, d, e);
+}
+__declspec(dllexport) unsigned int NVSDK_NGX_D3D12_Init_Ext(uintptr_t a, uintptr_t b, void *dev, uintptr_t d, uintptr_t e)
+{
+ REAL(NVSDK_NGX_D3D12_Init_Ext);
+ u = unwrap(dev); note(__func__, dev, u);
+ return ((f5)p)(a, b, u, d, e);
+}
+__declspec(dllexport) unsigned int NVSDK_NGX_D3D12_Init_ProjectID(uintptr_t a, uintptr_t b, uintptr_t c, uintptr_t d, void *dev, uintptr_t f, uintptr_t g)
+{
+ REAL(NVSDK_NGX_D3D12_Init_ProjectID);
+ u = unwrap(dev); note(__func__, dev, u);
+ return ((f7)p)(a, b, c, d, u, f, g);
+}
+__declspec(dllexport) unsigned int NVSDK_NGX_D3D12_CreateFeature(void *list, uintptr_t b, uintptr_t c, uintptr_t d)
+{
+ REAL(NVSDK_NGX_D3D12_CreateFeature);
+ u = unwrap(list); note(__func__, list, u);
+ return ((f4)p)(u, b, c, d);
+}
+__declspec(dllexport) unsigned int NVSDK_NGX_D3D12_EvaluateFeature(void *list, uintptr_t b, uintptr_t c, uintptr_t d)
+{
+ REAL(NVSDK_NGX_D3D12_EvaluateFeature);
+ u = unwrap(list);
+ return ((f4)p)(u, b, c, d);
+}
+
+BOOL WINAPI DllMain(HINSTANCE h, DWORD reason, void *reserved)
+{
+ if (reason == DLL_PROCESS_ATTACH) DisableThreadLibraryCalls(h);
+ return TRUE;
+}
diff --git a/tools/ngx-unwrap/nvngx.def b/tools/ngx-unwrap/nvngx.def
new file mode 100644
index 00000000000..08cbb4301f7
--- /dev/null
+++ b/tools/ngx-unwrap/nvngx.def
@@ -0,0 +1,30 @@
+LIBRARY nvngx.dll
+EXPORTS
+ NVSDK_NGX_D3D11_AllocateParameters=nvngx_metalfx.NVSDK_NGX_D3D11_AllocateParameters
+ NVSDK_NGX_D3D11_CreateFeature=nvngx_metalfx.NVSDK_NGX_D3D11_CreateFeature
+ NVSDK_NGX_D3D11_DestroyParameters=nvngx_metalfx.NVSDK_NGX_D3D11_DestroyParameters
+ NVSDK_NGX_D3D11_EvaluateFeature=nvngx_metalfx.NVSDK_NGX_D3D11_EvaluateFeature
+ NVSDK_NGX_D3D11_GetCapabilityParameters=nvngx_metalfx.NVSDK_NGX_D3D11_GetCapabilityParameters
+ NVSDK_NGX_D3D11_GetFeatureRequirements=nvngx_metalfx.NVSDK_NGX_D3D11_GetFeatureRequirements
+ NVSDK_NGX_D3D11_GetParameters=nvngx_metalfx.NVSDK_NGX_D3D11_GetParameters
+ NVSDK_NGX_D3D11_GetScratchBufferSize=nvngx_metalfx.NVSDK_NGX_D3D11_GetScratchBufferSize
+ NVSDK_NGX_D3D11_Init=nvngx_metalfx.NVSDK_NGX_D3D11_Init
+ NVSDK_NGX_D3D11_Init_Ext=nvngx_metalfx.NVSDK_NGX_D3D11_Init_Ext
+ NVSDK_NGX_D3D11_Init_ProjectID=nvngx_metalfx.NVSDK_NGX_D3D11_Init_ProjectID
+ NVSDK_NGX_D3D11_ReleaseFeature=nvngx_metalfx.NVSDK_NGX_D3D11_ReleaseFeature
+ NVSDK_NGX_D3D11_Shutdown=nvngx_metalfx.NVSDK_NGX_D3D11_Shutdown
+ NVSDK_NGX_D3D11_Shutdown1=nvngx_metalfx.NVSDK_NGX_D3D11_Shutdown1
+ NVSDK_NGX_D3D12_AllocateParameters=nvngx_metalfx.NVSDK_NGX_D3D12_AllocateParameters
+ NVSDK_NGX_D3D12_CreateFeature
+ NVSDK_NGX_D3D12_DestroyParameters=nvngx_metalfx.NVSDK_NGX_D3D12_DestroyParameters
+ NVSDK_NGX_D3D12_EvaluateFeature
+ NVSDK_NGX_D3D12_GetCapabilityParameters=nvngx_metalfx.NVSDK_NGX_D3D12_GetCapabilityParameters
+ NVSDK_NGX_D3D12_GetFeatureRequirements=nvngx_metalfx.NVSDK_NGX_D3D12_GetFeatureRequirements
+ NVSDK_NGX_D3D12_GetParameters=nvngx_metalfx.NVSDK_NGX_D3D12_GetParameters
+ NVSDK_NGX_D3D12_GetScratchBufferSize=nvngx_metalfx.NVSDK_NGX_D3D12_GetScratchBufferSize
+ NVSDK_NGX_D3D12_Init
+ NVSDK_NGX_D3D12_Init_Ext
+ NVSDK_NGX_D3D12_Init_ProjectID
+ NVSDK_NGX_D3D12_ReleaseFeature=nvngx_metalfx.NVSDK_NGX_D3D12_ReleaseFeature
+ NVSDK_NGX_D3D12_Shutdown=nvngx_metalfx.NVSDK_NGX_D3D12_Shutdown
+ NVSDK_NGX_D3D12_Shutdown1=nvngx_metalfx.NVSDK_NGX_D3D12_Shutdown1