@team-antioch/sc2-adjutant-host-macos 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +52 -2
- package/dist/.built +0 -0
- package/dist/capture-tour.js +562 -0
- package/dist/index.js +242 -0
- package/dist/refresh.js +72 -0
- package/dist/whiteoutflakes.js +46 -0
- package/docs/macos-host.md +129 -0
- package/package.json +33 -4
- package/sc2-adjutant-plugin.json +8 -0
- package/scripts/build-whiteoutflakes.sh +82 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 TeamAntioch
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,53 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @team-antioch/sc2-adjutant-host-macos
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The macOS **Host Adapter** for [sc2-adjutant](https://github.com/TeamAntioch/sc2-adjutant). It is the Plugin that does what a Mac can do with StarCraft II, so the co-design tools can open, test and look at your maps for you. Without it, those tools hand you the steps to follow in the Editor yourself.
|
|
4
|
+
|
|
5
|
+
## What it does
|
|
6
|
+
|
|
7
|
+
| Capability | How |
|
|
8
|
+
|---|---|
|
|
9
|
+
| `editor.open`, `editor.checkClosed`, `editor.refresh` | Opens a Map Package in the Galaxy Editor, tells whether the Editor has it open, and closes a clean copy so a compile can rewrite it. It never saves or discards your changes. |
|
|
10
|
+
| `editor.testDocument`, `editor.save` | Runs File > Test Document, and saves a throwaway copy of a map, through the Editor's menus. |
|
|
11
|
+
| `editor.captureTour`, `editor.closeCaptureCopies`, `game.running` | Plays a capture map and screenshots each camera stop, then closes it unsaved. Captures run one at a time through the Editor Broker. |
|
|
12
|
+
| `screen.capture` | Captures the game's window, else the Editor's. |
|
|
13
|
+
| `tts.speak` | Speaks placeholder voice lines with macOS's `say`. |
|
|
14
|
+
| `model.render`, `model.rendererKey`, `model.export`, `model.exportGltf` | Renders game and mod models to turntable thumbnails, and exports them as `.m3` or glTF, with the WhiteoutFlakes model viewer. |
|
|
15
|
+
|
|
16
|
+
It has no `game.launch`, because the Mac game starts only through the Editor's Test Document.
|
|
17
|
+
|
|
18
|
+
## Install
|
|
19
|
+
|
|
20
|
+
`npx @team-antioch/sc2-adjutant init` installs it in a new Workspace on a Mac, and names it in your machine config. To add it to an existing Workspace:
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
npm install @team-antioch/sc2-adjutant-host-macos
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Then name it in your machine config, `~/.config/sc2-adjutant/machine.json`. It loads only when it's named:
|
|
27
|
+
|
|
28
|
+
```json
|
|
29
|
+
{
|
|
30
|
+
"hostAdapter": "bundled:host-macos",
|
|
31
|
+
"editorPath": "/Applications/StarCraft II Editor (Fixed).app",
|
|
32
|
+
"cacheDir": "~/Library/Caches/sc2-adjutant",
|
|
33
|
+
"modelViewerPath": "~/.cache/sc2-adjutant/whiteoutflakes/stage/WhiteoutFlakes.app/Contents/MacOS/WhiteoutFlakes"
|
|
34
|
+
}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
It needs sc2-adjutant core (`@team-antioch/sc2-adjutant`) installed beside it, which is a peer dependency.
|
|
38
|
+
|
|
39
|
+
## What it needs
|
|
40
|
+
|
|
41
|
+
- **`editorPath`**: the Galaxy Editor app to launch. On Apple Silicon, the native Editor runs only through a community fix that ships as a launcher app ([the native Editor fix](https://github.com/TeamAntioch/sc2-adjutant/blob/main/packages/plugin-host-macos/docs/macos-host.md#the-native-editor-fix)). Point `editorPath` at that launcher, since the bare Editor crashes at launch.
|
|
42
|
+
- **`cacheDir`**: a folder outside the Workspace for capture copies and the model viewer's working copies.
|
|
43
|
+
- **Accessibility and Screen Recording permission** for the app that runs the MCP server (your terminal, or Claude Code). The Editor is driven through its menus, and captures read the screen.
|
|
44
|
+
- **For models, `modelViewerPath`**: the WhiteoutFlakes viewer, which `scripts/build-whiteoutflakes.sh [dir]` builds. It needs Xcode, with its Metal toolchain, Homebrew, git, and the GitHub CLI (`gh`) signed in, which downloads the shader compiler. Re-running it skips the steps already done.
|
|
45
|
+
|
|
46
|
+
Every path comes from the machine config. Nothing about your machine is built in, so a capability that needs a missing setting fails with the setting to add. The rest of the machine config is in [core's README](https://github.com/TeamAntioch/sc2-adjutant/tree/main/packages/core#the-machine-config).
|
|
47
|
+
|
|
48
|
+
## More
|
|
49
|
+
|
|
50
|
+
- [`docs/macos-host.md`](https://github.com/TeamAntioch/sc2-adjutant/blob/main/packages/plugin-host-macos/docs/macos-host.md): the Editor and game behaviour this adapter relies on, and how to do each step by hand.
|
|
51
|
+
- [The plugin API](https://github.com/TeamAntioch/sc2-adjutant/blob/main/docs/plugin-api.md#host-adapter-kinds): what every Host Adapter capability takes and returns.
|
|
52
|
+
|
|
53
|
+
MIT licensed.
|
package/dist/.built
ADDED
|
File without changes
|
|
@@ -0,0 +1,562 @@
|
|
|
1
|
+
// editor.captureTour and screen.capture on the Mac: camera-tour captures driven through the Galaxy
|
|
2
|
+
// Editor, as the Exemplar and cinematic-set captures were with their shell scripts. Opens the
|
|
3
|
+
// capture map with the Editor at `editorPath`, clicks File > Test Document, screenshots the game
|
|
4
|
+
// window each time the map announces a new stop in its bank, then quits the game and closes the map
|
|
5
|
+
// without saving. Only documents under <cacheDir>/capture/maps/ are ever closed or discarded.
|
|
6
|
+
//
|
|
7
|
+
// Mac facts it relies on (docs/reference/game-testing.md has more):
|
|
8
|
+
// - The Editor has to come forward for a moment to open its menu; macOS refuses that while someone
|
|
9
|
+
// is using another app. Then this posts a notification and, for up to 15 minutes, tries again
|
|
10
|
+
// every 30 seconds (it gets through once they pause) while waiting for their click.
|
|
11
|
+
// - With the Editor's Test Document window mode set to Windowed, the game can sit behind other
|
|
12
|
+
// windows (`screencapture -l` reads a covered window), but not minimized; a locked or sleeping
|
|
13
|
+
// screen hides every window from Accessibility, so the display is kept awake.
|
|
14
|
+
// - The game saves banks to ~/Library/Application Support/Blizzard/StarCraft II/Banks/.
|
|
15
|
+
// - Save prompts are sometimes invisible to Accessibility; they are read and answered by OCR.
|
|
16
|
+
// - A loading screen may wait for Space; pressing it takes focus, so only after a long wait.
|
|
17
|
+
// Needs Accessibility and Screen Recording for the app that runs it.
|
|
18
|
+
import { execFile, spawn } from "node:child_process";
|
|
19
|
+
import { existsSync } from "node:fs";
|
|
20
|
+
import { appendFile, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
21
|
+
import os from "node:os";
|
|
22
|
+
import path from "node:path";
|
|
23
|
+
import { promisify } from "node:util";
|
|
24
|
+
import { CAPTURE_MAPS_FOLDER } from "@team-antioch/sc2-adjutant/plugin-sdk";
|
|
25
|
+
const run = promisify(execFile);
|
|
26
|
+
const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));
|
|
27
|
+
const EDITOR = "StarCraft II Editor";
|
|
28
|
+
/**
|
|
29
|
+
* What a window title holds for this capture copy: its file name after a slash. Not its folder: the
|
|
30
|
+
* Editor shortens a long title's path ("[/.../maps/<name>]"), and with a long enough name even
|
|
31
|
+
* "capture/" goes. The name is enough, since each copy's name ends in its job id.
|
|
32
|
+
*/
|
|
33
|
+
export const captureFragment = (mapPath) => `/${path.basename(mapPath)}`;
|
|
34
|
+
/** A copy the Editor Broker named: `<map> <label>-<job id>.SC2Map`, the id base-36 milliseconds and a count. */
|
|
35
|
+
const BROKER_COPY_NAME = / [^/]*-[0-9a-z]{9,}\.SC2Map$/i;
|
|
36
|
+
/** The .SC2Map file names in the Editor's window titles, whatever of their path the title shows. */
|
|
37
|
+
export const titledMapNames = (titles) => [...titles.matchAll(/\/([^/\t\n]+?\.SC2Map)/gi)].map((match) => match[1]);
|
|
38
|
+
const BANKS = path.join(os.homedir(), "Library/Application Support/Blizzard/StarCraft II/Banks");
|
|
39
|
+
/** A bank file's int or fixed value for a key, as the game writes it (`<Key name="..."><Value int="..."/>`). */
|
|
40
|
+
export function bankValue(bank, key, kind) {
|
|
41
|
+
const match = new RegExp(`name="${key}"[^\\n]*\\n[^\\n]*${kind}="([-0-9.]*)"`).exec(bank);
|
|
42
|
+
return match?.[1];
|
|
43
|
+
}
|
|
44
|
+
/** Every window of the processes whose owner name contains argv[0]: owner, layer, id, size, title, tab-separated. */
|
|
45
|
+
const WINDOW_LIST = `
|
|
46
|
+
ObjC.import('CoreGraphics');
|
|
47
|
+
ObjC.import('Foundation');
|
|
48
|
+
function run(argv) {
|
|
49
|
+
const arr = ObjC.castRefToObject($.CGWindowListCopyWindowInfo($.kCGWindowListOptionAll, 0));
|
|
50
|
+
const out = [];
|
|
51
|
+
for (let i = 0; i < arr.count; i++) {
|
|
52
|
+
const w = ObjC.deepUnwrap(arr.objectAtIndex(i));
|
|
53
|
+
if ((w.kCGWindowOwnerName || '').includes(argv[0]))
|
|
54
|
+
out.push(\`\${w.kCGWindowOwnerName}\\tL\${w.kCGWindowLayer}\\t\${w.kCGWindowNumber}\\t\${w.kCGWindowBounds.Width}x\${w.kCGWindowBounds.Height}\\t\${w.kCGWindowName || ''}\`);
|
|
55
|
+
}
|
|
56
|
+
return out.join('\\n');
|
|
57
|
+
}`;
|
|
58
|
+
/** The Editor's window titles as Accessibility sees them, one per line. */
|
|
59
|
+
const AX_WINDOWS = `
|
|
60
|
+
tell application "System Events"
|
|
61
|
+
if not (exists process "${EDITOR}") then return ""
|
|
62
|
+
tell process "${EDITOR}"
|
|
63
|
+
set out to ""
|
|
64
|
+
repeat with w in windows
|
|
65
|
+
try
|
|
66
|
+
set out to out & (name of w) & linefeed
|
|
67
|
+
end try
|
|
68
|
+
end repeat
|
|
69
|
+
return out
|
|
70
|
+
end tell
|
|
71
|
+
end tell`;
|
|
72
|
+
/**
|
|
73
|
+
* Makes the document whose window titles contain argv[1] the Editor's active one, then clicks
|
|
74
|
+
* argv[2] > argv[3], trying for argv[4] seconds. Menu commands act on the active document and work
|
|
75
|
+
* from any Editor window showing it; Test Document does nothing while an Activity window is open.
|
|
76
|
+
* Prefers a window that isn't minimized, restores a minimized one only when it's the only choice,
|
|
77
|
+
* and then says "restored". Never acts on another document.
|
|
78
|
+
*/
|
|
79
|
+
/** How often a capture tries again to bring the Editor forward while waiting for the author. */
|
|
80
|
+
const RAISE_RETRY_MS = 30_000;
|
|
81
|
+
/** Prints "granted" or "denied": whether this process may read other apps' windows (Screen Recording). */
|
|
82
|
+
const SCREEN_ACCESS_SWIFT = `import CoreGraphics
|
|
83
|
+
print(CGPreflightScreenCaptureAccess() ? "granted" : "denied")
|
|
84
|
+
`;
|
|
85
|
+
const MENU_CLICK = `
|
|
86
|
+
on run argv
|
|
87
|
+
set fragment to item 1 of argv
|
|
88
|
+
set m to item 2 of argv
|
|
89
|
+
set i to item 3 of argv
|
|
90
|
+
set tries to (item 4 of argv) as integer
|
|
91
|
+
set restored to false
|
|
92
|
+
tell application "System Events" to tell process "${EDITOR}"
|
|
93
|
+
repeat tries times
|
|
94
|
+
set loading to false
|
|
95
|
+
set target to missing value
|
|
96
|
+
set fallback to missing value
|
|
97
|
+
repeat with w in windows
|
|
98
|
+
try
|
|
99
|
+
set n to name of w
|
|
100
|
+
if n starts with "Activity - " then set loading to true
|
|
101
|
+
if n contains fragment then
|
|
102
|
+
if value of attribute "AXMinimized" of w is false then
|
|
103
|
+
set target to w
|
|
104
|
+
else
|
|
105
|
+
set fallback to w
|
|
106
|
+
end if
|
|
107
|
+
end if
|
|
108
|
+
end try
|
|
109
|
+
end repeat
|
|
110
|
+
if not loading and (target is not missing value or fallback is not missing value) then
|
|
111
|
+
if target is missing value then
|
|
112
|
+
set target to fallback
|
|
113
|
+
set value of attribute "AXMinimized" of target to false
|
|
114
|
+
set restored to true
|
|
115
|
+
delay 1
|
|
116
|
+
end if
|
|
117
|
+
perform action "AXRaise" of target
|
|
118
|
+
set value of attribute "AXFrontmost" to true
|
|
119
|
+
delay 0.8
|
|
120
|
+
if (name of window 1) contains fragment then
|
|
121
|
+
click menu item i of menu 1 of menu bar item m of menu bar 1
|
|
122
|
+
if restored then return "clicked restored"
|
|
123
|
+
return "clicked"
|
|
124
|
+
end if
|
|
125
|
+
end if
|
|
126
|
+
delay 1
|
|
127
|
+
end repeat
|
|
128
|
+
end tell
|
|
129
|
+
error "could not make the capture copy active (still loading, or no window shows it)"
|
|
130
|
+
end run`;
|
|
131
|
+
/** Dismisses script-error and OK dialogs; says whether a window still shows a capture copy. */
|
|
132
|
+
const CLOSE_PREPARE = `
|
|
133
|
+
on run argv
|
|
134
|
+
set fragment to item 1 of argv
|
|
135
|
+
tell application "System Events" to tell process "${EDITOR}"
|
|
136
|
+
try
|
|
137
|
+
click button 1 of window "Script Compile Errors"
|
|
138
|
+
end try
|
|
139
|
+
repeat with w in windows
|
|
140
|
+
try
|
|
141
|
+
if exists button "OK" of w then click button "OK" of w
|
|
142
|
+
end try
|
|
143
|
+
end repeat
|
|
144
|
+
repeat with w in windows
|
|
145
|
+
try
|
|
146
|
+
if (name of w) contains fragment then return "open"
|
|
147
|
+
end try
|
|
148
|
+
end repeat
|
|
149
|
+
end tell
|
|
150
|
+
return "nothing to close"
|
|
151
|
+
end run`;
|
|
152
|
+
/** Answers a save prompt: Don't Save for a capture copy, Cancel for any other document. */
|
|
153
|
+
const ANSWER_SAVE = `
|
|
154
|
+
on run argv
|
|
155
|
+
set fragment to item 1 of argv
|
|
156
|
+
tell application "System Events" to tell process "${EDITOR}"
|
|
157
|
+
repeat with w in windows
|
|
158
|
+
try
|
|
159
|
+
set txt to (value of every static text of w) as text
|
|
160
|
+
if txt contains "Save changes" then
|
|
161
|
+
repeat with b in buttons of w
|
|
162
|
+
if txt contains fragment and name of b starts with "Don" then
|
|
163
|
+
click b
|
|
164
|
+
return "discarded"
|
|
165
|
+
else if txt does not contain fragment and name of b is "Cancel" then
|
|
166
|
+
click b
|
|
167
|
+
return "REFUSED: prompt was for another document"
|
|
168
|
+
end if
|
|
169
|
+
end repeat
|
|
170
|
+
end if
|
|
171
|
+
end try
|
|
172
|
+
end repeat
|
|
173
|
+
end tell
|
|
174
|
+
return "closed"
|
|
175
|
+
end run`;
|
|
176
|
+
const MINIMIZE_TERRAIN = `
|
|
177
|
+
tell application "System Events" to tell process "${EDITOR}"
|
|
178
|
+
repeat with w in windows
|
|
179
|
+
try
|
|
180
|
+
if (name of w) starts with "Terrain - " then set value of attribute "AXMinimized" of w to true
|
|
181
|
+
end try
|
|
182
|
+
end repeat
|
|
183
|
+
end tell`;
|
|
184
|
+
const PRESS_SPACE = `
|
|
185
|
+
tell application "System Events" to tell process "SC2" to set value of attribute "AXFrontmost" to true
|
|
186
|
+
delay 0.3
|
|
187
|
+
tell application "System Events" to key code 49`;
|
|
188
|
+
/**
|
|
189
|
+
* dialog <owner> <must-contain> <button-text>: finds an untitled dialog window of <owner>, reads it
|
|
190
|
+
* by OCR, and clicks <button-text> only if its text contains <must-contain>.
|
|
191
|
+
*/
|
|
192
|
+
const DIALOG_SWIFT = `import CoreGraphics
|
|
193
|
+
import Foundation
|
|
194
|
+
import ImageIO
|
|
195
|
+
import Vision
|
|
196
|
+
|
|
197
|
+
let args = CommandLine.arguments
|
|
198
|
+
let owner = args[1], mustContain = args[2], buttonText = args[3]
|
|
199
|
+
let infos = CGWindowListCopyWindowInfo(.optionOnScreenOnly, kCGNullWindowID) as! [[String: Any]]
|
|
200
|
+
for info in infos {
|
|
201
|
+
guard (info[kCGWindowOwnerName as String] as? String) == owner,
|
|
202
|
+
((info[kCGWindowName as String] as? String) ?? "").isEmpty,
|
|
203
|
+
let id = info[kCGWindowNumber as String] as? CGWindowID,
|
|
204
|
+
let b = info[kCGWindowBounds as String] as? [String: CGFloat],
|
|
205
|
+
let w = b["Width"], let h = b["Height"], w > 150, h > 150, w < 900, h < 900
|
|
206
|
+
else { continue }
|
|
207
|
+
let path = NSTemporaryDirectory() + "dialog-\\(id).png"
|
|
208
|
+
let cap = Process()
|
|
209
|
+
cap.executableURL = URL(fileURLWithPath: "/usr/sbin/screencapture")
|
|
210
|
+
cap.arguments = ["-x", "-o", "-l", "\\(id)", path]
|
|
211
|
+
try? cap.run(); cap.waitUntilExit()
|
|
212
|
+
guard let src = CGImageSourceCreateWithURL(URL(fileURLWithPath: path) as CFURL, nil),
|
|
213
|
+
let img = CGImageSourceCreateImageAtIndex(src, 0, nil) else { continue }
|
|
214
|
+
let req = VNRecognizeTextRequest()
|
|
215
|
+
req.recognitionLevel = .accurate
|
|
216
|
+
try? VNImageRequestHandler(cgImage: img, options: [:]).perform([req])
|
|
217
|
+
let obs = req.results ?? []
|
|
218
|
+
let text = obs.compactMap { $0.topCandidates(1).first?.string }.joined(separator: " ")
|
|
219
|
+
let flat = text.replacingOccurrences(of: " ", with: "")
|
|
220
|
+
guard flat.contains(mustContain.replacingOccurrences(of: " ", with: "")) else {
|
|
221
|
+
print("SKIP window \\(id): \\(text)"); continue
|
|
222
|
+
}
|
|
223
|
+
guard let btn = obs.first(where: { ($0.topCandidates(1).first?.string ?? "").replacingOccurrences(of: "\\u{2019}", with: "'") == buttonText }) else {
|
|
224
|
+
print("NO BUTTON in \\(id): \\(text)"); continue
|
|
225
|
+
}
|
|
226
|
+
// Vision boxes are normalised with a bottom-left origin.
|
|
227
|
+
let p = CGPoint(x: b["X"]! + btn.boundingBox.midX * w, y: b["Y"]! + (1 - btn.boundingBox.midY) * h)
|
|
228
|
+
let source = CGEventSource(stateID: .hidSystemState)
|
|
229
|
+
for t in [CGEventType.mouseMoved, .leftMouseDown, .leftMouseUp] {
|
|
230
|
+
let e = CGEvent(mouseEventSource: source, mouseType: t, mouseCursorPosition: p, mouseButton: .left)
|
|
231
|
+
e?.setIntegerValueField(.mouseEventClickState, value: 1)
|
|
232
|
+
e?.post(tap: .cghidEventTap)
|
|
233
|
+
usleep(150_000)
|
|
234
|
+
}
|
|
235
|
+
print("CLICKED \\(buttonText) in \\(id)")
|
|
236
|
+
exit(0)
|
|
237
|
+
}
|
|
238
|
+
print("NONE")
|
|
239
|
+
`;
|
|
240
|
+
/** crop <in.jpg> <out.jpg> <quality>: cuts whatever sits above a 16:9 picture (the window's title bar). sips's --cropOffset is ignored on this macOS. */
|
|
241
|
+
const CROP_SWIFT = `import CoreGraphics
|
|
242
|
+
import Foundation
|
|
243
|
+
import ImageIO
|
|
244
|
+
import UniformTypeIdentifiers
|
|
245
|
+
|
|
246
|
+
let args = CommandLine.arguments
|
|
247
|
+
guard args.count == 5,
|
|
248
|
+
let quality = Double(args[3]),
|
|
249
|
+
let width = Int(args[4]),
|
|
250
|
+
let source = CGImageSourceCreateWithURL(URL(fileURLWithPath: args[1]) as CFURL, nil),
|
|
251
|
+
let image = CGImageSourceCreateImageAtIndex(source, 0, nil),
|
|
252
|
+
let cropped = image.cropping(to: CGRect(x: 0, y: max(0, image.height - image.width * 9 / 16), width: image.width, height: min(image.height, image.width * 9 / 16))),
|
|
253
|
+
let destination = CGImageDestinationCreateWithURL(URL(fileURLWithPath: args[2]) as CFURL, UTType.jpeg.identifier as CFString, 1, nil)
|
|
254
|
+
else {
|
|
255
|
+
FileHandle.standardError.write("usage: crop <in.png> <out.jpg> <quality 0-1> <max width>\\n".data(using: .utf8)!)
|
|
256
|
+
exit(2)
|
|
257
|
+
}
|
|
258
|
+
// Scaled so neither side is over <max width>, as sips -Z did; never enlarged.
|
|
259
|
+
let scale = min(1.0, Double(width) / Double(max(cropped.width, cropped.height)))
|
|
260
|
+
let outWidth = max(1, Int((Double(cropped.width) * scale).rounded()))
|
|
261
|
+
let outHeight = max(1, Int((Double(cropped.height) * scale).rounded()))
|
|
262
|
+
guard let context = CGContext(data: nil, width: outWidth, height: outHeight, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { exit(1) }
|
|
263
|
+
context.interpolationQuality = .high
|
|
264
|
+
context.draw(cropped, in: CGRect(x: 0, y: 0, width: outWidth, height: outHeight))
|
|
265
|
+
guard let scaled = context.makeImage() else { exit(1) }
|
|
266
|
+
CGImageDestinationAddImage(destination, scaled, [kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary)
|
|
267
|
+
exit(CGImageDestinationFinalize(destination) ? 0 : 1)
|
|
268
|
+
`;
|
|
269
|
+
/** A Swift helper, compiled once into the cache folder. */
|
|
270
|
+
async function swiftTool(context, name, source) {
|
|
271
|
+
const folder = path.join(context.requirePath("cacheDir"), "host-macos", "bin");
|
|
272
|
+
const bin = path.join(folder, name);
|
|
273
|
+
const sourceFile = `${bin}.swift`;
|
|
274
|
+
const current = existsSync(bin) && existsSync(sourceFile) && (await readFile(sourceFile, "utf8")) === source;
|
|
275
|
+
if (!current) {
|
|
276
|
+
await mkdir(folder, { recursive: true });
|
|
277
|
+
// The source is kept beside the binary only once it compiled, so a failed rebuild is tried again.
|
|
278
|
+
const draft = `${bin}.draft.swift`;
|
|
279
|
+
await writeFile(draft, source);
|
|
280
|
+
await run("swiftc", ["-O", "-o", bin, draft]);
|
|
281
|
+
await rename(draft, sourceFile);
|
|
282
|
+
}
|
|
283
|
+
return bin;
|
|
284
|
+
}
|
|
285
|
+
const osascript = async (script, args = [], language = "AppleScript") => (await run("osascript", ["-l", language, "-e", script, ...args])).stdout;
|
|
286
|
+
const quietly = async (script, args = []) => osascript(script, args).catch(() => "");
|
|
287
|
+
const windowList = (owner) => osascript(WINDOW_LIST, [owner], "JavaScript").catch(() => "");
|
|
288
|
+
export async function gameRunning() {
|
|
289
|
+
return run("pgrep", ["-f", "MacOS/SC2 "]).then(() => true, () => false);
|
|
290
|
+
}
|
|
291
|
+
async function quitGame() {
|
|
292
|
+
await run("pkill", ["-f", "MacOS/SC2 "]).catch(() => undefined);
|
|
293
|
+
await sleep(2);
|
|
294
|
+
await run("pkill", ["-9", "-f", "MacOS/SC2 "]).catch(() => undefined);
|
|
295
|
+
await sleep(1);
|
|
296
|
+
}
|
|
297
|
+
/** The game's main window id, for `screencapture -l`. */
|
|
298
|
+
async function gameWindow() {
|
|
299
|
+
for (const line of (await windowList("SC2")).split("\n")) {
|
|
300
|
+
const fields = line.split("\t");
|
|
301
|
+
if (fields[4] === "StarCraft II")
|
|
302
|
+
return fields[2];
|
|
303
|
+
}
|
|
304
|
+
return undefined;
|
|
305
|
+
}
|
|
306
|
+
/** Whether the Editor shows the map; asks Accessibility and the window server, whose titles lag behind. */
|
|
307
|
+
async function mapOpen(mapPath) {
|
|
308
|
+
const titles = (await quietly(AX_WINDOWS)) + (await windowList(EDITOR));
|
|
309
|
+
return titles.includes(captureFragment(mapPath));
|
|
310
|
+
}
|
|
311
|
+
async function closeMap(context, mapPath, log) {
|
|
312
|
+
const dialog = await swiftTool(context, "dialog", DIALOG_SWIFT);
|
|
313
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
314
|
+
if (!(await mapOpen(mapPath)))
|
|
315
|
+
return;
|
|
316
|
+
const fragment = captureFragment(mapPath);
|
|
317
|
+
if ((await quietly(CLOSE_PREPARE, [fragment])).trim() === "open") {
|
|
318
|
+
await quietly(MENU_CLICK, [fragment, "File", "Close", "90"]);
|
|
319
|
+
await sleep(1.5);
|
|
320
|
+
await quietly(ANSWER_SAVE, [fragment]);
|
|
321
|
+
}
|
|
322
|
+
await sleep(2);
|
|
323
|
+
// The prompt read by OCR, where a long path can wrap: the capture folder is enough there, since
|
|
324
|
+
// only capture copies are ever in it.
|
|
325
|
+
await run(dialog, [EDITOR, `${CAPTURE_MAPS_FOLDER}/`, "Don't Save"]).catch(() => undefined);
|
|
326
|
+
await sleep(2);
|
|
327
|
+
}
|
|
328
|
+
if (await mapOpen(mapPath))
|
|
329
|
+
log(`WARNING: ${path.basename(mapPath)} is still open in the Editor`);
|
|
330
|
+
}
|
|
331
|
+
/** An AppleScript string literal: only backslashes and double quotes need escaping. */
|
|
332
|
+
const appleString = (text) => `"${text.replace(/[\\"]/g, (c) => `\\${c}`)}"`;
|
|
333
|
+
async function notify(title, message) {
|
|
334
|
+
await quietly(`display notification ${appleString(message)} with title ${appleString(title)} sound name "Glass"`);
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* Closes, without saving, every capture copy the Editor has open (any document whose window title
|
|
338
|
+
* shows a copy in <cacheDir>/capture/maps/), quitting the game first when one is open, since that game is
|
|
339
|
+
* most likely testing it. The Editor Broker runs this as it starts and after a failed tour.
|
|
340
|
+
*/
|
|
341
|
+
export async function closeCaptureCopies(request, context) {
|
|
342
|
+
const log = request.log ?? (() => undefined);
|
|
343
|
+
const maps = path.join(context.requirePath("cacheDir"), CAPTURE_MAPS_FOLDER);
|
|
344
|
+
const titles = (await quietly(AX_WINDOWS)) + "\n" + (await windowList(EDITOR));
|
|
345
|
+
// Only this machine's capture folder: a copy under another cache's folder isn't this broker's to
|
|
346
|
+
// close. Titles shorten the path, so a title showing the full path counts, and otherwise only a
|
|
347
|
+
// name the broker made (ending in its job id) whose copy is on disk here, never an author's own
|
|
348
|
+
// map that shares a name with an old copy.
|
|
349
|
+
const names = new Set(titledMapNames(titles).filter((name) => titles.includes(path.join(maps, name)) || (BROKER_COPY_NAME.test(name) && existsSync(path.join(maps, name)))));
|
|
350
|
+
if (names.size === 0)
|
|
351
|
+
return;
|
|
352
|
+
if (await gameRunning()) {
|
|
353
|
+
log("quitting the game a capture copy left running");
|
|
354
|
+
await quitGame();
|
|
355
|
+
}
|
|
356
|
+
for (const name of names) {
|
|
357
|
+
log(`closing ${name}`);
|
|
358
|
+
await closeMap(context, path.join(maps, name), log);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
export async function captureTour(request, context) {
|
|
362
|
+
const log = request.log ?? (() => undefined);
|
|
363
|
+
// Checked at every wait and stop: a cancelled tour stops there and cleans up in the finally below.
|
|
364
|
+
const signal = request.signal;
|
|
365
|
+
const stopIfCancelled = () => {
|
|
366
|
+
if (signal?.aborted)
|
|
367
|
+
throw new Error("the capture was cancelled");
|
|
368
|
+
};
|
|
369
|
+
const waitFor = (seconds, every, check) => waitUntil(seconds, every, check, signal);
|
|
370
|
+
const maps = path.join(context.requirePath("cacheDir"), CAPTURE_MAPS_FOLDER);
|
|
371
|
+
const mapPath = path.resolve(request.mapPath);
|
|
372
|
+
if (!request.attach && path.dirname(mapPath) !== maps) {
|
|
373
|
+
throw new Error(`editor.captureTour closes its map without saving, so it only takes maps in ${maps}; ${mapPath} isn't there`);
|
|
374
|
+
}
|
|
375
|
+
// Without Screen Recording, macOS hides other apps' window titles, so the game window is never
|
|
376
|
+
// found and every stop is skipped; refuse before opening anything.
|
|
377
|
+
const access = (await run(await swiftTool(context, "screen-access", SCREEN_ACCESS_SWIFT), []).catch(() => ({ stdout: "" }))).stdout.trim();
|
|
378
|
+
if (access === "denied") {
|
|
379
|
+
throw new Error("Screen Recording isn't allowed for the app running this capture, so it can't find or capture the game window. " +
|
|
380
|
+
"Turn it on in System Settings > Privacy & Security > Screen & System Audio Recording for that app (the terminal, or T3 Code), then quit and reopen it. " +
|
|
381
|
+
"An Editor Broker it started inherits the permission, so stop a running broker too.");
|
|
382
|
+
}
|
|
383
|
+
const crop = await swiftTool(context, "crop", CROP_SWIFT);
|
|
384
|
+
const bankFile = path.join(BANKS, `${request.bank}.SC2Bank`);
|
|
385
|
+
await mkdir(request.outputDir, { recursive: true });
|
|
386
|
+
// Keep the display awake for the whole run: a sleeping or locked screen stops every capture.
|
|
387
|
+
await run("caffeinate", ["-u", "-t", "2"]).catch(() => undefined);
|
|
388
|
+
const awake = spawn("caffeinate", ["-d", "-w", String(process.pid)], { stdio: "ignore" });
|
|
389
|
+
let restoredTerrain = false;
|
|
390
|
+
// Set once this run may have opened the map or started the game; whatever ends the run then
|
|
391
|
+
// quits the game and closes the map.
|
|
392
|
+
let touchedEditor = false;
|
|
393
|
+
const shrinking = [];
|
|
394
|
+
// Attached to a game already running, the bank may still hold an earlier run's last stop (-1);
|
|
395
|
+
// that content is ignored until the game saves the bank again.
|
|
396
|
+
let leftover;
|
|
397
|
+
try {
|
|
398
|
+
stopIfCancelled();
|
|
399
|
+
if (request.attach) {
|
|
400
|
+
if (!(await gameRunning()))
|
|
401
|
+
throw new Error("no game is running to watch");
|
|
402
|
+
leftover = existsSync(bankFile) ? await readFile(bankFile, "utf8") : undefined;
|
|
403
|
+
}
|
|
404
|
+
else {
|
|
405
|
+
await rm(bankFile, { force: true });
|
|
406
|
+
await quitGame();
|
|
407
|
+
// A copy left open by an earlier run would be tested as it was: opening only brings it forward.
|
|
408
|
+
if (await mapOpen(mapPath)) {
|
|
409
|
+
log("closing a stale copy");
|
|
410
|
+
await closeMap(context, mapPath, log);
|
|
411
|
+
if (await mapOpen(mapPath))
|
|
412
|
+
throw new Error(`a stale copy of ${path.basename(mapPath)} is still open in the Editor`);
|
|
413
|
+
}
|
|
414
|
+
stopIfCancelled();
|
|
415
|
+
await request.writeMap?.();
|
|
416
|
+
touchedEditor = true;
|
|
417
|
+
await run("open", ["-g", "-a", context.requirePath("editorPath"), mapPath]);
|
|
418
|
+
const opened = await waitFor(300, 2, () => mapOpen(mapPath));
|
|
419
|
+
stopIfCancelled();
|
|
420
|
+
if (!opened) {
|
|
421
|
+
throw new Error(`the Editor never opened ${path.basename(mapPath)}`);
|
|
422
|
+
}
|
|
423
|
+
await waitFor(600, 2, async () => !(await quietly(AX_WINDOWS)).includes("Activity - "));
|
|
424
|
+
stopIfCancelled();
|
|
425
|
+
await sleep(2);
|
|
426
|
+
const clicked = await osascript(MENU_CLICK, [captureFragment(mapPath), "File", "Test Document", "15"]).catch(() => "");
|
|
427
|
+
if (clicked.includes("clicked"))
|
|
428
|
+
log("Test Document clicked");
|
|
429
|
+
restoredTerrain = clicked.includes("restored");
|
|
430
|
+
const started = await waitFor(30, 2, gameRunning);
|
|
431
|
+
stopIfCancelled();
|
|
432
|
+
if (!started) {
|
|
433
|
+
log("couldn't bring the Editor forward; trying again every 30 s, or waiting for File > Test Document (15 min)");
|
|
434
|
+
await notify("Camera tour capture", `Capture is waiting for the Editor. Stop typing for a moment, or click File > Test Document in the window for ${path.basename(mapPath)}. Capture starts by itself.`);
|
|
435
|
+
let compileErrors = false;
|
|
436
|
+
// macOS refuses to bring the Editor forward only while someone is using another app, so a
|
|
437
|
+
// later try gets through once they pause. The game takes a few seconds to appear after a
|
|
438
|
+
// click, so tries are spaced well apart and never made while it's starting.
|
|
439
|
+
let lastTry = Date.now();
|
|
440
|
+
await waitFor(900, 2, async () => {
|
|
441
|
+
compileErrors = (await windowList(EDITOR)).includes("Script Compile Errors");
|
|
442
|
+
if (compileErrors || (await gameRunning()))
|
|
443
|
+
return true;
|
|
444
|
+
if (Date.now() - lastTry >= RAISE_RETRY_MS) {
|
|
445
|
+
lastTry = Date.now();
|
|
446
|
+
const retried = await osascript(MENU_CLICK, [captureFragment(mapPath), "File", "Test Document", "2"]).catch(() => "");
|
|
447
|
+
if (retried.includes("clicked")) {
|
|
448
|
+
log("Test Document clicked");
|
|
449
|
+
restoredTerrain ||= retried.includes("restored");
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
return false;
|
|
453
|
+
});
|
|
454
|
+
stopIfCancelled();
|
|
455
|
+
if (compileErrors && !(await gameRunning())) {
|
|
456
|
+
throw new Error(`the Editor shows script compile errors for ${path.basename(mapPath)}`);
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
if (!(await gameRunning())) {
|
|
460
|
+
throw new Error("the game never started");
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
log("game started; it can sit behind other windows now (don't minimize it)");
|
|
464
|
+
let last = 0;
|
|
465
|
+
let frames = 0;
|
|
466
|
+
let idle = 0;
|
|
467
|
+
let warnedNoWindow = false;
|
|
468
|
+
let end = "never started";
|
|
469
|
+
for (;;) {
|
|
470
|
+
await sleep(0.5);
|
|
471
|
+
stopIfCancelled();
|
|
472
|
+
if (!(await gameRunning())) {
|
|
473
|
+
log(`game exited at stop ${last}`);
|
|
474
|
+
end = "game exited";
|
|
475
|
+
break;
|
|
476
|
+
}
|
|
477
|
+
const bank = existsSync(bankFile) ? await readFile(bankFile, "utf8") : "";
|
|
478
|
+
if (leftover !== undefined && bank !== leftover)
|
|
479
|
+
leftover = undefined;
|
|
480
|
+
const stop = leftover === undefined ? bankValue(bank, "stop", "int") : undefined;
|
|
481
|
+
if (stop === undefined) {
|
|
482
|
+
idle++;
|
|
483
|
+
if (idle >= request.pressSpaceAfterSeconds * 2 && idle % 20 === 0) {
|
|
484
|
+
log("no stop yet; pressing Space in the game (takes focus)");
|
|
485
|
+
await quietly(PRESS_SPACE);
|
|
486
|
+
}
|
|
487
|
+
if (idle > request.startSeconds * 2) {
|
|
488
|
+
log("the tour never started");
|
|
489
|
+
break;
|
|
490
|
+
}
|
|
491
|
+
continue;
|
|
492
|
+
}
|
|
493
|
+
if (stop === "-1") {
|
|
494
|
+
end = "done";
|
|
495
|
+
log(`tour done (${frames} stops)`);
|
|
496
|
+
break;
|
|
497
|
+
}
|
|
498
|
+
if (Number(stop) === last)
|
|
499
|
+
continue;
|
|
500
|
+
const window = await gameWindow();
|
|
501
|
+
if (!window) {
|
|
502
|
+
if (!warnedNoWindow)
|
|
503
|
+
log(`stop ${stop}: no game window to capture`);
|
|
504
|
+
warnedNoWindow = true;
|
|
505
|
+
continue;
|
|
506
|
+
}
|
|
507
|
+
const frame = path.join(request.outputDir, `${stop.padStart(request.frameDigits, "0")}.jpg`);
|
|
508
|
+
// Captured losslessly, then cropped, scaled and encoded as JPEG once.
|
|
509
|
+
const raw = `${frame}.capture.png`;
|
|
510
|
+
try {
|
|
511
|
+
await run("screencapture", ["-x", "-o", "-t", "png", "-l", window, raw]);
|
|
512
|
+
}
|
|
513
|
+
catch {
|
|
514
|
+
continue;
|
|
515
|
+
}
|
|
516
|
+
last = Number(stop);
|
|
517
|
+
frames++;
|
|
518
|
+
log(`stop ${stop}`);
|
|
519
|
+
if (request.recordKeys) {
|
|
520
|
+
await appendFile(path.join(request.outputDir, "stops.txt"), `${[stop, ...request.recordKeys.map((key) => bankValue(bank, key, "fixed") ?? "")].join(" ")}\n`);
|
|
521
|
+
}
|
|
522
|
+
// The window's title bar cut off the top, down to the asked width, in one encode.
|
|
523
|
+
shrinking.push(run(crop, [raw, frame, String(request.quality / 100), String(request.width)])
|
|
524
|
+
.catch(() => undefined)
|
|
525
|
+
.finally(() => rm(raw, { force: true })));
|
|
526
|
+
}
|
|
527
|
+
return { frames, end };
|
|
528
|
+
}
|
|
529
|
+
finally {
|
|
530
|
+
await Promise.all(shrinking);
|
|
531
|
+
if (touchedEditor) {
|
|
532
|
+
await quitGame();
|
|
533
|
+
await closeMap(context, mapPath, log).catch((error) => log(`couldn't close ${path.basename(mapPath)}: ${error.message}`));
|
|
534
|
+
if (restoredTerrain)
|
|
535
|
+
await quietly(MINIMIZE_TERRAIN);
|
|
536
|
+
}
|
|
537
|
+
awake.kill();
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
/** Polls `check` every `every` seconds for up to `seconds`; whether it came true. Gives up, false, once `signal` is aborted. */
|
|
541
|
+
async function waitUntil(seconds, every, check, signal) {
|
|
542
|
+
for (let waited = 0; waited < seconds; waited += every) {
|
|
543
|
+
if (signal?.aborted)
|
|
544
|
+
return false;
|
|
545
|
+
if (await check())
|
|
546
|
+
return true;
|
|
547
|
+
await sleep(every);
|
|
548
|
+
}
|
|
549
|
+
return !signal?.aborted && check();
|
|
550
|
+
}
|
|
551
|
+
/** Captures the game window, else the Editor's frontmost window, as JPEG or PNG by the path's extension. */
|
|
552
|
+
export async function captureScreen({ outputPath }) {
|
|
553
|
+
const editor = (await windowList(EDITOR))
|
|
554
|
+
.split("\n")
|
|
555
|
+
.map((line) => line.split("\t"))
|
|
556
|
+
.find((fields) => fields[1] === "L0" && fields[4]);
|
|
557
|
+
const window = (await gameWindow()) ?? editor?.[2];
|
|
558
|
+
if (!window)
|
|
559
|
+
throw new Error("neither the game nor the Editor has a window to capture");
|
|
560
|
+
const format = path.extname(outputPath).toLowerCase() === ".png" ? "png" : "jpg";
|
|
561
|
+
await run("screencapture", ["-x", "-o", "-t", format, "-l", window, outputPath]);
|
|
562
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
// The macOS Host Adapter, a first-party Plugin package (#96) that core loads as bundled:host-macos: what an author's Mac can
|
|
2
|
+
// do with StarCraft II. It opens Map Packages in the Galaxy Editor, runs Test Document through the
|
|
3
|
+
// Editor's menu, saves a copy of a map there (the MapScript drift test), speaks placeholder voice lines with `say`, captures camera tours and the screen
|
|
4
|
+
// (capture-tour.ts), and renders and exports game models with WhiteoutFlakes (whiteoutflakes.ts).
|
|
5
|
+
// Every path comes from the machine config (`editorPath`, `cacheDir`, `modelViewerPath`); nothing
|
|
6
|
+
// about the machine is built in. It has no game.launch: the game can't be started without the Editor.
|
|
7
|
+
//
|
|
8
|
+
// Editor facts it relies on (docs/macos-host.md and the repo's docs/reference/game-testing.md have the rest):
|
|
9
|
+
// - The game can't be launched directly on the Mac; only the Editor's Test Document starts it.
|
|
10
|
+
// - An unpacked Map Package opens through its ComponentList.SC2Components file, not the folder.
|
|
11
|
+
// - Opening a map that is already open only brings it forward, still as it was loaded.
|
|
12
|
+
// - Menus exist only while the Editor is frontmost, and macOS refuses to bring it forward from the
|
|
13
|
+
// background while someone is using another app. Then Test Document fails here, and the tool
|
|
14
|
+
// hands that click to the author.
|
|
15
|
+
// - Test Document does nothing while the map is still loading (an "Activity - " window is open).
|
|
16
|
+
// The automation needs Accessibility permission for the app that runs the MCP server.
|
|
17
|
+
import { execFile } from "node:child_process";
|
|
18
|
+
import { mkdtemp, rm, stat, writeFile } from "node:fs/promises";
|
|
19
|
+
import { tmpdir } from "node:os";
|
|
20
|
+
import path from "node:path";
|
|
21
|
+
import { promisify } from "node:util";
|
|
22
|
+
import { fragmentFor, refusalFor, windowState } from "./refresh.js";
|
|
23
|
+
import { captureScreen, captureTour, closeCaptureCopies, gameRunning } from "./capture-tour.js";
|
|
24
|
+
import { exportModel, exportModelGltf, rendererKey, renderModel } from "./whiteoutflakes.js";
|
|
25
|
+
const run = promisify(execFile);
|
|
26
|
+
/**
|
|
27
|
+
* How long to wait for the Editor to show the map and for the game to start, in seconds, when the
|
|
28
|
+
* caller gives no budget of its own. Together they stay under an MCP client's usual 60 s request
|
|
29
|
+
* timeout; a slower load fails here, and the tool hands the click to the author while the Editor
|
|
30
|
+
* keeps loading. A caller's budget (`seconds`) is split the same way.
|
|
31
|
+
*/
|
|
32
|
+
const EDITOR_LOAD_SECONDS = 35;
|
|
33
|
+
const GAME_START_SECONDS = 15;
|
|
34
|
+
async function openInEditor({ mapPath }, context) {
|
|
35
|
+
const editor = context.requirePath("editorPath");
|
|
36
|
+
await run("open", ["-a", editor, path.join(mapPath, "ComponentList.SC2Components")]);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Clicks <menu> > <item> in the Editor window showing a map whose title contains <fragment>,
|
|
40
|
+
* waiting up to <tries> seconds for the map to finish loading. Never acts on another document.
|
|
41
|
+
*/
|
|
42
|
+
const CLICK_MENU = `
|
|
43
|
+
on run argv
|
|
44
|
+
set fragment to item 1 of argv
|
|
45
|
+
set m to item 2 of argv
|
|
46
|
+
set i to item 3 of argv
|
|
47
|
+
set tries to (item 4 of argv) as integer
|
|
48
|
+
tell application "System Events" to tell process "StarCraft II Editor"
|
|
49
|
+
repeat tries times
|
|
50
|
+
set loading to false
|
|
51
|
+
set target to missing value
|
|
52
|
+
repeat with w in windows
|
|
53
|
+
try
|
|
54
|
+
set n to name of w
|
|
55
|
+
if n starts with "Activity - " then set loading to true
|
|
56
|
+
if n contains fragment and value of attribute "AXMinimized" of w is false then set target to w
|
|
57
|
+
end try
|
|
58
|
+
end repeat
|
|
59
|
+
if not loading and target is not missing value then
|
|
60
|
+
perform action "AXRaise" of target
|
|
61
|
+
set value of attribute "AXFrontmost" to true
|
|
62
|
+
delay 0.8
|
|
63
|
+
if (name of window 1) contains fragment then
|
|
64
|
+
click menu item i of menu 1 of menu bar item m of menu bar 1
|
|
65
|
+
return "clicked"
|
|
66
|
+
end if
|
|
67
|
+
end if
|
|
68
|
+
delay 1
|
|
69
|
+
end repeat
|
|
70
|
+
end tell
|
|
71
|
+
error "the Editor never showed the map ready to test, or couldn't be brought forward (macOS refuses while another app is in use)"
|
|
72
|
+
end run
|
|
73
|
+
`;
|
|
74
|
+
/** The Editor's window titles, one per line; nothing when the Editor isn't running. */
|
|
75
|
+
const WINDOW_NAMES = `
|
|
76
|
+
tell application "System Events"
|
|
77
|
+
if not (exists process "StarCraft II Editor") then return ""
|
|
78
|
+
set AppleScript's text item delimiters to linefeed
|
|
79
|
+
return (name of windows of process "StarCraft II Editor") as text
|
|
80
|
+
end tell
|
|
81
|
+
`;
|
|
82
|
+
/**
|
|
83
|
+
* What a window title holds for this Map Package: its whole path, so another worktree's copy of
|
|
84
|
+
* the same Mission (same folder name) isn't taken for it.
|
|
85
|
+
*/
|
|
86
|
+
const titleFragment = (mapPath) => path.resolve(mapPath);
|
|
87
|
+
/** Whether the Editor has a window on this Map Package. */
|
|
88
|
+
async function editorHasOpen(mapPath) {
|
|
89
|
+
// By windowState, so a long path the Editor shortened (`/.../tail`) still counts as open; a title naming only the map's name counts too, as it can't be ruled out.
|
|
90
|
+
return windowState(await editorWindowTitles(), mapPath).state !== "none";
|
|
91
|
+
}
|
|
92
|
+
async function checkClosed({ mapPath }) {
|
|
93
|
+
if (await editorHasOpen(mapPath)) {
|
|
94
|
+
throw new Error(`the Editor has ${path.basename(mapPath)} open; close it there without saving first, since rewriting a map the Editor has open can crash it`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
async function testDocument(request, context) {
|
|
98
|
+
const fragment = titleFragment(request.mapPath);
|
|
99
|
+
if (await editorHasOpen(request.mapPath)) {
|
|
100
|
+
// Opening it again would only bring forward the copy the Editor loaded before this compile.
|
|
101
|
+
throw new Error(`the Editor already has ${path.basename(request.mapPath)} open, as it was before this compile; close it there without saving, then test again`);
|
|
102
|
+
}
|
|
103
|
+
const total = request.seconds ?? EDITOR_LOAD_SECONDS + GAME_START_SECONDS;
|
|
104
|
+
const gameStart = Math.max(1, Math.round((total * GAME_START_SECONDS) / (EDITOR_LOAD_SECONDS + GAME_START_SECONDS)));
|
|
105
|
+
const load = Math.max(1, Math.floor(total - gameStart));
|
|
106
|
+
await openInEditor(request, context);
|
|
107
|
+
const before = await gamePids();
|
|
108
|
+
try {
|
|
109
|
+
await run("osascript", ["-e", CLICK_MENU, fragment, "File", "Test Document", String(load)]);
|
|
110
|
+
}
|
|
111
|
+
catch (error) {
|
|
112
|
+
const stderr = error.stderr?.trim();
|
|
113
|
+
throw new Error(`couldn't click File > Test Document in the Editor: ${stderr || error.message}`, { cause: error });
|
|
114
|
+
}
|
|
115
|
+
for (let second = 0; second < gameStart; second++) {
|
|
116
|
+
if ((await gamePids()).some((pid) => !before.includes(pid)))
|
|
117
|
+
return;
|
|
118
|
+
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
119
|
+
}
|
|
120
|
+
throw new Error(`clicked File > Test Document, but no new game started within ${gameStart} s; the Editor may be showing script errors`);
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Opens the Map Package, clicks File > Save once it has loaded, waits for the Editor to rewrite
|
|
124
|
+
* MapScript.galaxy, then clicks File > Close (nothing is left unsaved, so there is no prompt). Only
|
|
125
|
+
* for a copy made for the purpose: the save rewrites the package.
|
|
126
|
+
*/
|
|
127
|
+
async function saveInEditor(request, context) {
|
|
128
|
+
const fragment = titleFragment(request.mapPath);
|
|
129
|
+
if (await editorHasOpen(request.mapPath)) {
|
|
130
|
+
throw new Error(`the Editor already has ${path.basename(request.mapPath)} open; close it there without saving, then run this again`);
|
|
131
|
+
}
|
|
132
|
+
const script = path.join(request.mapPath, "MapScript.galaxy");
|
|
133
|
+
const before = await stat(script).then((info) => info.mtimeMs, () => 0);
|
|
134
|
+
const total = request.seconds ?? EDITOR_LOAD_SECONDS + GAME_START_SECONDS;
|
|
135
|
+
await openInEditor(request, context);
|
|
136
|
+
let saved = false;
|
|
137
|
+
try {
|
|
138
|
+
try {
|
|
139
|
+
await run("osascript", ["-e", CLICK_MENU, fragment, "File", "Save", String(Math.max(1, total - 10))]);
|
|
140
|
+
}
|
|
141
|
+
catch (error) {
|
|
142
|
+
const stderr = error.stderr?.trim();
|
|
143
|
+
throw new Error(`couldn't click File > Save in the Editor: ${stderr || error.message}`, { cause: error });
|
|
144
|
+
}
|
|
145
|
+
for (let second = 0;; second++) {
|
|
146
|
+
const now = await stat(script).then((info) => info.mtimeMs, () => 0);
|
|
147
|
+
if (now > before)
|
|
148
|
+
break;
|
|
149
|
+
if (second >= 10)
|
|
150
|
+
throw new Error(`clicked File > Save, but the Editor didn't rewrite ${script} within 10 s`);
|
|
151
|
+
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
152
|
+
}
|
|
153
|
+
saved = true;
|
|
154
|
+
}
|
|
155
|
+
finally {
|
|
156
|
+
// Closed even when the save failed, so the next run doesn't find the copy open. A failed close
|
|
157
|
+
// after a failed save leaves the save's error to report.
|
|
158
|
+
await run("osascript", ["-e", CLICK_MENU, fragment, "File", "Close", "10"]).catch((error) => {
|
|
159
|
+
if (saved)
|
|
160
|
+
throw error;
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
/** The Editor's window titles, one string each. */
|
|
165
|
+
async function editorWindowTitles() {
|
|
166
|
+
const { stdout } = await run("osascript", ["-e", WINDOW_NAMES]);
|
|
167
|
+
return stdout.split("\n").filter(Boolean);
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Closes the author's map from File > Close so a compile can rewrite its package and the caller
|
|
171
|
+
* reopen it (#739). It reads the Editor's window titles first and refuses, closing nothing, when
|
|
172
|
+
* the title shows unsaved changes (`*`) or it can't tell the map from another copy; and when the
|
|
173
|
+
* Editor can't be brought forward for its menu (macOS refuses while the author uses another app),
|
|
174
|
+
* CLICK_MENU fails and nothing is clicked. It never answers a save prompt: if one appears, the map
|
|
175
|
+
* stays open and the author answers it. A map the Editor doesn't have open is left as it is.
|
|
176
|
+
* Needs an Editor check: nothing here has been run against the real Editor.
|
|
177
|
+
*/
|
|
178
|
+
async function refreshEditor({ mapPath }) {
|
|
179
|
+
const state = windowState(await editorWindowTitles(), mapPath);
|
|
180
|
+
const refusal = refusalFor(state, mapPath);
|
|
181
|
+
if (refusal)
|
|
182
|
+
throw new Error(refusal);
|
|
183
|
+
if (state.state === "none")
|
|
184
|
+
return;
|
|
185
|
+
try {
|
|
186
|
+
const shown = state.state === "clean" ? state.titles[0] : "";
|
|
187
|
+
await run("osascript", ["-e", CLICK_MENU, fragmentFor(shown, mapPath), "File", "Close", "10"]);
|
|
188
|
+
}
|
|
189
|
+
catch (error) {
|
|
190
|
+
const stderr = error.stderr?.trim();
|
|
191
|
+
throw new Error(`couldn't click File > Close in the Editor, so ${path.basename(mapPath)} is still open: ${stderr || error.message}`, { cause: error });
|
|
192
|
+
}
|
|
193
|
+
for (let second = 0; second < 5; second++) {
|
|
194
|
+
if (!(await editorHasOpen(mapPath)))
|
|
195
|
+
return;
|
|
196
|
+
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
197
|
+
}
|
|
198
|
+
throw new Error(`clicked File > Close, but the Editor still has ${path.basename(mapPath)} open; a save prompt may be showing, so answer it yourself (Don't Save keeps what is on disk)`);
|
|
199
|
+
}
|
|
200
|
+
/** The ids of the running game processes. */
|
|
201
|
+
async function gamePids() {
|
|
202
|
+
try {
|
|
203
|
+
const { stdout } = await run("pgrep", ["-f", "MacOS/SC2 "]);
|
|
204
|
+
return stdout.split("\n").filter(Boolean);
|
|
205
|
+
}
|
|
206
|
+
catch {
|
|
207
|
+
return [];
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
/** `say` into AIFF, then `afconvert` to 16-bit mono WAV at 22050 Hz, which SC2 plays. */
|
|
211
|
+
async function speak({ text, voice, outputPath }) {
|
|
212
|
+
const work = await mkdtemp(path.join(tmpdir(), "sc2-adjutant-tts-"));
|
|
213
|
+
try {
|
|
214
|
+
const textFile = path.join(work, "line.txt");
|
|
215
|
+
const aiff = path.join(work, "line.aiff");
|
|
216
|
+
await writeFile(textFile, text);
|
|
217
|
+
await run("say", [...(voice ? ["-v", voice] : []), "-o", aiff, "-f", textFile]);
|
|
218
|
+
await run("afconvert", ["-f", "WAVE", "-d", "LEI16@22050", "-c", "1", aiff, outputPath]);
|
|
219
|
+
}
|
|
220
|
+
finally {
|
|
221
|
+
await rm(work, { recursive: true, force: true });
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
const plugin = {
|
|
225
|
+
capabilities: {
|
|
226
|
+
"editor.open": openInEditor,
|
|
227
|
+
"editor.checkClosed": checkClosed,
|
|
228
|
+
"editor.refresh": refreshEditor,
|
|
229
|
+
"editor.testDocument": testDocument,
|
|
230
|
+
"editor.save": saveInEditor,
|
|
231
|
+
"editor.captureTour": captureTour,
|
|
232
|
+
"editor.closeCaptureCopies": closeCaptureCopies,
|
|
233
|
+
"game.running": gameRunning,
|
|
234
|
+
"screen.capture": captureScreen,
|
|
235
|
+
"tts.speak": speak,
|
|
236
|
+
"model.render": renderModel,
|
|
237
|
+
"model.rendererKey": rendererKey,
|
|
238
|
+
"model.export": exportModel,
|
|
239
|
+
"model.exportGltf": exportModelGltf,
|
|
240
|
+
},
|
|
241
|
+
};
|
|
242
|
+
export default plugin;
|
package/dist/refresh.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// What the Editor's window titles say about one Map Package, for editor.refresh (#739). Pure, so it
|
|
2
|
+
// is tested without the Editor. A document window's title reads `<Module> - [<path>] - StarCraft II
|
|
3
|
+
// Editor`, and the author saw (2026-11-21, Data module) a `*` before the closing bracket while the
|
|
4
|
+
// document has unsaved changes: `... /Name.SC2Map/*] - StarCraft II Editor`. Not yet confirmed
|
|
5
|
+
// for every module or for a long path: needs an Editor check.
|
|
6
|
+
// macOS paths, read the same wherever the tests run.
|
|
7
|
+
import { posix as path } from "node:path";
|
|
8
|
+
/** The text between a title's `[` and the `]` that ends it, or undefined for a title without one. */
|
|
9
|
+
function bracketed(title) {
|
|
10
|
+
const open = title.indexOf("[");
|
|
11
|
+
const close = title.lastIndexOf("]");
|
|
12
|
+
return open >= 0 && close > open ? title.slice(open + 1, close) : undefined;
|
|
13
|
+
}
|
|
14
|
+
/** Whether a title's bracketed path ends in `*`, the Editor's mark for unsaved changes. */
|
|
15
|
+
export const showsUnsaved = (title) => bracketed(title)?.endsWith("*") ?? false;
|
|
16
|
+
/** What a title's bracketed path says of a map: its whole path, a shortened path whose tail ends it, or only its name, or nothing of it. */
|
|
17
|
+
function reading(title, full) {
|
|
18
|
+
const shown = bracketed(title)?.replace(/\/\*$/, "").replace(/\/$/, "");
|
|
19
|
+
if (shown === undefined)
|
|
20
|
+
return "other";
|
|
21
|
+
if (shown.includes(full))
|
|
22
|
+
return "whole";
|
|
23
|
+
const elided = /^\/?\.\.\.\/(.+)$/.exec(shown);
|
|
24
|
+
if (elided === null)
|
|
25
|
+
return "other";
|
|
26
|
+
const tail = elided[1];
|
|
27
|
+
if (!full.endsWith(`/${tail}`))
|
|
28
|
+
return "other";
|
|
29
|
+
return tail.includes("/") ? "tail" : "name";
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Reads `titles` (every Editor window's title) for the Map Package at `mapPath`. The Editor shortens
|
|
33
|
+
* a long path to `/.../<tail>` (seen 2026-11-21: `/.../repos/my-campaign/missions/m/output/Name.SC2Map/*`),
|
|
34
|
+
* so a title belongs to the map when it holds the whole resolved path, or a shortened one whose tail,
|
|
35
|
+
* with at least a folder beside the name, ends the resolved path. Another worktree's copy shows a
|
|
36
|
+
* different tail, so it is not taken for this one; a tail that happens to be shared by two copies
|
|
37
|
+
* can't be told apart (needs an Editor check: how often that happens). A shortened title that is only
|
|
38
|
+
* the map's name (`/.../Name.SC2Map`) is `unclear`. A `*` in another map's title is not this map's,
|
|
39
|
+
* and any unsaved mark among this map's windows beats a clean one.
|
|
40
|
+
*/
|
|
41
|
+
export function windowState(titles, mapPath) {
|
|
42
|
+
const full = path.resolve(mapPath);
|
|
43
|
+
const read = titles.map((title) => ({ title, kind: reading(title, full) }));
|
|
44
|
+
const ours = read.filter((entry) => entry.kind === "whole" || entry.kind === "tail").map((entry) => entry.title);
|
|
45
|
+
const unsaved = ours.find(showsUnsaved);
|
|
46
|
+
if (unsaved !== undefined)
|
|
47
|
+
return { state: "dirty", title: unsaved };
|
|
48
|
+
const nameOnly = read.find((entry) => entry.kind === "name");
|
|
49
|
+
if (nameOnly !== undefined)
|
|
50
|
+
return { state: "unclear", title: nameOnly.title };
|
|
51
|
+
return ours.length > 0 ? { state: "clean", titles: ours } : { state: "none" };
|
|
52
|
+
}
|
|
53
|
+
/** The sentence refusing a refresh, or undefined when the document may be closed (or isn't open). */
|
|
54
|
+
export function refusalFor(result, mapPath) {
|
|
55
|
+
const name = path.basename(mapPath);
|
|
56
|
+
if (result.state === "dirty")
|
|
57
|
+
return `the Editor shows unsaved changes in ${name} (its title ends in *): not closed, so nothing of yours is lost; save or discard them in the Editor, then ask again`;
|
|
58
|
+
if (result.state === "unclear")
|
|
59
|
+
return `the Editor has a window whose shortened title ("${result.title}") may be ${name}, but it can't be told from another copy: not closed; close it in the Editor yourself`;
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* The text of a title that finds its window again: the shortened tail when the Editor shortened the
|
|
64
|
+
* path (the whole path is not in that title), else the whole resolved path. Every window of the map
|
|
65
|
+
* holds it, since the tail ends the resolved path.
|
|
66
|
+
*/
|
|
67
|
+
export function fragmentFor(title, mapPath) {
|
|
68
|
+
const full = path.resolve(mapPath);
|
|
69
|
+
const shown = bracketed(title)?.replace(/\/\*$/, "").replace(/\/$/, "");
|
|
70
|
+
const elided = shown === undefined ? null : /^\/?\.\.\.\/(.+)$/.exec(shown);
|
|
71
|
+
return elided !== null && !shown.includes(full) ? elided[1] : full;
|
|
72
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// model.render and model.export with the WhiteoutFlakes viewer (this package's scripts/build-whiteoutflakes.sh)
|
|
2
|
+
// on its Vulkan backend, through the plugin SDK's viewer driver (core's host/whiteoutflakes.ts),
|
|
3
|
+
// which has the viewer facts it relies on. The viewer comes from the machine config's
|
|
4
|
+
// `modelViewerPath`, and its per-process homes live in `cacheDir`.
|
|
5
|
+
//
|
|
6
|
+
// The viewer keeps its Vulkan pipeline cache and PSO trace in ~/Library/Caches/WhiteoutFlakes.
|
|
7
|
+
// Processes sharing them corrupt them and draw magenta, so each concurrent run gets its own HOME,
|
|
8
|
+
// kept between runs so the caches stay warm. A mod model's textures are linked beside its copy.
|
|
9
|
+
import { existsSync } from "node:fs";
|
|
10
|
+
import { mkdir, stat } from "node:fs/promises";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import { exportGltfWithViewer, exportWithViewer, renderWithViewer, viewerRendererKey, WorkerPool } from "@team-antioch/sc2-adjutant/plugin-sdk";
|
|
13
|
+
/** The viewer program, checked to exist. */
|
|
14
|
+
function viewer(context) {
|
|
15
|
+
const bin = context.requirePath("modelViewerPath");
|
|
16
|
+
if (!existsSync(bin))
|
|
17
|
+
throw new Error(`No WhiteoutFlakes viewer at ${bin} (modelViewerPath); build it with packages/plugin-host-macos/scripts/build-whiteoutflakes.sh`);
|
|
18
|
+
return bin;
|
|
19
|
+
}
|
|
20
|
+
/** Numbered viewer homes not in use, so concurrent renders never share one. */
|
|
21
|
+
const homes = new WorkerPool();
|
|
22
|
+
function withHome(context, use) {
|
|
23
|
+
return homes.use(async (index) => {
|
|
24
|
+
const home = path.join(context.requirePath("cacheDir"), "whiteoutflakes", "worker-homes", String(index));
|
|
25
|
+
await mkdir(home, { recursive: true });
|
|
26
|
+
return use(home);
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
const run = (bin, home, args) => ({ bin, env: { ...process.env, HOME: home }, args });
|
|
30
|
+
/** The viewer build (its file's modification time) and the export recipe, hashed: what makes renderModel's output what it is. */
|
|
31
|
+
export async function rendererKey({ outputs, size }, context) {
|
|
32
|
+
return viewerRendererKey((await stat(viewer(context))).mtimeMs, outputs, size);
|
|
33
|
+
}
|
|
34
|
+
export async function renderModel(request, context) {
|
|
35
|
+
const bin = viewer(context);
|
|
36
|
+
await withHome(context, (home) => renderWithViewer(request, run(bin, home, ["--backend", "vulkan"]), { workRoot: context.requirePath("cacheDir"), placement: "link" }));
|
|
37
|
+
}
|
|
38
|
+
export async function exportModel(request, context) {
|
|
39
|
+
const bin = viewer(context);
|
|
40
|
+
await withHome(context, (home) => exportWithViewer(request, run(bin, home, [])));
|
|
41
|
+
}
|
|
42
|
+
/** Writes a model, by game path or file path, as a .glb with its textures embedded: how Blender reads a model with its pictures. */
|
|
43
|
+
export async function exportModelGltf(request, context) {
|
|
44
|
+
const bin = viewer(context);
|
|
45
|
+
await withHome(context, (home) => exportGltfWithViewer(request, run(bin, home, [])));
|
|
46
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
# macOS Host
|
|
2
|
+
|
|
3
|
+
How the mapper drives the StarCraft II Editor and game on macOS: the facts behind the macOS Host Adapter, `bundled:host-macos` (`packages/plugin-host-macos/`). How to install and configure it (`machine.json`, `editorPath`, `cacheDir`, the permissions it needs) and which capabilities it has are in the package's [README](../README.md). This doc is what the adapter's code relies on, and what an author or assistant needs when doing the same by hand. The native Editor runs on Apple Silicon only through the community fix shim ([below](#the-native-editor-fix)).
|
|
4
|
+
|
|
5
|
+
## The native Editor fix
|
|
6
|
+
|
|
7
|
+
On Apple Silicon the native Editor crashes at launch with "StarCraft II has encountered an error while initializing your videocard." The community shim [Nish07/sc2-editor-macos-fix](https://github.com/Nish07/sc2-editor-macos-fix) fixes it without changing the game's files (source reviewed at `f3bd83e`). It builds an x86_64 `dylib` locally, launches the Editor with `DYLD_INSERT_LIBRARIES` through `open --env`, and patches seven bytes in memory: 3 that skip the graphics gate behind the misleading error, and 4 that send an `NSBitmapImageRep` call to a 32bpp conversion hook for object previews. It needs Rosetta 2 and `clang`.
|
|
8
|
+
|
|
9
|
+
Checked on an M1 Max under macOS Sequoia 15.6 with Editor 5.0.16 (97671): the Editor opens, saves, reopens and runs Test Document. On that build the preview hook was skipped (`signature not found - skipped`), and the Editor still works. The fix is unofficial and depends on the build: a new SC2 build may need its patch addresses found again. Install it apart from this repo, and don't commit its binaries.
|
|
10
|
+
|
|
11
|
+
## Opening a map in the Editor
|
|
12
|
+
|
|
13
|
+
Open an unpacked map by its component list, not its folder:
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
open -a "StarCraft II Editor (Fixed)" <map>.SC2Map/ComponentList.SC2Components
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Double-clicking `ComponentList.SC2Components` in Finder opens the map in the Editor too (the author, 2026-11-21).
|
|
20
|
+
|
|
21
|
+
Use the shim's launcher app (the machine config's `editorPath`), which injects the fix; the bare `StarCraft II Editor.app` crashes at launch. The running process is still named "StarCraft II Editor". Opening a map that's already open only brings it forward, still as it was loaded.
|
|
22
|
+
|
|
23
|
+
The map the author opens is the Mission's committed package, `missions/<id>/<Name>.SC2Map` in its Workspace, which `compile_map` compiles in place by default. A throwaway copy (a test Cinematic's map, an `exp-*` bisection copy) goes under the Mission's `output/`, which survives restarts. The Workspace's `.gitignore` keeps `output/` out of commits (the example Campaign's ignores `missions/*/output/`); a Workspace without that line should add it.
|
|
24
|
+
|
|
25
|
+
**Telling whether the Editor has a map open.** The adapter's `editor.checkClosed` lists the Editor's window titles through System Events (`name of windows of process "StarCraft II Editor"`; nothing when it isn't running) and takes the map as open when a title holds the package's whole resolved path, or a shortened one (`[/.../<tail>]`, as the Editor shows a long path, seen 2026-11-21) whose tail with at least a folder beside the name ends that path, so another worktree's copy of the same Mission isn't taken for it. A title that is only the map's name counts as open too, since it can't be ruled out. Before 2026-11-21 the check needed the whole path and missed a map whose title the Editor had shortened. It needs the Accessibility permission, and sees no windows while the screen is locked. When the Editor is too busy to answer (in a Test Document session, say), System Events times out (`AppleEvent timed out (-1712)`) and the check fails, so the tool refuses as if the map were open: try again once the Editor is idle. Core asks it before every tool that rewrites a package: `compile_map` (for the package it writes, so also an `outputDir` the Editor has open), `compile_cutscene`, `test_mission`, `edit_kept_objects`, `tune_kept_triggers` and `edit_kept_terrain`, which write nothing while the map is open.
|
|
26
|
+
|
|
27
|
+
**Same-file refresh (built; checked on one throwaway map, 2026-11-21).** `compile_map` with `refresh: true` closes a map the author has open, compiles, and opens the same `ComponentList.SC2Components` again, instead of refusing (#739; the idea came from comparing another project's design, no code or text used). It was run against the real Editor through the five steps below (results after them); the two gaps are marked there.
|
|
28
|
+
|
|
29
|
+
What the author saw on a throwaway map (2026-11-21, Data module), which it rests on: (1) the window title carries `*` before the closing bracket while the document has unsaved changes (`... /Name.SC2Map/*] - StarCraft II Editor`) and none when clean, and System Events sees it; (2) a closed map whose files changed on disk shows the changes when reopened by its `ComponentList.SC2Components`, with no prompt; (3) File > Close with "Don't Save" on a dirty document closes it and writes nothing.
|
|
30
|
+
|
|
31
|
+
How it works:
|
|
32
|
+
|
|
33
|
+
- *Refuse if dirty.* The adapter's `editor.refresh` reads the window titles and reads them with `windowState` (`refresh.ts`, a pure function over title strings). A title belongs to the map when it holds the package's whole resolved path, or the shortened tail the Editor shows for a long path (seen 2026-11-21: `/.../repos/my-campaign/missions/trigger-test/output/Exp-Refresh.SC2Map/*`) that ends it with at least a folder beside the name. A `*` in the bracketed path refuses with a message and closes nothing, so the author's work is never closed over, and the save prompt is never answered "Save". A shortened title that is only the map's name (`[/.../Name.SC2Map]`) is refused too, since it can't be told from another worktree's copy. Two copies that share a whole tail can't be told apart either (needs an Editor check: how often).
|
|
34
|
+
- *Close.* Otherwise it clicks File > Close in the window for that map, the same System Events click the capture-copy close uses. If the Editor can't be brought forward (macOS refuses while the author is in another app) the click fails before anything is clicked, and the tool says the map is still open: it never clicks blind. It then waits up to 5 s for the title to go; if the map is still open, a save prompt may be showing, and the author answers it (it never answers one).
|
|
35
|
+
- *Reopen.* After the compile `compile_map` calls `editor.open` on the same path, and says so in its reply. A compile that stops (Editor changes to decide, say) writes nothing, so the map is reopened as it was. If the reopen fails, the reply gives the file to open.
|
|
36
|
+
- *Which maps.* It acts only when `editor.checkClosed` says the map is open, goes through the Editor Broker like the other menu clicks, and fails at once while a capture runs. A Host Adapter without `editor.refresh` makes `refresh: true` refuse and hand the close to the author, as without it.
|
|
37
|
+
|
|
38
|
+
What the author ran, on a throwaway copy under a Mission's `output/`, with the Editor open on it by `ComponentList.SC2Components`:
|
|
39
|
+
|
|
40
|
+
1. **Clean map, `refresh: true`: passed.** The window closed with no prompt, the compile ran, and the map reopened with the compile's changes, one window, no reload prompt.
|
|
41
|
+
2. **Dirty map: passed.** It refused, naming unsaved changes (the title ended in `*`). The window stayed open with the edit intact, nothing was written to the package, and no save prompt appeared.
|
|
42
|
+
3. **Another app in front: partly checked.** The adapter did bring the Editor forward. The author's click took focus away before File > Close, so the menu lookup failed and the call refused with the map still open and nothing compiled. The case where macOS refuses to bring the Editor forward at all was not tried; the code refuses on any failed click, so it should refuse the same way (needs an Editor check).
|
|
43
|
+
4. **Map not open: passed.** A plain compile, and the Editor did not open the map.
|
|
44
|
+
5. **`*` in the other modules and with a long path: not run.** The author reports `*` shows in the Triggers and Data modules too (their report, not a recorded run). A path long enough to shorten the title to just the map's name is still untried; that is refused as unclear.
|
|
45
|
+
|
|
46
|
+
Everything above is one small map, one Editor version (not recorded), one machine.
|
|
47
|
+
|
|
48
|
+
Not known: whether File > Close can leave a save prompt on a map that was clean (the title lagging an edit by a moment); the adapter would then report the map still open and leave the prompt to the author.
|
|
49
|
+
|
|
50
|
+
**Recompiling an open map can crash the Editor.** Rewriting a map's files while the Editor has that map open sometimes crashes it, and otherwise the Editor keeps testing the copy it loaded. Before recompiling a map the author has open, ask them to close it, or tell them a reopen is coming. After a crash, reopen the map: the crash isn't the map's fault.
|
|
51
|
+
|
|
52
|
+
## Starting the game: only through Test Document
|
|
53
|
+
|
|
54
|
+
On the Mac the game can't be launched directly: a bare launch exits within seconds, and the gate is Battle.net's per-launch `BDK_LAUNCH_GUID` handshake, which isn't forged. The evidence (bare, ASLR-off, lldb and Battle.net-flag launches, and the ignored `-listen`) is in [game-testing.md §1](../../../docs/reference/game-testing.md#the-launcher-handshake-and-exit-code-47). The only automatable way to start a game is the Editor's **File > Test Document** (⌘F9), which is why the adapter has `editor.testDocument` and no `game.launch`. Test Document does nothing while the map is still loading (an "Activity - " window is open).
|
|
55
|
+
|
|
56
|
+
## When the game or the Editor won't open
|
|
57
|
+
|
|
58
|
+
Two settings outside the maps have stopped both from opening. Fix them in the files with everything closed:
|
|
59
|
+
|
|
60
|
+
- **The graphics API.** `GraphicsApi=` in `~/Library/Application Support/Blizzard/StarCraft II/Variables.txt` (CRLF line endings) is shared by the game and the Editor. Choosing the beta API in the game's options writes `OpenGL3`. It was set when the game stopped opening on Apple Silicon (alongside the startup modules below, which turned out to be the Editor's problem). The working value is `Metal`; deleting the line returns to the default. The game's graphics log (`GameLogs/<time> Graphics.txt`) says `Initialized Metal GraphicsDevice` when it's working.
|
|
61
|
+
- **The Editor's startup modules.** `#Current User\StarCraft II Editor\Preferences\StartupModules` in `~/Library/Preferences/com.blizzard.StarCraft II Editor.prefs` is a bit mask of the editors opened at launch, the value on the line after the key. `512` opens the Cutscene Editor at startup, and with it the Editor spun at full CPU and never showed a window. Delete the key and its value line to start with the Terrain Editor; the Editor rewrites the file when it quits, so do it while it's closed.
|
|
62
|
+
|
|
63
|
+
## Driving the Editor
|
|
64
|
+
|
|
65
|
+
The adapter's AppleScript and Swift helpers are in `packages/plugin-host-macos/index.ts` and `capture-tour.ts`.
|
|
66
|
+
|
|
67
|
+
- **Focus.** `activate` and `open -a` are refused from the background. Use System Events: `AXRaise` a window and set `AXFrontmost` to true. Menus (File > Test Document) exist only while the Editor is frontmost, and macOS refuses to bring it forward while someone is using another app, but not once they pause: a capture tries again every 30 seconds and meanwhile asks the author for the click. Keys posted to the Editor's process in the background (⌘F9 through `CGEventPostToPid`) do nothing, and a background Editor's menu bar has only its Apple and application menus, so there is no way to start Test Document without bringing it forward (tried 2026-11-11).
|
|
68
|
+
- **Close without saving.** File > Close, then the button whose title starts "Don" (the apostrophe in "Don’t Save" is curly). Close only documents the tool opened: the author's own maps may be open with unsaved changes. The adapter closes only capture copies under `<cacheDir>/capture/maps/`, and the author's own map only through `editor.refresh`, which refuses a title showing `*` and never answers a save prompt (see "Same-file refresh").
|
|
69
|
+
- **Shortened titles.** A document window's title shows its path shortened, and a long file name shortens it more: `Terrain - [/.../maps/<name>.SC2Map]`, with even `capture/` gone. So the adapter finds a capture copy by its file name, which ends in the broker's job id, not by its folder. The sweep for leftover copies closes a name it reads from a title only when the title shows the full path, or when the name ends in a job id and the copy is on disk in this cache's folder.
|
|
70
|
+
- **Invisible dialogs.** Save prompts are sometimes invisible to Accessibility (window count 0). Find them with `CGWindowListCopyWindowInfo`, confirm the text with Vision OCR, and click with a CGEvent.
|
|
71
|
+
- **Screen Recording.** Without it macOS hides other apps' window titles, so the game window can't be found or captured, and a tour runs to its end with no frames. The permission belongs to the app that started the process (Terminal, or T3 Code for its terminals and agents), and an Editor Broker inherits it from the app that started it. A capture checks first and refuses with the setting to change.
|
|
72
|
+
- **Awake screen.** The run needs an unlocked, awake display: once it sleeps and locks, Accessibility sees no windows and screenshots fail. The adapter keeps the display awake with `caffeinate` during a capture; start `caffeinate -d` yourself before a long unattended run of anything else. Never try to unlock the screen.
|
|
73
|
+
|
|
74
|
+
## The Editor Broker: one Editor job at a time
|
|
75
|
+
|
|
76
|
+
There is one Editor, one menu bar and one frontmost window. Two captures at once click menus on each other's maps and capture each other's windows. A Test Document during a capture starts a second game, which the capture then quits. The Editor Broker (`packages/core/src/capture/editor-broker.ts`) is the one process that runs `editor.captureTour` and the other Editor actions that click menus, one job at a time, first come first served.
|
|
77
|
+
|
|
78
|
+
- **What goes through it.** Every `editor.captureTour` run: `capture_shots` and `npm run capture-shots`, `capture-exemplars`, `capture-sets` and `capture-edit`. Nothing else opens or closes capture copies. On a machine whose Host Adapter captures, `editor.open`, `editor.refresh`, `editor.testDocument` and `editor.save` go through it too (`runEditorAction` in `editor-broker-client.ts`), so `test_mission`, `compile_cutscene` with `play`, and the MapScript drift test take their turn in the same queue. `editor.checkClosed` only reads window titles and goes straight to the host. A host that can't capture has no broker, and runs those actions directly.
|
|
79
|
+
- **`test_mission` doesn't wait.** Its whole call has to fit under the MCP client's 60 s request timeout, so its Test Document is refused at once while a capture runs or waits. The reply names the job ("The Editor is busy … capture job <id> of <map> is running, 2 more waiting") and tells the author to wait, not to click Test Document by hand. The drift test's save does wait its turn.
|
|
80
|
+
- **A test game holds the queue.** A capture starts by quitting any game it finds. So after a Test Document that started a game, the broker starts nothing else until that game quits, checking `game.running` every 5 seconds. Meanwhile its status shows the Test Document job as running with `holding: true`, the log says `holding the queue until the test game quits`, and another `test_mission` is refused ("quit it first"). A game the author started from the Editor by hand isn't held for: a capture still quits it.
|
|
81
|
+
- **Merged tours.** Waiting tour jobs on the same map with the same capture options (lighting among them) run as one tour, and the frames are split back to each job, so the game starts once for all of them.
|
|
82
|
+
- **Its socket and log.** It listens on `<cacheDir>/editor-broker.sock` (the machine config's `cacheDir`). When that path is longer than a Unix socket allows (103 bytes), it uses `$TMPDIR/sc2-adjutant-broker-<hash>.sock` instead. Its output goes to `<cacheDir>/editor-broker.log`. The first capture that finds no broker answering starts one, detached, with the same machine config. It exits after 10 minutes with no job and no client connected. The Editor stays open between jobs; only the capture copies open and close.
|
|
83
|
+
- **Capture copies.** The broker writes each job's copy under its own name, `<map> <label>-<job id>.SC2Map` in `<cacheDir>/capture/maps/`, so a stale copy is never taken for a new one. It removes the copy once the tour is done, and keeps it when the tour stopped early, to open and debug.
|
|
84
|
+
- **Reading its log.** One broker runs one job at a time, so a job's `running <id>` line always follows the previous job's `done <id>: N frames, <end>` or `failed <id>: <message>`. A `running` line in the same second as its `queued` line means the queue was empty, not that two jobs ran at once. Between those lines are the job's own progress lines, `<id>: <line>` (`Test Document clicked`, `game started`, `stop 3`, `closing a stale copy`), the same lines its client sees, so a failure like "the Editor never opened" shows what the Editor was doing before it. Brokers built before 2026-11-20 log neither `done` lines nor progress lines. An editor job logs `done <id>: <action>`, a refused one `refused <action> on <map>: busy`, and a cancelled tour `cancelled <id>`.
|
|
85
|
+
- **Status.** `npm run capture-shots -- --status` prints the broker's pid, the script it runs from (so its checkout), the running job (or merged jobs), the queue and the last error, or says no broker is running. A `capture_shots` call that outlasts its wait reports its job's place the same way.
|
|
86
|
+
- **Screen and focus.** `editor.captureTour` keeps the display awake (`caffeinate -d`) while a tour runs. When macOS won't bring the Editor forward because the author is using another app, it posts a notification asking for File > Test Document and waits up to 15 minutes for the click, and every job behind it waits too.
|
|
87
|
+
|
|
88
|
+
**After a crash.** A broker that crashed leaves its socket file, which nothing answers on. The next capture starts a new broker, which takes the socket over (one at a time, with a `.lock` folder beside it). Each broker closes, unsaved, every capture copy the Editor still has open under this `cacheDir` when it starts, quitting the game first if one is running, and again after a failed job. To stop a broker that's stuck, `kill <pid>` with the pid from the status: it removes its socket as it exits.
|
|
89
|
+
|
|
90
|
+
**Cancelling a capture.** A waiting job whose client hangs up (an agent's session ending, Ctrl-C on a CLI) is dropped from the queue. A running tour is cancelled once every client of it has hung up. It stops at its next wait or stop, quits the game, closes its copy unsaved, and the broker closes any capture copy left open, as after a failure; the log says `job <id> running; its client hung up, so it is cancelled`, then `cancelled <id>`. A merged tour runs on while any of its jobs' clients is still connected. A `capture_shots` job belongs to the MCP server, which stays connected past the call's wait, so it is cancelled with `capture_shots({ job, cancel: true })`, or by stopping a call that is waiting on it (the author stopping the task). A job the call has already returned from runs on until one of those. A cancelled tour's frames so far stay in its folder, with no `shots.json`. An editor job isn't cancelled: it is short, and it runs to its end.
|
|
91
|
+
|
|
92
|
+
**A broker from another checkout.** Every checkout and worktree on the machine shares one broker, because they share one `cacheDir` socket and one Editor. The first capture to find none running starts it, from its own checkout's build, so it may come from another session's worktree. Its first log line and its status name the script it runs from. A client from another checkout gets a progress line saying so ("The Editor Broker running (pid N) was built from …"), and its job runs on that checkout's capture code. The broker doesn't refuse that client or hand over to it: a client turned away would need a second broker, and two brokers would drive the one Editor at once. When the protocol differs, the broker refuses the job ("speaks protocol N"): protocol 2 added editor jobs, so a broker built before them refuses every client built after, until it idles out. When the capture code differs in a way that matters (a fix the job needs, or a `dist` rebuilt since the broker started, which it doesn't reload), let the broker idle out, or ask whoever is using it before you `kill <pid>`.
|
|
93
|
+
|
|
94
|
+
## Placeholder voices
|
|
95
|
+
|
|
96
|
+
`tts.speak` runs `say -o <aiff>` in the line's character's voice, then `afconvert -f WAVE -d LEI16@22050 -c 1`. `say` leaves silence at the file's end, about 0.2 s, and more for some voices (0.4-0.5 s for the Protoss voices, with their effects). Core trims each spoken placeholder to its speech before it moves the file into place (`packages/core/src/host/placeholder-voices.ts`), whatever the Host Adapter, so a Cinematic that plays its lines back to back has no gap after each.
|
|
97
|
+
|
|
98
|
+
For text with nothing to say ("...", say), `say` succeeds but writes no audio, and `afconvert` makes that a WAV whose data chunk is empty. Core takes such a file for a line it couldn't speak: it writes the line's silence instead, lists the line as silent, and doesn't speak it again until its text changes. An empty WAV must never reach ffmpeg's own Vorbis encoder, which never finishes one (see [asset-sources.md](../../../docs/reference/asset-sources.md)).
|
|
99
|
+
|
|
100
|
+
## Watching the game
|
|
101
|
+
|
|
102
|
+
- **Find the window.** Find the game window with `CGWindowListCopyWindowInfo` and `kCGWindowListOptionAll`, owner "SC2", name "StarCraft II", and capture it with `screencapture -l <id>`. With the Editor's Test Document window mode set to Windowed, a covered window still captures; a minimized one doesn't.
|
|
103
|
+
- **Loading screens.** Some maps wait on a "press space" loading screen: send Space. Pressing it takes focus, so do it only after a long wait.
|
|
104
|
+
- **Getting data out.** A map can report to the outside through `BankSave`. The bank appears at once at `~/Library/Application Support/Blizzard/StarCraft II/Banks/<name>.SC2Bank`. The `Text.txt` log stays empty. The ClientAPI on port 6119 also works ([game-testing.md §5](../../../docs/reference/game-testing.md#5-the-clientapi-http-server)).
|
|
105
|
+
|
|
106
|
+
## Rendering a mod's models
|
|
107
|
+
|
|
108
|
+
`model.render` draws with WhiteoutFlakes (`whiteoutflakes.ts`, through the plugin SDK's viewer driver, core's `src/host/whiteoutflakes.ts`, which the Windows Host Adapter shares). It reads a model and its textures straight from the game's CASC storage. Given a model by its file path, it reads each texture the model names (`Assets/Textures/x.dds`) from that path under the model's folder first, and never looks in a mod package. So when a request's `packages` hold the model (ADR-0017), the adapter copies the `.m3` into its work folder and renders the copy. Beside the copy it links just the textures the model names: it reads each material layer's image path from the `.m3`, and links that path to the file in the newest package that holds it. It also links a texture kept beside the model in its package beside the copy, where the viewer looks next. Textures the packages lack still come from the game. A render costs a few links however large the packages are, since it never links a package's other files (an asset mod can hold thousands, mostly sounds). A model whose textures can't be read, one that isn't an MD34, is copied with none. Nothing is written into the packages. Without the staging, a mod model whose textures are only in the mod draws untextured: flat grey or white, and the viewer logs nothing.
|
|
109
|
+
|
|
110
|
+
## Recording a cutscene with its sound
|
|
111
|
+
|
|
112
|
+
The built-in recorder (⌘⇧5, QuickTime) records the screen and a microphone, never the game's sound. Two ways to get the sound:
|
|
113
|
+
|
|
114
|
+
**OBS Studio (recommended).** `brew install --cask obs`. On macOS 13 and later its sources use ScreenCaptureKit, so it captures the game's audio with no virtual audio device, and the volume keys keep working.
|
|
115
|
+
|
|
116
|
+
1. On first launch, skip the auto-configuration wizard (or choose "Optimize just for recording"). Grant OBS **Screen & System Audio Recording** in System Settings > Privacy & Security when asked, then quit and reopen it.
|
|
117
|
+
2. Start the game with Test Document, with the Editor's Test Document window mode set to Windowed (see [Watching the game](#watching-the-game)).
|
|
118
|
+
3. Under Sources, **+** > **macOS Screen Capture**. Method **Window Capture**, Application **SC2**, Window **StarCraft II**. Untick "Show window shadow".
|
|
119
|
+
4. Under Sources, **+** > **macOS Audio Capture**. Method **Application Audio Capture**, Application **SC2**. Its meter in the Audio Mixer should move while the game makes sound. If two meters move in step, the screen capture is carrying the sound too: mute one, or the sound doubles.
|
|
120
|
+
5. Settings > Video: set Base and Output resolution to the game window's size so nothing is scaled. Settings > Output: Recording Format **MPEG-4 (.mp4)** or **Hybrid MP4**. Recordings go to `~/Movies` by default.
|
|
121
|
+
6. **Start Recording**, play the cutscene, **Stop Recording**. Once the scene is set up it stays, so later recordings are steps 2 and 6 only. If the game was restarted and the picture is black, open the screen capture source's properties and pick the window again.
|
|
122
|
+
|
|
123
|
+
**The built-in recorder with BlackHole.** With the free BlackHole 2ch virtual device (`brew install --cask blackhole-2ch`): in Audio MIDI Setup, **+** > Create Multi-Output Device with the speakers or headphones listed first plus BlackHole 2ch (Drift Correction on BlackHole), and choose it in System Settings > Sound > Output. Then in ⌘⇧5 > Options pick BlackHole 2ch as the microphone. The volume keys don't work while that device is the output, so set the volume in the game, and switch the output back afterwards.
|
|
124
|
+
|
|
125
|
+
For a clean take either way, hide the FPS counter and any debug overlays, and drop the game's graphics a notch if the recording stutters.
|
|
126
|
+
|
|
127
|
+
## Custom Script the Editor keeps
|
|
128
|
+
|
|
129
|
+
When writing a `CustomScript` into the Triggers XML: the Editor strips 12 characters of indent from each line, so indent accordingly; use `<InitFunc>`; `RegionPlayableMapArea` isn't available; and the timer type is `c_timeGame`. Write the same Galaxy into `MapScript.galaxy` too, since Test Document runs that file as it stands ([editor-and-engine.md](../../../docs/reference/editor-and-engine.md#test-document-and-mapscriptgalaxy)).
|
package/package.json
CHANGED
|
@@ -1,6 +1,35 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@team-antioch/sc2-adjutant-host-macos",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "The macOS Host Adapter Plugin for sc2-adjutant: opens the Galaxy Editor, runs Test Document, captures tours and the screen, speaks placeholder voices and renders game models.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/TeamAntioch/sc2-adjutant.git",
|
|
9
|
+
"directory": "packages/plugin-host-macos"
|
|
10
|
+
},
|
|
11
|
+
"type": "module",
|
|
12
|
+
"exports": {
|
|
13
|
+
"./sc2-adjutant-plugin.json": "./sc2-adjutant-plugin.json",
|
|
14
|
+
"./package.json": "./package.json"
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"dist",
|
|
18
|
+
"!dist/.tsbuildinfo",
|
|
19
|
+
"sc2-adjutant-plugin.json",
|
|
20
|
+
"docs",
|
|
21
|
+
"scripts"
|
|
22
|
+
],
|
|
23
|
+
"scripts": {
|
|
24
|
+
"build": "tsc -p tsconfig.json && node -e \"require('node:fs').writeFileSync('dist/.built', '')\"",
|
|
25
|
+
"prepack": "npm run build",
|
|
26
|
+
"lint": "tsc -p tsconfig.json --noEmit",
|
|
27
|
+
"test": "npm run build && vitest run"
|
|
28
|
+
},
|
|
29
|
+
"engines": {
|
|
30
|
+
"node": ">=22.18"
|
|
31
|
+
},
|
|
32
|
+
"peerDependencies": {
|
|
33
|
+
"@team-antioch/sc2-adjutant": "^0.1.0"
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "host-macos",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"pluginApi": 2,
|
|
5
|
+
"roles": ["host-adapter"],
|
|
6
|
+
"entry": "./dist/index.js",
|
|
7
|
+
"contributions": { "capabilities": ["editor.open", "editor.checkClosed", "editor.refresh","editor.testDocument", "editor.save", "editor.captureTour", "editor.closeCaptureCopies", "game.running", "screen.capture", "tts.speak", "model.render", "model.rendererKey", "model.export", "model.exportGltf"] }
|
|
8
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# Build the WhiteoutFlakes model viewer (github.com/FernandoS27/WhiteoutFlakes), which the macOS
|
|
3
|
+
# Host Adapter renders Asset Catalog thumbnails and exports models with (model.render,
|
|
4
|
+
# model.export). Vulkan via MoltenVK only: its Metal backend renders black on macOS 27 (see
|
|
5
|
+
# docs/reference/related-repos.md).
|
|
6
|
+
#
|
|
7
|
+
# packages/plugin-host-macos/scripts/build-whiteoutflakes.sh [dir] # default ~/.cache/sc2-adjutant/whiteoutflakes
|
|
8
|
+
#
|
|
9
|
+
# Needs Xcode (with `xcodebuild -downloadComponent MetalToolchain`), Homebrew, git and the GitHub CLI
|
|
10
|
+
# (`gh`, signed in; it downloads Slang). Re-running
|
|
11
|
+
# skips the steps that are already done. The app lands at <dir>/stage/WhiteoutFlakes.app; point the
|
|
12
|
+
# machine config's `modelViewerPath` at <dir>/stage/WhiteoutFlakes.app/Contents/MacOS/WhiteoutFlakes.
|
|
13
|
+
set -euo pipefail
|
|
14
|
+
|
|
15
|
+
DIR="${1:-$HOME/.cache/sc2-adjutant/whiteoutflakes}"
|
|
16
|
+
# Pins proven together on macOS 27.2 / Xcode 27.1 (2026-10-27). Newer Slang rejects the bundled
|
|
17
|
+
# WC3 shaders; the headers match the LunarG SDK upstream CI uses.
|
|
18
|
+
WF_COMMIT=d2756ce
|
|
19
|
+
SLANG_VERSION=2026.1.2
|
|
20
|
+
VULKAN_HEADERS_TAG=v1.4.341
|
|
21
|
+
VMA_TAG=v3.3.0
|
|
22
|
+
|
|
23
|
+
export DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer
|
|
24
|
+
if ! xcrun --sdk macosx metal -v >/dev/null 2>&1; then
|
|
25
|
+
echo "Xcode's Metal toolchain is missing; run: xcodebuild -downloadComponent MetalToolchain" >&2
|
|
26
|
+
exit 1
|
|
27
|
+
fi
|
|
28
|
+
brew list cmake ninja vulkan-loader molten-vk >/dev/null 2>&1 || brew install cmake ninja vulkan-loader molten-vk
|
|
29
|
+
|
|
30
|
+
mkdir -p "$DIR"
|
|
31
|
+
cd "$DIR"
|
|
32
|
+
|
|
33
|
+
if [[ ! -d src ]]; then
|
|
34
|
+
git clone --filter=blob:none https://github.com/FernandoS27/WhiteoutFlakes src
|
|
35
|
+
git -C src checkout -q "$WF_COMMIT"
|
|
36
|
+
git -C src submodule update --init --recursive --depth 1
|
|
37
|
+
fi
|
|
38
|
+
|
|
39
|
+
if [[ ! -x slang/bin/slangc ]]; then
|
|
40
|
+
mkdir -p slang
|
|
41
|
+
gh release download "v$SLANG_VERSION" -R shader-slang/slang -p "slang-$SLANG_VERSION-macos-aarch64.tar.gz" -O - | tar -xz -C slang
|
|
42
|
+
fi
|
|
43
|
+
|
|
44
|
+
# A minimal stand-in for the LunarG SDK: pinned headers + VMA; loader and MoltenVK from Homebrew.
|
|
45
|
+
if [[ ! -f vksdk/include/vma/vk_mem_alloc.h ]]; then
|
|
46
|
+
rm -rf vksdk vk-dl
|
|
47
|
+
git clone -q --depth 1 --branch "$VULKAN_HEADERS_TAG" https://github.com/KhronosGroup/Vulkan-Headers.git vk-dl/headers
|
|
48
|
+
git clone -q --depth 1 --branch "$VMA_TAG" https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator.git vk-dl/vma
|
|
49
|
+
mkdir -p vksdk/include/vma
|
|
50
|
+
cp -R vk-dl/headers/include/. vksdk/include/
|
|
51
|
+
cp vk-dl/vma/include/vk_mem_alloc.h vksdk/include/vma/
|
|
52
|
+
rm -rf vk-dl
|
|
53
|
+
fi
|
|
54
|
+
|
|
55
|
+
# Flags follow upstream's .github/workflows/macos-dmg.yml, except: Metal and WebGPU off; the GLFW
|
|
56
|
+
# include path (upstream only adds it through the WebGPU target); deployment target 26.0 (Xcode
|
|
57
|
+
# 27's libc++ marks floating-point std::from_chars as macOS 26+).
|
|
58
|
+
if [[ ! -f build/build.ninja ]]; then
|
|
59
|
+
cmake -S src -B build -G Ninja \
|
|
60
|
+
-DCMAKE_BUILD_TYPE=Release \
|
|
61
|
+
-DCMAKE_OSX_DEPLOYMENT_TARGET=26.0 \
|
|
62
|
+
-DCMAKE_OSX_ARCHITECTURES=arm64 \
|
|
63
|
+
-DSLANG_DIR="$DIR/slang" \
|
|
64
|
+
-DWDX_BUILD_WC3_SHADERS=OFF \
|
|
65
|
+
-DWDX_USE_PREBUILT_SHADERS=ON \
|
|
66
|
+
-DWDX_BUILD_WC3_DEBUG_SHADERS=OFF \
|
|
67
|
+
-DWDX_ENABLE_TRACY=OFF \
|
|
68
|
+
-DWDX_BUILD_MAX_PLUGIN=OFF \
|
|
69
|
+
-DWDX_ENABLE_METAL=OFF \
|
|
70
|
+
-DWDX_ENABLE_WEBGPU=OFF \
|
|
71
|
+
-DVulkan_INCLUDE_DIR="$DIR/vksdk/include" \
|
|
72
|
+
-DVulkan_LIBRARY="$(brew --prefix vulkan-loader)/lib/libvulkan.dylib" \
|
|
73
|
+
-DCMAKE_CXX_FLAGS="-I$DIR/src/externals/glfw/include"
|
|
74
|
+
fi
|
|
75
|
+
|
|
76
|
+
cmake --build build --target WhiteoutFlakesStandalone --parallel
|
|
77
|
+
# On macOS the shaders, fonts and translations are staged beside the .app; install puts them in it.
|
|
78
|
+
cmake --install build --prefix stage >/dev/null
|
|
79
|
+
|
|
80
|
+
APP="$DIR/stage/WhiteoutFlakes.app"
|
|
81
|
+
"$APP/Contents/MacOS/WhiteoutFlakes" --backend vulkan --headless-test 2>&1 | grep -E '^\[headless\] (PASS|FAIL)'
|
|
82
|
+
echo "Built $APP"
|