Run Windows games on Apple Silicon — free, open source, with an open compatibility database that tells you what actually works.
Swift apple-silicond3dmetaldxmtdxvkfexgame-porting-toolkitgamingmac-gamingmacosmetalmoltenvksteamswiftuivkd3d-protonwhisky-alternativewindows-gameswinewine-wrapper
Engine r1: MoltenVK component with the shadow-import patch, and an engine update path
Gauthier Piarrettedacbb69edf54
diff --git a/Scripts/build-moltenvk.sh b/Scripts/build-moltenvk.shnew file mode 100755index 0000000..b2ac49b--- /dev/null+++ b/Scripts/build-moltenvk.sh@@ -0,0 +1,25 @@+#!/bin/bash+# Reproducible build of the engine's MoltenVK component: a pinned upstream tag plus Highball's+# patches, x86_64 only (the engine's Wine is x86_64 under Rosetta), packaged as the tarball the+# engine manifest points at. Usage: Scripts/build-moltenvk.sh [tag] [out-dir]+set -euo pipefail+TAG="${1:-v1.4.1}"+OUT="${2:-$(pwd)/build-moltenvk}"+PATCH="$(cd "$(dirname "$0")/.." && pwd)/spike/patches/moltenvk-shadow-import.patch"+WORK="$(mktemp -d)"+echo "[moltenvk] tag $TAG, work dir $WORK"+git clone -q --depth 1 --branch "$TAG" https://github.com/KhronosGroup/MoltenVK.git "$WORK/src"+cd "$WORK/src"+git apply --check "$PATCH" && git apply "$PATCH"+./fetchDependencies --macos+xcodebuild build -project MoltenVKPackaging.xcodeproj -scheme "MoltenVK Package (macOS only)" \+ -destination "generic/platform=macOS" -configuration Release ARCHS=x86_64 ONLY_ACTIVE_ARCH=NO -quiet+DYLIB="$(find Package/Release -name libMoltenVK.dylib -path '*macOS*' | head -1)"+test -f "$DYLIB"+strings "$DYLIB" | grep -q "HIGHBALL shadow-import" || { echo "patch missing from build"; exit 1; }+mkdir -p "$OUT/pkg" && cp "$DYLIB" "$OUT/pkg/libMoltenVK.dylib"+NAME="moltenvk-${TAG#v}-shadow-import-1-x86_64.tar.gz"+tar -czf "$OUT/$NAME" -C "$OUT/pkg" libMoltenVK.dylib+echo "[moltenvk] $OUT/$NAME"+echo " sha256: $(shasum -a 256 "$OUT/$NAME" | awk '{print $1}')"+echo " size: $(stat -f %z "$OUT/$NAME")"diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swiftindex 579a810..3092574 100644--- a/Sources/HighballApp/AppState.swift+++ b/Sources/HighballApp/AppState.swift@@ -239,7 +239,71 @@ final class AppState {}func engine(for bottle: Bottle) -> InstalledEngine? {- (try? engineStore.engine(bottle.settings.engineID)) ?? engines.first+ (try? engineStore.engine(bottle.settings.engineID)) ?? defaultEngine+ }++ /// The engine new bottles get and the sidebar shows: the one the bundled manifest names when+ /// it is installed, else the first installed. Without this, an engine update would leave+ /// two engines side by side and `engines.first` (alphabetical) would keep picking the old one.+ var defaultEngine: InstalledEngine? {+ EngineStore.defaultEngine(installed: engines, bundledID: Self.bundledManifestID)+ }++ static var bundledManifestID: String? {+ guard let url = bundledManifest, let m = try? EngineManifest.load(from: url) else { return nil }+ return m.id+ }++ /// The bundled manifest when it names an engine that is not installed yet while another one+ /// is: an engine update is available. New installs never see this (onboarding installs the+ /// bundled engine directly).+ var engineUpdate: EngineManifest? {+ guard !engines.isEmpty, let url = Self.bundledManifest,+ let m = try? EngineManifest.load(from: url),+ !engines.contains(where: { $0.id == m.id }) else { return nil }+ return m+ }++ /// Installs the bundled engine next to the current one, points every bottle at it, refreshes+ /// each bottle's Windows environment (wineboot), and removes the old engine directory.+ /// Licenses already accepted on the old engine carry over; the download cache makes an+ /// update cost only the components that actually changed.+ func updateEngine() {+ guard let manifest = engineUpdate, let old = defaultEngine else { return }+ let oldID = old.id+ let accepted = Set(engines.flatMap { $0.manifest.acceptedLicenses ?? [] })+ let title = String(format: L("Updating engine to %@"), manifest.id)+ runBusy(title, expected: L("usually a few minutes"),+ done: DoneState(title: L("Engine updated"), ctaTitle: nil, cta: nil)) { [self] in+ let fresh = try await engineStore.install(manifest, accepted: accepted) { name, received, total in+ Task { @MainActor in+ let mb = { (b: Int64) in String(format: "%.0f", Double(b) / 1_048_576) }+ if let total, total > 0 { self.stage = "Downloading \(name) — \(mb(received)) / \(mb(total)) MB" }+ else { self.stage = "Downloading \(name) — \(mb(received)) MB" }+ }+ }+ await MainActor.run { self.appendLog("engine \(fresh.id) installed") }+ for var bottle in try bottleStore.list() where bottle.settings.engineID != fresh.id {+ let runnerOld = WineRunner(paths: paths, engine: old, bottle: bottle)+ try? runnerOld.kill()+ try? await Task.sleep(for: .seconds(2))+ bottle.settings.engineID = fresh.id+ try bottle.save()+ await MainActor.run { self.stage = String(format: L("Refreshing bottle '%@'"), bottle.name) }+ let runner = WineRunner(paths: paths, engine: fresh, bottle: bottle)+ let r = try await runner.wineboot()+ guard r.exitStatus == 0 else {+ throw HighballError.processFailed(command: "wineboot -u", status: r.exitStatus, output: "see \(r.log.path)")+ }+ try await BottleStore.ensureWoW64(runner: runner, bottle: bottle, log: r.log)+ try? await runner.setGpuIdentity()+ try? await runner.setServiceTimeout()+ try? await runner.setKeyboardMapping(commandIsControl: bottle.settings.commandIsControl)+ await MainActor.run { self.appendLog("bottle '\(bottle.name)' moved to \(fresh.id)") }+ }+ if oldID != fresh.id { try? FileManager.default.removeItem(at: old.root) }+ await MainActor.run { self.appendLog("old engine \(oldID) removed") }+ }}/// What to put in front of the user when something throws. Interpolating an NSError dumps@@ -322,7 +386,7 @@ final class AppState {}func createBottle(name: String, recipeID: String?) {- guard let engine = engines.first else { return }+ guard let engine = defaultEngine else { return }runBusy("Creating bottle '\(name)' — first boot takes about 90 seconds",done: DoneState(title: String(format: L("Bottle '%@' is ready"), name), ctaTitle: nil, cta: nil)) { [self] inlet bottle = try await bottleStore.create(name: name, engine: engine)diff --git a/Sources/HighballApp/HighballApp.swift b/Sources/HighballApp/HighballApp.swiftindex 659bec4..817fa2d 100644--- a/Sources/HighballApp/HighballApp.swift+++ b/Sources/HighballApp/HighballApp.swift@@ -215,7 +215,7 @@ struct ContentView: View {.listRowInsets(EdgeInsets(top: 1, leading: 6, bottom: 1, trailing: 6))}}- if let engine = state.engines.first {+ if let engine = state.defaultEngine {Section(L("Engine")) {Label {VStack(alignment: .leading, spacing: 1) {@@ -223,6 +223,21 @@ struct ContentView: View {Text(engine.id).font(.caption2).foregroundStyle(.tertiary).lineLimit(1)}} icon: { Image(systemName: "gearshape.2").foregroundStyle(.secondary) }+ if let update = state.engineUpdate {+ Button {+ state.updateEngine()+ } label: {+ Label {+ VStack(alignment: .leading, spacing: 1) {+ Text(L("Update engine")).font(.caption)+ Text(update.id).font(.caption2).foregroundStyle(.tertiary).lineLimit(1)+ }+ } icon: { Image(systemName: "arrow.down.circle").foregroundStyle(.tint) }+ }+ .buttonStyle(.plain)+ .disabled(state.busy)+ .help(L("Installs the newer engine this version of Highball ships, moves every bottle to it and refreshes their Windows environment. Only changed components are downloaded."))+ }}}}diff --git a/Sources/HighballApp/L10n.swift b/Sources/HighballApp/L10n.swiftindex 37cf78d..e6a8d0d 100644--- a/Sources/HighballApp/L10n.swift+++ b/Sources/HighballApp/L10n.swift@@ -10,6 +10,12 @@ func L(_ en: String) -> String {enum L10n {static let fr: [String: String] = [// Sidebar & shell+ "Update engine": "Mettre à jour le moteur",+ "Installs the newer engine this version of Highball ships, moves every bottle to it and refreshes their Windows environment. Only changed components are downloaded.": "Installe le moteur plus récent livré avec cette version de Highball, y déplace chaque bouteille et rafraîchit leur environnement Windows. Seuls les composants modifiés sont téléchargés.",+ "Updating engine to %@": "Mise à jour du moteur vers %@",+ "usually a few minutes": "généralement quelques minutes",+ "Engine updated": "Moteur mis à jour",+ "Refreshing bottle '%@'": "Rafraîchissement de la bouteille « %@ »","Use ⌘C / ⌘V inside Windows apps": "Utiliser ⌘C / ⌘V dans les applications Windows","Maps the Command keys to Ctrl, so Mac copy and paste work in Steam and games. Option becomes Alt so Alt-based bindings keep working. Off = Wine's default, where Command acts as Alt.": "Associe les touches Command à Ctrl, pour que le copier-coller du Mac fonctionne dans Steam et les jeux. Option devient Alt afin que les raccourcis Alt continuent de fonctionner. Désactivé = comportement par défaut de Wine, où Command agit comme Alt.","Bottles": "Bouteilles",diff --git a/Sources/HighballKit/EngineStore.swift b/Sources/HighballKit/EngineStore.swiftindex 0e7e989..a5ae8d7 100644--- a/Sources/HighballKit/EngineStore.swift+++ b/Sources/HighballKit/EngineStore.swift@@ -47,6 +47,13 @@ public struct EngineStore: Sendable {}.sorted { $0.manifest.id < $1.manifest.id }}+ /// The engine to use by default: the one the bundled manifest names when it is installed,+ /// else the first installed (alphabetical). After an engine update two engines can coexist+ /// briefly, and "first" would be the old one.+ public static func defaultEngine(installed: [InstalledEngine], bundledID: String?) -> InstalledEngine? {+ installed.first { $0.id == bundledID } ?? installed.first+ }+public func engine(_ id: String) throws -> InstalledEngine {let root = paths.engine(id)let m = try EngineManifest.load(from: root.appending(path: "manifest.json"))@@ -154,7 +161,12 @@ public struct EngineStore: Sendable {guard FileManager.default.fileExists(atPath: source.path) else {throw HighballError.missing("\(ex.subpath ?? ex.strip ?? "") inside \(archive.lastPathComponent)")}- let dest = root.appending(path: ex.into, directoryHint: .isDirectory)+ // `into` names a directory (a whole overlay) or a single file: a component that replaces+ // one file another component installed, like a patched libMoltenVK.dylib on top of the+ // runtime's. A file target leaves the rest of the parent directory alone.+ var isDir: ObjCBool = false+ _ = FileManager.default.fileExists(atPath: source.path, isDirectory: &isDir)+ let dest = root.appending(path: ex.into, directoryHint: isDir.boolValue ? .isDirectory : .notDirectory)try FileManager.default.createDirectory(at: dest.deletingLastPathComponent(), withIntermediateDirectories: true)try? FileManager.default.removeItem(at: dest)try FileManager.default.moveItem(at: source, to: dest)diff --git a/Sources/HighballKit/Manifest.swift b/Sources/HighballKit/Manifest.swiftindex af6cbd7..1f75d83 100644--- a/Sources/HighballKit/Manifest.swift+++ b/Sources/HighballKit/Manifest.swift@@ -25,6 +25,10 @@ public struct EngineManifest: Codable, Sendable, Identifiable {public var extract: Extract?public var note: String?public var version: String?+ /// Install order among components of the same optionality (default 0, lower first).+ /// A component that must land on top of another one's files, like a patched+ /// MoltenVK replacing the runtime's, declares a higher order than the one it overrides.+ public var order: Int?public var isOptional: Bool { optional ?? false }}@@ -67,6 +71,7 @@ public struct EngineManifest: Codable, Sendable, Identifiable {public var orderedComponents: [(name: String, component: Component)] {components.sorted { a, b inif a.value.isOptional != b.value.isOptional { return !a.value.isOptional }+ if (a.value.order ?? 0) != (b.value.order ?? 0) { return (a.value.order ?? 0) < (b.value.order ?? 0) }return a.key < b.key}.map { ($0.key, $0.value) }}diff --git a/Sources/highball/main.swift b/Sources/highball/main.swiftindex 789a7df..f2da6b6 100644--- a/Sources/highball/main.swift+++ b/Sources/highball/main.swift@@ -128,7 +128,7 @@ struct Bottle: AsyncParsableCommand {}struct Set: AsyncParsableCommand {- static let configuration = CommandConfiguration(abstract: "Change a bottle setting: renderer, winver, sync, hud, avx, dpi, dxvkasync, dlloverrides, env KEY=VALUE")+ static let configuration = CommandConfiguration(abstract: "Change a bottle setting: engine, renderer, winver, sync, hud, avx, dpi, dxvkasync, dlloverrides, env KEY=VALUE")@Argument var name: String@Argument var setting: String@Argument var value: String@@ -137,6 +137,11 @@ struct Bottle: AsyncParsableCommand {let bs = BottleStore()var b = try bs.get(name)switch setting {+ case "engine":+ // Point the bottle at another installed engine; run `bottle repair` afterwards so+ // the prefix's Windows environment matches it.+ guard let eng = try? EngineStore().engine(value) else { fail("engine '\(value)' is not installed") }+ b.settings.engineID = eng.idcase "renderer":guard let r = HighballKit.Renderer(rawValue: value) else { fail("bad renderer") }b.settings.renderer = rdiff --git a/Tests/HighballKitTests/RegressionTests.swift b/Tests/HighballKitTests/RegressionTests.swiftindex 40566df..0a385c1 100644--- a/Tests/HighballKitTests/RegressionTests.swift+++ b/Tests/HighballKitTests/RegressionTests.swift@@ -651,6 +651,82 @@ extension RegressionTests {}}+ // A component that replaces a file another component installed (the patched MoltenVK on+ // top of the runtime's) must extract after it. `order` is the only thing that guarantees+ // that: by key alone "moltenvk" sorts before "runtime" and would be silently overwritten.+ func testComponentOrderBeatsAlphabeticalKey() throws {+ let json = """+ {"id":"e","displayName":"e","arch":"x86_64","minMacOS":"14.0","components":{+ "moltenvk":{"kind":"runtime","url":"https://x/m.tgz","sha256":"a","order":1,+ "extract":{"subpath":"libMoltenVK.dylib","into":"frameworks/libMoltenVK.dylib"}},+ "runtime":{"kind":"frameworks","url":"https://x/r.tgz","sha256":"b","extract":{"into":"frameworks"}},+ "d3dmetal":{"kind":"renderer","url":"https://x/d.tgz","sha256":"c","optional":true,"acceptance":"l"}+ }}+ """+ let m = try JSONDecoder().decode(EngineManifest.self, from: Data(json.utf8))+ XCTAssertEqual(m.orderedComponents.map(\.name), ["runtime", "moltenvk", "d3dmetal"],+ "required components by order then key, optional ones last")+ }++ // The shipped manifest must keep that guarantee: the runtime's frameworks land first, the+ // patched MoltenVK replaces exactly one file inside them afterwards.+ func testShippedMoltenVKComponentLandsAfterRuntime() throws {+ let url = URL(fileURLWithPath: #filePath)+ .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()+ .appending(path: "spike/engine-manifest.json")+ let m = try EngineManifest.load(from: url)+ let names = m.orderedComponents.map(\.name)+ guard let r = names.firstIndex(of: "runtime"), let v = names.firstIndex(of: "moltenvk") else {+ return XCTFail("manifest needs both runtime and moltenvk components")+ }+ XCTAssertLessThan(r, v, "moltenvk must extract after runtime or the runtime overwrites it")+ XCTAssertEqual(m.components["moltenvk"]?.extract?.into, "frameworks/libMoltenVK.dylib")+ }++ // After an engine update the old and new engines coexist until the old one is removed;+ // sorted by id the old one comes first, so "first installed" would keep choosing it for+ // new bottles and the sidebar. The bundled manifest's id must win when it is installed.+ func testDefaultEnginePrefersBundledManifestID() throws {+ func engine(_ id: String) throws -> InstalledEngine {+ let json = #"{"id":"\#(id)","displayName":"e","arch":"x86_64","minMacOS":"14.0","components":{}}"#+ let m = try JSONDecoder().decode(EngineManifest.self, from: Data(json.utf8))+ return InstalledEngine(manifest: m, root: URL(fileURLWithPath: "/tmp/\(id)"))+ }+ let old = try engine("x64-sikarugir10.0_6-r0"), new = try engine("x64-sikarugir10.0_6-r1")+ XCTAssertEqual(EngineStore.defaultEngine(installed: [old, new], bundledID: new.id)?.id, new.id)+ XCTAssertEqual(EngineStore.defaultEngine(installed: [old, new], bundledID: nil)?.id, old.id, "no manifest: first installed")+ XCTAssertEqual(EngineStore.defaultEngine(installed: [old], bundledID: new.id)?.id, old.id, "update not installed yet: keep using the old one")+ XCTAssertNil(EngineStore.defaultEngine(installed: [], bundledID: new.id))+ }++ // extract() with a single-file `into` replaces that file and nothing else in the directory.+ // The old code treated every target as a directory, so a file target would have removed+ // the whole frameworks tree on the way in.+ func testExtractSingleFileTargetKeepsSiblings() throws {+ let fm = FileManager.default+ let tmp = fm.temporaryDirectory.appending(path: "hb-extract-\(UUID().uuidString)", directoryHint: .isDirectory)+ let root = tmp.appending(path: "root", directoryHint: .isDirectory)+ let frameworks = root.appending(path: "frameworks", directoryHint: .isDirectory)+ try fm.createDirectory(at: frameworks, withIntermediateDirectories: true)+ try "old".write(to: frameworks.appending(path: "libMoltenVK.dylib"), atomically: true, encoding: .utf8)+ try "keep".write(to: frameworks.appending(path: "libother.dylib"), atomically: true, encoding: .utf8)+ let src = tmp.appending(path: "src", directoryHint: .isDirectory)+ try fm.createDirectory(at: src, withIntermediateDirectories: true)+ try "new".write(to: src.appending(path: "libMoltenVK.dylib"), atomically: true, encoding: .utf8)+ let archive = tmp.appending(path: "m.tar.gz")+ try Shell.run("/usr/bin/tar", ["-czf", archive.path, "-C", src.path, "libMoltenVK.dylib"])+ defer { try? fm.removeItem(at: tmp) }++ let component = try JSONDecoder().decode(EngineManifest.Component.self, from: Data("""+ {"kind":"runtime","url":"https://x/m.tgz","sha256":"a","order":1,+ "extract":{"subpath":"libMoltenVK.dylib","into":"frameworks/libMoltenVK.dylib"}}+ """.utf8))+ try EngineStore().extract(archive, component: component, name: "moltenvk", into: root)+ XCTAssertEqual(try String(contentsOf: frameworks.appending(path: "libMoltenVK.dylib"), encoding: .utf8), "new")+ XCTAssertEqual(try String(contentsOf: frameworks.appending(path: "libother.dylib"), encoding: .utf8), "keep",+ "a file target must not wipe the directory it lands in")+ }+// Issue #31: install progress must be legible without reading raw Wine output. The step// line carries the label, the hint line the slow-step expectation, and neither may leak// into the other.diff --git a/spike/engine-manifest.json b/spike/engine-manifest.jsonindex cb778fa..f0d4525 100644--- a/spike/engine-manifest.json+++ b/spike/engine-manifest.json@@ -1,7 +1,7 @@{"$schema": "https://highball.app/schemas/engine-manifest/v0",- "id": "x64-sikarugir10.0_6-r0",- "displayName": "Wine 10.0 (Sikarugir) + DXMT 0.80 + D3DMetal 3.0",+ "id": "x64-sikarugir10.0_6-r1",+ "displayName": "Wine 10.0 (Sikarugir) + DXMT 0.80 + D3DMetal 3.0 + MoltenVK 1.4.1 (shadow-import patch)","arch": "x86_64","minMacOS": "14.0","requires": [@@ -12,7 +12,8 @@"Vanilla Gcenx wine-devel 11.15 lacks the macdrv_functions export -> DXMT and D3DMetal do NOT work on it. Verified 2026-08-23 with nm.","Runtime dylibs (GStreamer, MoltenVK, gnutls, freetype, SDL2, icu...) are NOT inside the engine; they come from the Sikarugir Wrapper Template's Frameworks/ and are found via DYLD_FALLBACK_LIBRARY_PATH.","Wine 10 still ships a wine64 binary but the loader is `wine`; use `wine` so Wine 11 engines work unchanged.",- "D3DMetal is NOT downloaded separately: the Template's frameworks/renderer/d3dmetal overlay is used, but only exposed once the user has accepted the Apple GPTK license (recorded in manifest.json as acceptedLicenses)."+ "D3DMetal is NOT downloaded separately: the Template's frameworks/renderer/d3dmetal overlay is used, but only exposed once the user has accepted the Apple GPTK license (recorded in manifest.json as acceptedLicenses).",+ "r1 (2026-09-02): adds the moltenvk component. Everything else is byte-identical to r0, so existing downloads are reused; only the 5 MB MoltenVK tarball is new."],"components": {"wine": {@@ -73,6 +74,20 @@"sha256": "f35c29737ca08a583569e6a3752d52fbe23333c5acfad5f16c4177d25eaf3f4b","license": "LGPL-2.1","note": "Pinned to upstream commit 5a59ea07 (20260125+dev, 2026-08-07) — the exact bytes 0.7.x verified with dotnet48. The old branch URL drifted and broke every fresh engine install (issues #27/#28); URLs here must be immutable."+ },+ "moltenvk": {+ "kind": "runtime",+ "url": "https://github.com/gauthierpiarrette/highball/releases/download/engine-components/moltenvk-1.4.1-shadow-import-1-x86_64.tar.gz",+ "sha256": "fbed7b80d6dc2aeaba6fa7047c1fe64827d5004c28029fb43c2bc34f80c35228",+ "size": 1674937,+ "license": "Apache-2.0",+ "version": "1.4.1+shadow-import-1",+ "order": 1,+ "extract": {+ "subpath": "libMoltenVK.dylib",+ "into": "frameworks/libMoltenVK.dylib"+ },+ "note": "MoltenVK 1.4.1 rebuilt with Highball's shadow-import patch (spike/patches/moltenvk-shadow-import.patch, Scripts/build-moltenvk.sh). Replaces the Template's libMoltenVK.dylib. Off unless a launch sets MVK_SHADOW_IMPORT=1: with it, Wine's wow64 host-memory imports are backed by a private Metal buffer synced on every submit, which is what makes 32-bit native-Vulkan games (The Sims Legacy Collection) render instead of losing the device on every vkQueueSubmit."}},"alternatives": {@@ -110,4 +125,4 @@"summary": "Apple Game Porting Toolkit license: non-commercial use/distribution only; no modification; use scoped to developing, testing or evaluating games on Apple hardware."}}-}\ No newline at end of file+}diff --git a/spike/patches/moltenvk-shadow-import.patch b/spike/patches/moltenvk-shadow-import.patchnew file mode 100644index 0000000..993aee2--- /dev/null+++ b/spike/patches/moltenvk-shadow-import.patch@@ -0,0 +1,104 @@+diff --git a/MoltenVK/MoltenVK/GPUObjects/MVKDevice.h b/MoltenVK/MoltenVK/GPUObjects/MVKDevice.h+index 534a414..d7641b3 100644+--- a/MoltenVK/MoltenVK/GPUObjects/MVKDevice.h++++ b/MoltenVK/MoltenVK/GPUObjects/MVKDevice.h+@@ -1106,6 +1106,14 @@ protected:+ MVKLiveResourceSet _liveResources;+ std::mutex _rezLock;+ std::mutex _sem4Lock;++ std::mutex _shadowLock;++ std::vector<MVKDeviceMemory*> _shadowMems;++public:++ void addShadowMemory(MVKDeviceMemory* m) { std::lock_guard<std::mutex> l(_shadowLock); _shadowMems.push_back(m); }++ void removeShadowMemory(MVKDeviceMemory* m) { std::lock_guard<std::mutex> l(_shadowLock); for (auto it=_shadowMems.begin(); it!=_shadowMems.end(); ++it) { if (*it==m) { _shadowMems.erase(it); break; } } }++ void syncShadowMemoriesToDevice();++ void syncShadowMemoriesFromDevice();++protected:+ std::mutex _perfLock;+ std::mutex _vizLock;+ std::string _capturePipeFileName;+diff --git a/MoltenVK/MoltenVK/GPUObjects/MVKDevice.mm b/MoltenVK/MoltenVK/GPUObjects/MVKDevice.mm+index 9772757..dab10d9 100644+--- a/MoltenVK/MoltenVK/GPUObjects/MVKDevice.mm++++ b/MoltenVK/MoltenVK/GPUObjects/MVKDevice.mm+@@ -5638,3 +5638,13 @@ uint64_t mvkGetLocationID(id<MTLDevice> mtlDevice) {++ return hash;+ }++++// HIGHBALL EXPERIMENT: shadow-import sync hooks.++void MVKDevice::syncShadowMemoriesToDevice() {++ std::lock_guard<std::mutex> l(_shadowLock);++ for (auto* m : _shadowMems) { m->syncShadowToDevice(); }++}++void MVKDevice::syncShadowMemoriesFromDevice() {++ std::lock_guard<std::mutex> l(_shadowLock);++ for (auto* m : _shadowMems) { m->syncShadowFromDevice(); }++}+diff --git a/MoltenVK/MoltenVK/GPUObjects/MVKDeviceMemory.h b/MoltenVK/MoltenVK/GPUObjects/MVKDeviceMemory.h+index b349d6e..e0f56fe 100644+--- a/MoltenVK/MoltenVK/GPUObjects/MVKDeviceMemory.h++++ b/MoltenVK/MoltenVK/GPUObjects/MVKDeviceMemory.h+@@ -185,6 +185,12 @@ protected:+ MTLCPUCacheMode _mtlCPUCacheMode;+ bool _isDedicated = false;+ bool _isHostMemImported = false;++ // HIGHBALL EXPERIMENT: imported host memory backed by a private copy instead of no-copy.++ void* _pShadowHost = nullptr;++ NSUInteger _shadowLen = 0;++public:++ void syncShadowToDevice();++ void syncShadowFromDevice();+ VkExternalMemoryHandleTypeFlags _externalMemoryHandleType = 0u;+ };++diff --git a/MoltenVK/MoltenVK/GPUObjects/MVKDeviceMemory.mm b/MoltenVK/MoltenVK/GPUObjects/MVKDeviceMemory.mm+index e6e7786..f82460a 100644+--- a/MoltenVK/MoltenVK/GPUObjects/MVKDeviceMemory.mm++++ b/MoltenVK/MoltenVK/GPUObjects/MVKDeviceMemory.mm+@@ -255,7 +255,15 @@+ [buf makeAliasable];+ } else if (_pHostMemory) {+ auto rezOpts = getMTLResourceOptions();+- if (_isHostMemImported) {++ if (_isHostMemImported && getenv("MVK_SHADOW_IMPORT")) {++ // HIGHBALL EXPERIMENT: back imported host memory with a normal MTLBuffer and keep the++ // host pages as the CPU-side shadow, synced on every queue submission.++ buf = [getMTLDevice() newBufferWithBytes: _pHostMemory length: memLen options: rezOpts]; // retained++ _pShadowHost = _pHostMemory;++ _shadowLen = memLen;++ _device->addShadowMemory(this);++ MVKLogInfo("HIGHBALL shadow-import: %lu bytes at %p", (unsigned long)memLen, _pHostMemory);++ } else if (_isHostMemImported) {+ buf = [getMTLDevice() newBufferWithBytesNoCopy: _pHostMemory length: memLen options: rezOpts deallocator: nil]; // retained+ } else {+ buf = [getMTLDevice() newBufferWithBytes: _pHostMemory length: memLen options: rezOpts]; // retained+@@ -499,7 +507,16 @@+ }+ }+++void MVKDeviceMemory::syncShadowToDevice() {++ if (_pShadowHost && _mtlBuffer) { memcpy(_mtlBuffer.contents, _pShadowHost, _shadowLen); }++}++++void MVKDeviceMemory::syncShadowFromDevice() {++ if (_pShadowHost && _mtlBuffer) { memcpy(_pShadowHost, _mtlBuffer.contents, _shadowLen); }++}+++ MVKDeviceMemory::~MVKDeviceMemory() {++ if (_pShadowHost) { _device->removeShadowMemory(this); _pShadowHost = nullptr; }+ // Unbind any resources that are using me.+ // Manually null the binding parameter to prevent them from trying to remove themselves from the array.+ // This will leave texture buffer pointers dangling, but according to Vulkan, those are not supposed to be used again anyways.+diff --git a/MoltenVK/MoltenVK/GPUObjects/MVKQueue.mm b/MoltenVK/MoltenVK/GPUObjects/MVKQueue.mm+index dec4b45..6b81d2a 100644+--- a/MoltenVK/MoltenVK/GPUObjects/MVKQueue.mm++++ b/MoltenVK/MoltenVK/GPUObjects/MVKQueue.mm+@@ -84,6 +84,7 @@+ // Submit regardless of config result, to ensure submission semaphores and fences are signalled.+ // The submissions will ensure a misconfiguration will be safe to execute.+ VkResult rslt = qSubmit->getConfigurationResult();++ _device->syncShadowMemoriesToDevice(); // HIGHBALL EXPERIMENT+ if (_execQueue) {+ std::unique_lock lock(_execQueueMutex);+ _execQueueJobCount++;