diff --git a/compiler/backend/emit.ts b/compiler/backend/emit.ts index 417774f..8b9fbe6 100644 --- a/compiler/backend/emit.ts +++ b/compiler/backend/emit.ts @@ -231,7 +231,7 @@ export function unlowered(s: Stmt, decls: Map, arrays: Map> = { owner: OWNER, type: TYPE, x: X, y: Y, kills: word(0x8f, 1), orderId: ORDER, cooldown: word(0x55, 1), resources: word(0xd0, 2), stim: word(0x115, 1), ensnare: word(0x116, 1), lockdown: word(0x117, 1), irradiate: word(0x118, 1), stasis: word(0x119, 1), plague: word(0x11a, 1), maelstrom: word(0x124, 1), buildTime: word(0xac, 2), rank: word(0x8e, 1), matrix: word(0x114, 1), speed: word(0x38, 4), + orderTargetX: word(0x58, 2), orderTargetY: word(0x5a, 2), }; const HP = 0x08 >> 2, SHIELDS = 0x60 >> 2, ENERGY = word(0xa2, 2), STATUS = 0xdc >> 2, USER_ACTION = word(0x93, 1); /** @@ -90,6 +92,8 @@ const ATTACKED = word(0x87, 1); const FLAG_BITS: Partial> = { invincible: 0x04000000, hallucinated: 0x40000000, burrowed: 0x10, cloaked: 0x300, speedUpgrade: 0x10000000, inTransport: 0x40 }; /** The unit an order is aimed at (a pointer, 0 for none), and the defensive matrix's hit points (a word, 256 a point) beside its timer. */ const ORDER_TARGET = 0x5c >> 2, MATRIX_HP = word(0x112, 2), MATRIX_POINTS = 250 * 256; +/** The order's state, beside the order in its dword: what `gather()` puts back to the start. */ +const ORDER_STATE = word(0x4e, 1); /** The most a field written holds, as the simulator stops it: points for hit points and shields, a byte, a word. */ const TOPS: Partial> = { hp: 0xffffff, shields: 0xffffff, energy: 255, kills: 255, cooldown: 255, resources: 0xffff, stim: 255, ensnare: 255, plague: 255, lockdown: 255, maelstrom: 255, irradiate: 255, stasis: 255, buildTime: 0xffff, rank: 255, matrix: 255 }; /** The Order action's orders. */ @@ -655,6 +659,17 @@ export function unitValues(program: Program, events?: { sources: Set [set(p, h(POINTER, 2))]), + ...when(cmp(">=", V(p), k(IN_TABLE)), [set(p, bin("-", V(p), k(DEATHS / 4)))], [set(p, k(0))]), + ])); + return { e: ranged(V(p), 0, UNIT_TABLE + STRIDE * PLACES), k: null, none: true, killed: true }; + } case "unitAt": { const ptr = plain(fix(e.ptr, pre) as NumExpr, pre); fix(e.epd, pre); @@ -767,6 +782,7 @@ export function unitValues(program: Program, events?: { sources: Set any(types.map((type) => cmp("==", ranged(V(id), 0, 0xffff), k(type)))); + body.push(dec(worker, k(0), 0xffff), dec(aimed, k(0), 0xffff), dec(order, k(0), 255), ...readInto(worker, e, TYPE)); + body.push(...when(all([is(worker, GATHER_WORKERS), alive(target)]), [ + ...readInto(aimed, target.e, TYPE), + ...GATHER_ORDERS.flatMap((g) => when(is(aimed, g.targets), [set(order, k(g.order))])), + ])); + body.push(...when(cmp(">=", ranged(V(order), 0, 255), k(1)), [ + poke(of(e, ORDER_TARGET), bin("+", bin("*", target.e, k(4)), k(DEATHS))), + poke(of(e, ORDER_STATE.dword), k(0), ORDER_STATE.mask), + poke(of(e, ORDER.dword), bin("*", ranged(V(order), 0, 255), k(256)), ORDER.mask), + ])); + break; + } case "damage": case "heal": { // Hit points down — at 0 the unit dies — or up to the type's most, in the game's own units (256 to a point). const now = fresh("hp"), ty = fresh("ty"), top = fresh("top"), step = fresh("step"); diff --git a/compiler/check.ts b/compiler/check.ts index 070328f..def0306 100644 --- a/compiler/check.ts +++ b/compiler/check.ts @@ -35,7 +35,7 @@ export function checkProgram(program: Program): { errors: ProgramDiagnostic[]; h /** Every expression of a statement list, calls' bodies included. */ function expressions(body: Stmt[], visit: (e: NumExpr | BoolExpr) => void, pick?: (u: UnitExpr & { kind: "pick" }) => void) { - const unit = (u: UnitExpr) => { if (u.kind === "call") call(u.call); else if (u.kind === "pick") pick?.(u); else if (u.kind === "unitAt") { expr(u.ptr); expr(u.epd); expr(u.uid); } }; + const unit = (u: UnitExpr): void => { if (u.kind === "call") call(u.call); else if (u.kind === "pick") pick?.(u); else if (u.kind === "unitAt") { expr(u.ptr); expr(u.epd); expr(u.uid); } else if (u.kind === "unitOrderTarget") unit(u.unit); }; const any = (e: NumExpr | BoolExpr | UnitExpr | TextExpr) => (isTextExpr(e) ? text(e) : isUnitExpr(e) ? unit(e) : expr(e)); const looks: TextMap = { num: (e) => { expr(e); return e; }, bool: (e) => { expr(e); return e; }, call: (c) => { call(c); return c; } }; const text = (t: TextExpr) => { mapText(t, looks); }; @@ -76,7 +76,7 @@ function expressions(body: Stmt[], visit: (e: NumExpr | BoolExpr) => void, pick? case "textLoop": text(s.of); s.body.forEach(stmt); break; case "unitLoop": s.body.forEach(stmt); break; case "unitWrite": unit(s.unit); expr(s.value); break; - case "unitDo": unit(s.unit); if (s.verb.do === "damage" || s.verb.do === "heal") expr(s.verb.amount); break; + case "unitDo": unit(s.unit); if (s.verb.do === "damage" || s.verb.do === "heal") expr(s.verb.amount); if (s.verb.do === "gather") unit(s.verb.target); break; case "select": s.units.forEach(unit); break; case "tableWrite": any(s.value); break; case "if": expr(s.cond); s.then.forEach(stmt); s.else?.forEach(stmt); break; @@ -280,6 +280,12 @@ const THE_GAME = "(the game)"; let WINDOWS = new Map(); const whole = (array: string): string => WINDOWS.get(array) ?? array; +/** The unit variable a unit is read through, and `THE_GAME` when it is the unit another one's order is aimed at. */ +function unitReads(u: UnitExpr, into: Set): void { + if (u.kind === "unitVar") into.add(u.id); + else if (u.kind === "unitOrderTarget") { into.add(THE_GAME); unitReads(u.unit, into); } +} + /** The variables an expression reads, by id — and `THE_GAME` when it reads a value of the game or tests a condition. */ function reads(e: NumExpr | BoolExpr, into = new Set()): Set { // A text reads the variables it is made from; a list of texts the script has never changes. @@ -292,8 +298,8 @@ function reads(e: NumExpr | BoolExpr, into = new Set()): Set { case "read": case "cond": case "tableRead": into.add(THE_GAME); break; // What the players did is as it was when the frame began: nothing a loop does within the frame changes it. case "input": break; - case "unitField": case "unitAlive": case "unitFlag": into.add(THE_GAME); if (e.unit.kind === "unitVar") into.add(e.unit.id); break; - case "unitSame": for (const u of [e.left, e.right]) if (u.kind === "unitVar") into.add(u.id); break; + case "unitField": case "unitAlive": case "unitFlag": into.add(THE_GAME); unitReads(e.unit, into); break; + case "unitSame": for (const u of [e.left, e.right]) unitReads(u, into); break; case "randomInt": reads(e.bound, into); break; case "unary": case "cast": reads(e.expr, into); break; case "binary": case "compare": reads(e.left, into); reads(e.right, into); break; diff --git a/compiler/declarations.ts b/compiler/declarations.ts index 5c4c051..ce764dc 100644 --- a/compiler/declarations.ts +++ b/compiler/declarations.ts @@ -145,6 +145,11 @@ ${kw}interface Unit { kills: number; /** What the unit is doing: \`if (u.orderId == orders.Move)\`. orders.PlayerGuard is standing guard, orders.AttackUnit attacking. */ readonly orderId: Order; + /** The unit the order is aimed at (the one followed, attacked, mined …), or null when it is aimed at a place or at nothing. */ + readonly orderTarget: Unit | null; + /** Where the order is aimed, in pixels: where a Move goes, or the target unit's centre. */ + readonly orderTargetX: number; + readonly orderTargetY: number; /** Frames until the unit can attack or cast again, 0 … 255; writing it holds the unit's fire that long (the ground weapon's, the air weapon's and the spells' alike). */ cooldown: number; /** @@ -199,6 +204,11 @@ ${kw}interface Unit { heal(amount: number | { percent: number }): void; /** Centre a location on the unit, its size kept: then createUnit(), moveUnit() and the rest can happen where the unit is. */ locate(location: Location): void; + /** + * Send an SCV, Probe or Drone to mine a mineral field or harvest a Refinery, Extractor or Assimilator, as a right-click + * on it does. Anything else, either way round, is left as it is. + */ + gather(target: Unit): void; } /** Which units a loop or a pick looks at; a part left out matches all. units.Men, units.Buildings and units.Factories work as a type. */ ${kw}interface UnitFilter { diff --git a/compiler/gameSim.ts b/compiler/gameSim.ts index 18820ef..5018a34 100644 --- a/compiler/gameSim.ts +++ b/compiler/gameSim.ts @@ -205,6 +205,8 @@ class GameUnit implements SimUnit { get speedUpgrade() { return this.read("speedUpgrade", () => this.flag(0x10000000)); } get hasTarget() { return this.read("hasTarget", () => this.m.getUint32(this.at + 0x5c, true) !== 0); } get inTransport() { return this.read("inTransport", () => this.flag(0x00000040)); } + get orderTargetX() { return this.read("orderTargetX", () => this.m.getUint16(this.at + 0x58, true)); } + get orderTargetY() { return this.read("orderTargetY", () => this.m.getUint16(this.at + 0x5a, true)); } // Not read from the game yet: the spell timers and whether the unit is under attack. stim = 0; ensnare = 0; plague = 0; lockdown = 0; maelstrom = 0; irradiate = 0; stasis = 0; /** The attack-notify timer (+0x87) running: the game raised its under-attack alert for the unit within the last second or so. */ diff --git a/compiler/generated/stdlib.ts b/compiler/generated/stdlib.ts index 544e410..3cbefec 100644 --- a/compiler/generated/stdlib.ts +++ b/compiler/generated/stdlib.ts @@ -8,6 +8,7 @@ export const STDLIB_SOURCES: Readonly> = { "screen": "/**\n * Pixel screens: the standard library's \"trigscript/screen\" (TrigScript 4).\n *\n * import { Screen, ScreenView, sprite } from \"trigscript/screen\";\n *\n * const SHIP = sprite([\".1.\", \"111\", \"1.1\"]);\n *\n * program(async () => {\n * const screen = new Screen(4, 4, 24, 16); // 24 × 16 pixels, its corner on tile (4, 4)\n * let x = 10;\n * while (true) {\n * screen.clear();\n * screen.rect(0, 15, 24, 1, 5); // the ground, in colour 5\n * screen.blit(SHIP, x, 12);\n * screen.number(score, 1, 1, 2); // digits 3 × 5 pixels, in colour 2\n * screen.present(); // on the map, and so on the minimap (screen.reveal(P1) once first)\n * await nextFrame();\n * }\n * });\n *\n * A screen is a grid of pixels, each 0 (empty) or a colour from 1 to 7; drawing changes the grid, and `present()`\n * shows it: a pixel is a unit on the map, owned by the player whose colour it is, so the minimap shows the picture —\n * neighbouring pixels of one colour join into a solid block there. Only the pixels that changed since the last\n * `present()` are made or taken away, and only the pixels drawn since are looked at, so a still picture costs nothing to\n * show. Draw through the methods (`set`, `clear`, `rect`, …): a pixel written into `pixels` directly is not seen. The same grid can be shown in a\n * player's text lines too, as squares (`ScreenView` in a `ui.lines` view): one game, two screens, as the Tetris probe has it.\n *\n * A player sees the pixels only where they have vision: `screen.reveal(P1)` once gives them Map Revealers over it.\n *\n * Two looks (the constructor's last argument): \"dots\", Overlords, which fly — the minimap draws each as a dot with a gap\n * round it, the screen may be over Space; and \"solid\", Pylons, which the minimap draws as their whole two-tile\n * footprint, so pixels side by side are one block — on buildable ground (probes/lib/screen-map.mts --ground).\n *\n * What the map needs, found playing the unit-pixel probe in StarCraft: Remastered (2026-10-16): the owners of the\n * pixels (P3, P4, P5, P1, P6, P7, P8 below; their colours are theirs on the map, so give them the colours of TEXT_COLORS) must not\n * be computers — a computer moves its own units — and Remastered will not start a game without a computer, so one slot\n * (P2 here) is a computer that owns no pixel. A pixel is an Overlord, which sits on any ground and on nothing else; keep\n * the screen's tiles clear of buildings. A Pylon needs buildable ground, and none of the map's own units in the way. About 80 pixels made and taken away in a frame did not slow the game.\n */\nimport { centerLocation, createUnit, removeUnitAt, reserveLocation, textColors, P1, P3, P4, P5, P6, P7, P8, type Player, type UnitType } from \"trigscript\";\n\n/**\n * Whose units show colours 1 to 7 on the map, in the order of TEXT_COLORS: give each player that colour in the map\n * (cyan, yellow, purple, green, red, blue, orange). Green is P1's — your own units are green on the minimap anyway.\n * Not computers.\n */\nexport const OWNERS: readonly Player[] = [P3, P4, P5, P1, P6, P7, P8];\n/** The same colours in the text lines (`ScreenView`), 0 an empty square: cyan, yellow, purple, green, red, blue, orange. */\nexport const TEXT_COLORS: readonly number[] = [0, textColors.cyan, textColors.yellow, textColors.purple, textColors.green, textColors.red, textColors.blue, textColors.orange];\n\n/** Where each pixel's unit is made: a location the map does not use, taken when the script is built. */\nconst SPOT = reserveLocation(\"screen: where each pixel is made\");\n\n/** A picture known when the script is built, to `blit` onto a screen: its size, and its pixels a row at a time (0 is see-through). */\nexport interface Sprite { readonly width: number; readonly height: number; readonly cells: readonly number[] }\n\n/**\n * A sprite from rows of text, when the script is built: \"1\" … \"7\" a pixel of that colour, anything else see-through.\n *\n * const SHIP = sprite([\".1.\", \"111\", \"1.1\"]);\n */\nexport function sprite(rows: readonly string[]): Sprite {\n const width = Math.max(0, ...rows.map((r) => r.length));\n const cells: number[] = [];\n for (const row of rows) for (let x = 0; x < width; x++) { const c = Number(row[x]); cells.push(c >= 1 && c <= 7 ? c : 0); }\n return { width, height: rows.length, cells };\n}\n\n/** The digits 0 to 9, three pixels wide and five high, for `number()`: each fifteen pixels, a row at a time. */\nconst DIGITS: readonly number[] = [\n \"111101101101111\", \"010110010010111\", \"111001111100111\", \"111001111001111\", \"101101111001001\",\n \"111100111001111\", \"111100111101111\", \"111001001010010\", \"111101111101111\", \"111101111001111\",\n].flatMap((d) => d.split(\"\").map(Number));\n\n/** The most pixels a screen has: 32 × 32 at two tiles a pixel covers a 64 × 64 map, 64 × 32 half of a 128 × 128 one. */\nexport const MAX_PIXELS = 2048;\n\nexport class Screen {\n /** The picture being drawn: a colour a pixel, a row at a time (the first width × height of them). */\n pixels: number[] = new Array(MAX_PIXELS).fill(0);\n /** What the map shows now: the picture as it was at the last `present()`. */\n shown: number[] = new Array(MAX_PIXELS).fill(0);\n /** The pixels drawn a colour they were not since the last `present()`, in order: each one's place and its x and y. */\n drawnAt: number[] = new Array(MAX_PIXELS).fill(0);\n drawnX: number[] = new Array(MAX_PIXELS).fill(0);\n drawnY: number[] = new Array(MAX_PIXELS).fill(0);\n drawn = 0;\n /** More drawn than the list holds: `present()` looks at every pixel instead. */\n overflow = false;\n x: number;\n y: number;\n width: number;\n height: number;\n cell: number;\n /** The unit a pixel is: an Overlord (\"dots\"), or a Pylon (\"solid\"). */\n unit = 0;\n\n /**\n * A screen `width` × `height` pixels (MAX_PIXELS at most), its top left corner on tile (x, y) of the map, a pixel two\n * tiles across.\n * @param look \"dots\" (the default): a pixel is an Overlord, which the minimap draws as a dot, a gap round it — it flies,\n * so the screen may be over anything, Space too. \"solid\": a pixel is a Pylon, which the minimap draws as its whole\n * footprint, two tiles square, so pixels side by side are one block — it needs buildable ground under the screen,\n * and gives its owner Protoss supply. (Overlords a tile apart do not fit: the game will not place most of them.)\n */\n constructor(x: number, y: number, width: number, height: number, look: \"dots\" | \"solid\" = \"dots\") {\n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n this.cell = 64;\n this.unit = (look === \"solid\" ? 156 : 42) as UnitType; // Protoss Pylon, Zerg Overlord: the game's own ids, the same under a mod's names\n }\n\n /** Every pixel the colour (0, empty, unless it says). */\n clear(color: number = 0) {\n let i = 0;\n let y = 0;\n while (y < this.height) {\n let x = 0;\n while (x < this.width) { this.put(i, x, y, color); i++; x++; }\n y++;\n }\n }\n\n /** One pixel; nothing happens outside the screen. */\n set(x: number, y: number, color: number) {\n if (x >= 0 && y >= 0 && x < this.width && y < this.height) this.put(y * this.width + x, x, y, color);\n }\n\n /** A pixel written, and listed for `present()` when its colour changed. */\n private put(i: number, x: number, y: number, color: number) {\n if (this.pixels[i] === color) return;\n this.pixels[i] = color;\n if (this.drawn < MAX_PIXELS) {\n this.drawnAt[this.drawn] = i;\n this.drawnX[this.drawn] = x;\n this.drawnY[this.drawn] = y;\n this.drawn++;\n } else this.overflow = true;\n }\n\n /** The colour of a pixel; 0 outside the screen. */\n get(x: number, y: number): number {\n if (x >= 0 && y >= 0 && x < this.width && y < this.height) return this.pixels[y * this.width + x];\n return 0;\n }\n\n /** A filled rectangle, its top left at (x, y); what is outside the screen is left out. */\n rect(x: number, y: number, width: number, height: number, color: number) {\n let j = 0;\n while (j < height) {\n let i = 0;\n while (i < width) { this.set(x + i, y + j, color); i++; }\n j++;\n }\n }\n\n /** A line from (x0, y0) to (x1, y1), both ends drawn. */\n line(x0: number, y0: number, x1: number, y1: number, color: number) {\n const dx = Math.abs(x1 - x0);\n const dy = -Math.abs(y1 - y0);\n const sx = x0 < x1 ? 1 : -1;\n const sy = y0 < y1 ? 1 : -1;\n let err = dx + dy;\n let x = x0;\n let y = y0;\n while (true) {\n this.set(x, y, color);\n if (x === x1 && y === y1) break;\n const e2 = 2 * err;\n if (e2 >= dy) { err += dy; x += sx; }\n if (e2 <= dx) { err += dx; y += sy; }\n }\n }\n\n /** A sprite with its top left at (x, y): its see-through pixels leave what is under them. */\n blit(s: Sprite, x: number, y: number) {\n let k = 0;\n let j = 0;\n while (j < s.height) {\n let i = 0;\n while (i < s.width) {\n const c = s.cells[k];\n if (c !== 0) this.set(x + i, y + j, c);\n k++;\n i++;\n }\n j++;\n }\n }\n\n /** A whole number's digits, 3 × 5 pixels each with a pixel between, its top left at (x, y): a score on the minimap. */\n number(n: number, x: number, y: number, color: number) {\n let rest = n < 0 ? -n : n;\n let count = 1;\n let probe = rest;\n while (probe >= 10) { probe = Math.floor(probe / 10); count++; }\n let place = x + (count - 1) * 4;\n while (true) {\n const d = rest % 10;\n let k = 0;\n while (k < 15) {\n if (DIGITS[d * 15 + k] === 1) this.set(place + (k % 3), y + Math.floor(k / 3), color);\n k++;\n }\n rest = Math.floor(rest / 10);\n place -= 4;\n if (rest === 0) break;\n }\n }\n\n /**\n * Let a player see the screen: Map Revealers of theirs over it, for the rest of the game. Without them its pixels,\n * owned by other players, are hidden by the fog of war — on the map and on the minimap. Once, before the first\n * `present()`.\n * @param player Who sees it: P1 … P8, known when the script is built.\n */\n reveal(player: Player) {\n // A Map Revealer sees ten tiles round; one every six tiles leaves no gap.\n const right = this.x * 32 + this.width * this.cell;\n const bottom = this.y * 32 + this.height * this.cell;\n let py = this.y * 32 + 96;\n while (py < bottom + 96) {\n let px = this.x * 32 + 96;\n while (px < right + 96) {\n centerLocation(SPOT, px, py, 32, 32);\n createUnit(player, 101 as UnitType, 1, SPOT); // Map Revealer\n px += 192;\n }\n py += 192;\n }\n }\n\n /**\n * The picture on the map: each pixel that changed since the last time taken away and made again in its colour. Only\n * the pixels drawn since are looked at (one drawn and drawn back is passed over), unless more were drawn than the list\n * holds.\n */\n present() {\n if (this.overflow) {\n let i = 0;\n let y = 0;\n while (y < this.height) {\n let x = 0;\n while (x < this.width) { this.show(i, x, y); i++; x++; }\n y++;\n }\n this.overflow = false;\n } else {\n for (let k = 0; k < this.drawn; k++) this.show(this.drawnAt[k], this.drawnX[k], this.drawnY[k]);\n }\n this.drawn = 0;\n }\n\n /** One pixel on the map as it is in the picture, when it is not already. */\n private show(i: number, x: number, y: number) {\n const now = this.pixels[i];\n const was = this.shown[i];\n if (now === was) return;\n const half = this.cell >> 1;\n centerLocation(SPOT, this.x * 32 + x * this.cell + half, this.y * 32 + y * this.cell + half, 32, 32);\n OWNERS.forEach((owner, k) => { if (was === k + 1) removeUnitAt(owner, this.unit, 1, SPOT); });\n OWNERS.forEach((owner, k) => { if (now === k + 1) createUnit(owner, this.unit, 1, SPOT); });\n this.shown[i] = now;\n }\n}\n\n/**\n * A screen in the text lines, a square a pixel — filled in its colour, or empty — a line a row. For a `ui.lines` view:\n * ``, the screen's size known when the script is built. Eleven lines\n * show at once, sixty squares across.\n */\nexport function ScreenView({ screen, width, height }: { screen: Screen; width: number; height: number }) {\n return <>{UP_TO_60.map((y) => y < height && {UP_TO_60.map((x) => x < width && )})};\n}\n\n/** 0 … 59: the places a view's rows and columns are counted over, the ones past its size left out when the script is built. */\nconst UP_TO_60: readonly number[] = Array.from({ length: 60 }, (_, i) => i);\n", "signals": "/**\n * Events of your own: the standard library's \"trigscript/signals\" (TrigScript 4).\n *\n * import { Signal } from \"trigscript/signals\";\n *\n * const waveCleared = new Signal();\n *\n * program(async () => {\n * waveCleared.on((wave) => { setResources(P1, \"add\", 100 * wave, \"ore\"); }); // braces: a handler gives back no action\n * waveCleared.once((wave) => print(`First wave down!`));\n * const id = waveCleared.on((wave) => print(`Wave ${wave} cleared`));\n * …\n * waveCleared.emit(3); // every handler, in the order they were added\n * waveCleared.off(id);\n * });\n *\n * A signal lets one part of a map say that something happened without knowing who listens: the shop, the score and the\n * music each add a handler, and the wave code only emits. What it carries is one value of the type it is made with —\n * a number, a boolean, a text or a unit (`new Signal()`). Its handlers are functions kept as values: they may use\n * what the block they were written in has, and they run to their end, one after another, within the frame.\n *\n * Make a signal inside the program that uses it (`const s = new Signal()` at its top): a signal is variables\n * of a program, as anything a program writes is.\n */\n\nexport class Signal {\n /** The handlers, by the number `on` gave; one taken off is undefined, and its place is given to the next one added. */\n handlers: (((value: T) => void) | undefined)[] = [];\n /** Which handlers go once they have run once. */\n onceOnly: boolean[] = [];\n\n /**\n * Add a handler: it runs at every `emit`, handed the value.\n * @returns Its number, for `off`.\n */\n on(handler: (value: T) => void): number {\n return this.add(handler, false);\n }\n\n /** Add a handler that runs at the next `emit` only. @returns Its number, for `off` before then. */\n once(handler: (value: T) => void): number {\n return this.add(handler, true);\n }\n\n /** Take a handler off, by the number `on` or `once` gave. */\n off(id: number) {\n if (id >= 0 && id < this.handlers.length) this.handlers[id] = undefined;\n }\n\n /** Run every handler, in the order they were added, each handed `value`. */\n emit(value: T) {\n let i = 0;\n while (i < this.handlers.length) {\n const h = this.handlers[i];\n if (h) {\n if (this.onceOnly[i]) this.handlers[i] = undefined;\n h(value);\n }\n i++;\n }\n }\n\n /** How many handlers it has. */\n count(): number {\n let n = 0;\n for (const h of this.handlers) if (h) n++;\n return n;\n }\n\n /** Take every handler off. */\n clear() {\n let i = 0;\n while (i < this.handlers.length) { this.handlers[i] = undefined; i++; }\n }\n\n private add(handler: (value: T) => void, once: boolean): number {\n // A place one was taken off from, or a new one at the end.\n let i = 0;\n while (i < this.handlers.length) {\n if (!this.handlers[i]) {\n this.handlers[i] = handler;\n this.onceOnly[i] = once;\n return i;\n }\n i++;\n }\n this.handlers.push(handler);\n this.onceOnly.push(once);\n return this.handlers.length - 1;\n }\n}\n", "timers": "/**\n * Time in a program: the standard library's \"trigscript/timers\" (TrigScript 4).\n *\n * import { every, after, Cooldown, Countdown, SECOND } from \"trigscript/timers\";\n *\n * program(async () => {\n * const spawner = every(10 * SECOND, (n) => spawnWave(n)); // every ten seconds, the wave's number handed over\n * after(3 * SECOND, () => print(\"Go!\"));\n * const shot = new Cooldown(12);\n * while (true) {\n * if (keyPressed(P1, \"Space\") && shot.use()) fire();\n * if (boss.hp <= 0) spawner.cancel();\n * await nextFrame();\n * }\n * });\n *\n * for await (const b of over(bullets, { per: 50 })) b.x += b.dx; // fifty a frame, on to the next frame after each fifty\n *\n * Time is counted in frames of the game, 24 a second on Fastest (`SECOND`). `every` and `after` run their function in a\n * task beside the program, so the program goes on at once; the Task they give back stops it (`cancel()`) and says\n * whether it still runs (`running`). Their function is kept for the task, with what it uses of the block it was written\n * in — written in a loop, each turn's is its own, as JavaScript has it — and it runs to its end within the frame (it\n * does not wait). Sixteen of one `every` or `after` written once can run at a time. `Cooldown`, `Countdown` and\n * `Stopwatch` read the game's frame counter: no task, nothing to stop.\n */\nimport { game, start, sleep, frames, nextFrame, memory, type Task } from \"trigscript\";\n\n/** Frames a second of game time on Fastest, the speed a map is played at. */\nexport const SECOND = 24;\n\n/** The frames of game time since the game began. */\nexport function now(): number {\n return memory.game.frame;\n}\n\nconst repeating = game(async (period: number, fn: (count: number) => void, times: number) => {\n let count = 0;\n while (times <= 0 || count < times) {\n await sleep(frames(period < 1 ? 1 : period));\n count++;\n fn(count);\n }\n});\n\nconst later = game(async (delay: number, fn: () => void) => {\n await sleep(frames(delay < 1 ? 1 : delay));\n fn();\n});\n\n/**\n * Run `fn` every `period` frames, from `period` frames from now: forever, or `times` times. It is handed how many times\n * it has run, 1 the first time.\n * @param period Frames between one run and the next (24 a second).\n * @param fn What to run; it runs to its end within the frame.\n * @param times How many times, or 0 (the default) for as long as the game lasts.\n * @returns The task: `cancel()` stops it.\n */\nexport const every = game((period: number, fn: (count: number) => void, times: number = 0): Task => start(repeating(period, fn, times)));\n\n/**\n * Run `fn` once, `delay` frames from now.\n * @param delay Frames from now (24 a second).\n * @param fn What to run; it runs to its end within the frame.\n * @returns The task: `cancel()` before then and it never runs.\n */\nexport const after = game((delay: number, fn: () => void): Task => start(later(delay, fn)));\n\n/**\n * The elements of `list`, `per` of them a frame: a loop spread over frames, for work that need not be done in one —\n * a thousand bullets moved, a map's cells looked at. What a frame costs stays what `per` turns cost.\n *\n * for await (const b of over(bullets, { per: 50 })) b.x += b.dx;\n *\n * It reads the list's length as it goes, as `for…of` does: what is pushed meanwhile is reached too, and an element\n * removed before it is reached moves the rest up, so one is passed over, as with an index. Each element is the list's\n * own: what is written to it stays. The loop goes on to the next frame only between elements, never after the last.\n * @param list The array to walk.\n * @param options `per`: how many elements a frame (1 at least).\n */\nexport async function* over(list: T[], options: { per: number }) {\n const per = options.per < 1 ? 1 : options.per;\n let n = 0;\n for (let i = 0; i < list.length; i++) {\n yield list[i];\n n++;\n if (n >= per && i + 1 < list.length) {\n n = 0;\n await nextFrame();\n }\n }\n}\n\n/**\n * 0, 1, … `count` − 1, `per` of them a frame: `over` for a count rather than an array.\n *\n * for await (const y of spread(96, { per: 8 })) drawRow(y); // twelve frames for 96 rows\n * @param count How many numbers, from 0.\n * @param options `per`: how many a frame (1 at least).\n */\nexport async function* spread(count: number, options: { per: number }) {\n const per = options.per < 1 ? 1 : options.per;\n let n = 0;\n for (let i = 0; i < count; i++) {\n yield i;\n n++;\n if (n >= per && i + 1 < count) {\n n = 0;\n await nextFrame();\n }\n }\n}\n\n/**\n * Something that can be done once every so many frames: a weapon's reload, a spell's cooldown.\n *\n * const blink = new Cooldown(5 * SECOND);\n * if (keyPressed(P1, \"B\") && blink.use()) teleport();\n */\nexport class Cooldown {\n period: number;\n until = 0;\n\n /** Ready at once, then once every `period` frames. */\n constructor(period: number) {\n this.period = period;\n }\n\n /** Whether it is ready now. */\n ready(): boolean {\n return now() >= this.until;\n }\n\n /** If it is ready, use it — it is ready again `period` frames from now — and say true; else false. */\n use(): boolean {\n if (now() < this.until) return false;\n this.until = now() + this.period;\n return true;\n }\n\n /** Frames until it is ready again: 0 when it is. */\n left(): number {\n return this.until > now() ? this.until - now() : 0;\n }\n\n /** Ready again at once. */\n reset() {\n this.until = 0;\n }\n}\n\n/**\n * A length of time that runs down while the game runs: a round's clock, a bomb's fuse.\n *\n * const round = new Countdown(90 * SECOND);\n * ui.lines(P1, () => {clock(round.left())});\n * await until(() => round.done());\n */\nexport class Countdown {\n end = 0;\n\n /** Running, done `length` frames from now (0: done already). */\n constructor(length: number = 0) {\n this.end = now() + length;\n }\n\n /** Start again, done `length` frames from now. */\n restart(length: number) {\n this.end = now() + length;\n }\n\n /** Frames left: 0 once it is done. */\n left(): number {\n return this.end > now() ? this.end - now() : 0;\n }\n\n /** Whether it has run out. */\n done(): boolean {\n return now() >= this.end;\n }\n\n /** More time, or less (a number below zero). */\n add(frames: number) {\n this.end += frames;\n }\n}\n\n/** How long since it was made, or last reset: a lap's time, a survival score. */\nexport class Stopwatch {\n from = 0;\n\n constructor() {\n this.from = now();\n }\n\n /** Frames since it started. */\n elapsed(): number {\n return now() - this.from;\n }\n\n /** From 0 again. */\n reset() {\n this.from = now();\n }\n}\n", - "ui": "/**\n * A kit for the game's text lines: the standard library's \"trigscript/ui\" (TrigScript 4).\n *\n * import { Meter, Panel, MenuList, DialogBox, choose, say, clock } from \"trigscript/ui\";\n *\n * const ITEMS = [\"Marine (50)\", \"Medic (75)\", \"Leave\"];\n * const shop = { selected: 0, open: false };\n * const talk = { speaker: \"\", text: \"\", open: false };\n *\n * program(async () => {\n * ui.lines(P1, () => (\n * <>\n * \n * \n * \n * {shop.open && }\n * \n * \n * ));\n * await say(P1, talk, \"Raynor\", \"Hold the bridge until dawn.\");\n * const pick = await choose(P1, ITEMS.length, shop);\n * });\n *\n * The text lines are one player's: a view is shown to that player only, rebuilt when what it reads changes (a function\n * it calls included) and shown again once a second as it was, so a menu, a dialog and a meter cost nothing while nothing\n * changes. Give a player one `ui.lines` and\n * put everything in it, as the example does: the components are pieces of one view, and the state they show is a\n * record of yours (`shop`, `talk`) that the functions here change.\n *\n * What the text lines can show, played in StarCraft: Remastered (the UI spike, 2026-10-16): eleven lines; colour codes\n * take no width; ■ □ ● are one width; after grey on a line every later colour code is ignored, so grey goes last.\n */\nimport { keyPressed, nextFrame, sleep, frames, game, textColors, type Player, type TextColor } from \"trigscript\";\n\n/** Frames a second of game time on Fastest, the speed a map is played at. */\nconst PER_SECOND = 24;\n\n/** \"1:05\": frames of game time as minutes and seconds (24 frames a second, on Fastest). */\nexport function clock(frames: number): string {\n const seconds = Math.floor(frames / PER_SECOND);\n return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, \"0\")}`;\n}\n\n/** \"12,345\": a whole number with its thousands marked. */\nexport function thousands(n: number): string {\n let rest = n < 0 ? -n : n;\n let out = \"\";\n while (rest >= 1000) {\n out = `,${String(rest % 1000).padStart(3, \"0\")}${out}`;\n rest = Math.floor(rest / 1000);\n }\n return `${n < 0 ? \"-\" : \"\"}${rest}${out}`;\n}\n\n/**\n * A labelled bar on a line of its own — \"Base ■■■■■■□□□□ 900/1500\" — green above half, yellow above a quarter, red below.\n * @param label What the bar is of.\n * @param value How much there is.\n * @param max How much there can be.\n * @param width How many squares the bar is (10 unless it says).\n */\nexport function Meter({ label, value, max, width }: { label: string; value: number; max: number; width?: number }) {\n return (\n \n {label} max ? textColors.green : value * 4 > max ? textColors.yellow : textColors.red} /> {value}/{max}\n \n );\n}\n\n/**\n * A title over what is inside it: \"-- Wave 3 --\" in its colour (yellow unless it says), then the lines inside.\n * @param title The title.\n * @param color The title's colour.\n */\nexport function Panel({ title, children, color }: { title: string; children?: Children; color?: TextColor }) {\n return (\n <>\n -- {title} --\n {children}\n \n );\n}\n\n/**\n * A menu's lines: each item on a line of its own, the one at `selected` marked \"> \" and in its colour (cyan unless it\n * says). `items` is a list the script has, or an array of texts of the program.\n */\nexport function MenuList({ items, selected, color }: { items: readonly string[]; selected: number; color?: TextColor }) {\n return (\n <>\n {items.map((item, i) => (\n \n {i === selected ? \"> \" : \" \"}\n {item}\n \n ))}\n \n );\n}\n\n/**\n * Let a player choose one of `count` things: the menu opens (`menu.open`), W and S (or Up and Down) move\n * `menu.selected` (round from the last to the first), and Space chooses — the place chosen, once it is. (Not Enter:\n * in a game of several players Enter opens the chat.) Show it with `MenuList`, in the\n * player's `ui.lines`: `{shop.open && }`.\n * @param player Who chooses: P1 … P8, known when the script is built.\n * @param count How many things there are to choose from.\n * @param menu The record a view shows: which is marked, and whether the menu is open.\n */\nexport const choose = game(async (player: Player, count: number, menu: { selected: number; open: boolean }): Promise => {\n menu.open = true;\n while (true) {\n if (keyPressed(player, \"W\") || keyPressed(player, \"Up\")) menu.selected = (menu.selected + count - 1) % count;\n if (keyPressed(player, \"S\") || keyPressed(player, \"Down\")) menu.selected = (menu.selected + 1) % count;\n if (keyPressed(player, \"Space\")) break;\n await nextFrame();\n }\n menu.open = false;\n return menu.selected;\n});\n\n/**\n * A text put into `into.text` a character at a time, one every `every` frames (2 unless it says): a view that shows\n * `into.text` shows it being typed. Done when the whole text is there.\n */\nexport const typewriter = game(async (into: { text: string }, text: string, every: number = 2) => {\n let n = 0;\n while (n < text.length) {\n n++;\n into.text = text.slice(0, n);\n await sleep(frames(every));\n }\n});\n\n/**\n * Someone says something to a player: the dialog opens (`box.open`), the speaker's name and the words typed in, and it\n * closes when the player presses Space. Show it with `DialogBox`.\n * @param player Who reads it: P1 … P8, known when the script is built.\n * @param box The record a view shows.\n * @param speaker Who speaks.\n * @param text What they say.\n */\nexport const say = game(async (player: Player, box: { speaker: string; text: string; open: boolean }, speaker: string, text: string) => {\n box.open = true;\n box.speaker = speaker;\n box.text = \"\";\n await typewriter(box, text);\n while (!keyPressed(player, \"Space\")) await nextFrame();\n box.open = false;\n});\n\n/** A dialog's lines while it is open: the speaker in yellow, the words, and what to press (Space). Nothing while it is closed. */\nexport function DialogBox({ box }: { box: { speaker: string; text: string; open: boolean } }) {\n return box.open ? (\n <>\n {box.speaker}\n {box.text}\n (Space)\n \n ) : null;\n}\n\n/** A line at the end of a log that keeps the last `keep` (6 unless it says), the oldest taken off the front. */\nexport const log = game((lines: string[], text: string, keep: number = 6) => {\n lines.push(text);\n while (lines.length > keep) lines.shift();\n});\n\n/** A log's lines, oldest first, each in its colour (white unless it says). */\nexport function LogLines({ lines, color }: { lines: readonly string[]; color?: TextColor }) {\n return <>{lines.map((text) => {text})};\n}\n" + "ui": "/**\n * A kit for the game's text lines: the standard library's \"trigscript/ui\" (TrigScript 4).\n *\n * import { Meter, Panel, MenuList, DialogBox, choose, say, clock } from \"trigscript/ui\";\n *\n * const ITEMS = [\"Marine (50)\", \"Medic (75)\", \"Leave\"];\n * const shop = { selected: 0, open: false };\n * const talk = { speaker: \"\", text: \"\", open: false };\n *\n * program(async () => {\n * ui.lines(P1, () => (\n * <>\n * \n * \n * \n * {shop.open && }\n * \n * \n * ));\n * await say(P1, talk, \"Raynor\", \"Hold the bridge until dawn.\");\n * const pick = await choose(P1, ITEMS.length, shop);\n * });\n *\n * The text lines are one player's: a view is shown to that player only, rebuilt when what it reads changes (a function\n * it calls included) and shown again once a second as it was, so a menu, a dialog and a meter cost nothing while nothing\n * changes. Give a player one `ui.lines` and\n * put everything in it, as the example does: the components are pieces of one view, and the state they show is a\n * record of yours (`shop`, `talk`) that the functions here change.\n *\n * What the text lines can show, played in StarCraft: Remastered (the UI spike, 2026-10-16): eleven lines; colour codes\n * take no width; ■ □ ● are one width; after grey on a line every later colour code is ignored, so grey goes last.\n */\nimport { keyPressed, nextFrame, sleep, frames, game, textColors, type Player, type TextColor } from \"trigscript\";\n\n/** Frames a second of game time on Fastest, the speed a map is played at. */\nconst PER_SECOND = 24;\n\n/** \"1:05\": frames of game time as minutes and seconds (24 frames a second, on Fastest). */\nexport function clock(frames: number): string {\n const seconds = Math.floor(frames / PER_SECOND);\n return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, \"0\")}`;\n}\n\n/** \"12,345\": a whole number with its thousands marked. */\nexport function thousands(n: number): string {\n let rest = n < 0 ? -n : n;\n let out = \"\";\n while (rest >= 1000) {\n out = `,${String(rest % 1000).padStart(3, \"0\")}${out}`;\n rest = Math.floor(rest / 1000);\n }\n return `${n < 0 ? \"-\" : \"\"}${rest}${out}`;\n}\n\n/**\n * A labelled bar on a line of its own — \"Base ■■■■■■□□□□ 900/1500\" — green above half, yellow above a quarter, red below.\n * @param label What the bar is of.\n * @param value How much there is.\n * @param max How much there can be.\n * @param width How many squares the bar is (10 unless it says).\n */\nexport function Meter({ label, value, max, width }: { label: string; value: number; max: number; width?: number }) {\n return (\n \n {label} max ? textColors.green : value * 4 > max ? textColors.yellow : textColors.red} /> {value}/{max}\n \n );\n}\n\n/**\n * A title over what is inside it: \"-- Wave 3 --\" in its colour (yellow unless it says), then the lines inside.\n * @param title The title.\n * @param color The title's colour.\n */\nexport function Panel({ title, children, color }: { title: string; children?: Children; color?: TextColor }) {\n return (\n <>\n -- {title} --\n {children}\n \n );\n}\n\n/**\n * A menu's lines: each item on a line of its own, the one at `selected` marked \"> \" and in its colour (cyan unless it\n * says). `items` is a list the script has, or an array of texts of the program.\n */\nexport function MenuList({ items, selected, color }: { items: readonly string[]; selected: number; color?: TextColor }) {\n return (\n <>\n {items.map((item, i) => (\n \n {i === selected ? \"> \" : \" \"}\n {item}\n \n ))}\n \n );\n}\n\n/**\n * Let a player choose one of `count` things: the menu opens (`menu.open`), W and S (or Up and Down) move\n * `menu.selected` (round from the last to the first), and Space chooses — the place chosen, once it is. (Not Enter:\n * in a game of several players Enter opens the chat.) Show it with `MenuList`, in the\n * player's `ui.lines`: `{shop.open && }`.\n * @param player Who chooses: P1 … P8, known when the script is built.\n * @param count How many things there are to choose from.\n * @param menu The record a view shows: which is marked, and whether the menu is open.\n */\nexport const choose = game(async (player: Player, count: number, menu: { selected: number; open: boolean }): Promise => {\n menu.open = true;\n while (true) {\n if (keyPressed(player, \"W\") || keyPressed(player, \"Up\")) menu.selected = (menu.selected + count - 1) % count;\n if (keyPressed(player, \"S\") || keyPressed(player, \"Down\")) menu.selected = (menu.selected + 1) % count;\n if (keyPressed(player, \"Space\")) break;\n await nextFrame();\n }\n menu.open = false;\n return menu.selected;\n});\n\n/**\n * A text put into `into.text` a character at a time, one every `every` frames (2 unless it says): a view that shows\n * `into.text` shows it being typed. Done when the whole text is there.\n */\nexport const typewriter = game(async (into: { text: string }, text: string, every: number = 2) => {\n let n = 0;\n while (n < text.length) {\n n++;\n into.text = text.slice(0, n);\n await sleep(frames(every));\n }\n});\n\n/**\n * Someone says something to a player: the dialog opens (`box.open`), the speaker's name and the words typed in, and it\n * closes when the player presses Space. Show it with `DialogBox`.\n * @param player Who reads it: P1 … P8, known when the script is built.\n * @param box The record a view shows.\n * @param speaker Who speaks.\n * @param text What they say.\n */\nexport const say = game(async (player: Player, box: { speaker: string; text: string; open: boolean }, speaker: string, text: string) => {\n box.open = true;\n box.speaker = speaker;\n box.text = \"\";\n await typewriter(box, text);\n while (!keyPressed(player, \"Space\")) await nextFrame();\n box.open = false;\n});\n\n/** A dialog's lines while it is open: the speaker in yellow, the words, and what to press (Space). Nothing while it is closed. */\nexport function DialogBox({ box }: { box: { speaker: string; text: string; open: boolean } }) {\n return box.open ? (\n <>\n {box.speaker}\n {box.text}\n (Space)\n \n ) : null;\n}\n\n/** A line at the end of a log that keeps the last `keep` (6 unless it says), the oldest taken off the front. */\nexport const log = game((lines: string[], text: string, keep: number = 6) => {\n lines.push(text);\n while (lines.length > keep) lines.shift();\n});\n\n/** A log's lines, oldest first, each in its colour (white unless it says). */\nexport function LogLines({ lines, color }: { lines: readonly string[]; color?: TextColor }) {\n return <>{lines.map((text) => {text})};\n}\n", + "workers": "/**\n * Workers that go to work: the standard library's \"trigscript/workers\" (TrigScript 4).\n *\n * import { buildAutoMiningProgram } from \"trigscript/workers\";\n *\n * buildAutoMiningProgram(); // at the top of the script, once: on for the whole game\n *\n * With auto-mining on, a human player's new SCV, Probe or Drone whose producer's rally point is on a mineral patch\n * starts mining that patch, instead of walking there and standing. One rallied to the player's own finished gas\n * building (Refinery, Extractor, Assimilator) starts gathering gas from it. Anywhere else — the ground, a bare geyser,\n * a gas building still being built or another player's, a patch mined out — it walks to the rally point as it always\n * does. It acts once, as the worker comes out: an order the player gives afterwards stands. Computer players' workers\n * and those a trigger makes (Create Unit) are left alone, and a busy patch or gas building is the game's to sort out,\n * as when the player right-clicks it.\n *\n * Played in StarCraft: Remastered (2026-11-07 and 2026-11-08): SCVs, Probes and Drones rallied to minerals and to gas\n * all went to work. How it sees a new worker, from `map trace` (2026-11-07): an SCV comes out of training with its\n * order changing from Nothing, and a Drone from ZergBirth, on the frame the rally is applied (a Probe was not traced;\n * in play it went to work as an SCV does). A rally on a patch gives the worker Move to the patch's exact centre with no target; one on a building gives\n * Follow with the building as the target. `gather()` then gives the order a right-click would: MoveToMinerals or\n * MoveToGas.\n */\nimport { program, on, isHuman, allUnits, units, orders, P1, P2, P3, P4, P5, P6, P7, P8, type Unit } from \"trigscript\";\n\nfunction ownerIsHuman(worker: Unit): boolean {\n const owner = worker.owner;\n if (owner == P1) return isHuman(P1);\n if (owner == P2) return isHuman(P2);\n if (owner == P3) return isHuman(P3);\n if (owner == P4) return isHuman(P4);\n if (owner == P5) return isHuman(P5);\n if (owner == P6) return isHuman(P6);\n if (owner == P7) return isHuman(P7);\n if (owner == P8) return isHuman(P8);\n return false;\n}\n\nfunction gatherFromRally(worker: Unit) {\n if (!ownerIsHuman(worker)) return;\n if (worker.orderId == orders.Follow) {\n const gasBuilding = worker.orderTarget;\n if (gasBuilding) if (gasBuilding.owner == worker.owner && gasBuilding.buildTime == 0) worker.gather(gasBuilding);\n return;\n }\n if (worker.orderId != orders.Move || worker.hasTarget) return;\n const x = worker.orderTargetX, y = worker.orderTargetY;\n for (const patch of allUnits({ type: units.MineralFieldType1 })) if (patch.x == x && patch.y == y) { worker.gather(patch); return; }\n for (const patch of allUnits({ type: units.MineralFieldType2 })) if (patch.x == x && patch.y == y) { worker.gather(patch); return; }\n for (const patch of allUnits({ type: units.MineralFieldType3 })) if (patch.x == x && patch.y == y) { worker.gather(patch); return; }\n}\n\nlet programBuilt = false;\n\n/**\n * Build the program that turns auto-mining on for the whole game: every human player's new SCV, Probe or Drone rallied\n * to a mineral patch or the player's own finished gas building starts gathering from it. Called at the top of a\n * script, as programs are made when the map is built; a call after the first adds nothing.\n */\nexport function buildAutoMiningProgram() {\n if (programBuilt) return;\n programBuilt = true;\n program(async () => {\n on.order((worker, order, was) => {\n if (worker.type == units.ZergDrone) {\n if (was == orders.ZergBirth) gatherFromRally(worker);\n } else if (was == orders.Nothing) {\n if (worker.type == units.TerranSCV || worker.type == units.ProtossProbe) gatherFromRally(worker);\n }\n });\n });\n}\n" }; -export const STDLIB_EXTENSIONS: Readonly> = {"cutscene":".ts","fog":".ts","math":".ts","music":".ts","random":".ts","screen":".tsx","signals":".ts","timers":".ts","ui":".tsx"}; +export const STDLIB_EXTENSIONS: Readonly> = {"cutscene":".ts","fog":".ts","math":".ts","music":".ts","random":".ts","screen":".tsx","signals":".ts","timers":".ts","ui":".tsx","workers":".ts"}; diff --git a/compiler/input.ts b/compiler/input.ts index 6721b41..18953d3 100644 --- a/compiler/input.ts +++ b/compiler/input.ts @@ -211,10 +211,11 @@ export function inputsOf(programs: Program[]): { sources: InputSource[]; mouse: const sources: InputSource[] = []; let mouse = false; let at: At | null = null; - const unit = (u: UnitExpr) => { + const unit = (u: UnitExpr): void => { if (u.kind === "call") call(u.call); else if (u.kind === "pick" && u.mouse !== undefined) { mouse = true; at ??= u.at; } else if (u.kind === "unitAt") { expr(u.ptr); expr(u.epd); expr(u.uid); } + else if (u.kind === "unitOrderTarget") unit(u.unit); }; const any = (e: NumExpr | BoolExpr | UnitExpr | TextExpr) => (isTextExpr(e) ? text(e) : isUnitExpr(e) ? unit(e) : expr(e)); const looks: TextMap = { num: (e) => { expr(e); return e; }, bool: (e) => { expr(e); return e; }, call: (c) => { call(c); return c; } }; @@ -254,7 +255,7 @@ export function inputsOf(programs: Program[]): { sources: InputSource[]; mouse: case "textLoop": text(s.of); s.body.forEach(stmt); break; case "unitLoop": s.body.forEach(stmt); break; case "unitWrite": unit(s.unit); expr(s.value); break; - case "unitDo": unit(s.unit); if (s.verb.do === "damage" || s.verb.do === "heal") expr(s.verb.amount); break; + case "unitDo": unit(s.unit); if (s.verb.do === "damage" || s.verb.do === "heal") expr(s.verb.amount); if (s.verb.do === "gather") unit(s.verb.target); break; case "select": s.units.forEach(unit); break; case "tableWrite": any(s.value); break; case "centerLocation": expr(s.x); expr(s.y); if (s.size) { expr(s.size.width); expr(s.size.height); } break; diff --git a/compiler/ir.ts b/compiler/ir.ts index a1329c5..ff19e6a 100644 --- a/compiler/ir.ts +++ b/compiler/ir.ts @@ -221,10 +221,10 @@ export type EventSource = "created" | "died" | "killed" | "ordered" | "morphed"; * remaining build time frames; `matrix` the defensive matrix's frames; `speed` the current speed in 256ths of a pixel a frame. */ export type UnitNumField = "hp" | "maxHp" | "shields" | "maxShields" | "energy" | "owner" | "type" | "x" | "y" | "kills" | "orderId" | "cooldown" | "resources" - | "stim" | "ensnare" | "plague" | "lockdown" | "maelstrom" | "irradiate" | "stasis" | "buildTime" | "rank" | "matrix" | "speed"; + | "stim" | "ensnare" | "plague" | "lockdown" | "maelstrom" | "irradiate" | "stasis" | "buildTime" | "rank" | "matrix" | "speed" | "orderTargetX" | "orderTargetY"; /** The ones a program may write; the rest the game keeps for itself (a position write ends the game). */ export const UNIT_WRITABLE: ReadonlySet = new Set(["hp", "shields", "energy", "kills", "cooldown", "resources", "stim", "ensnare", "plague", "lockdown", "maelstrom", "irradiate", "stasis", "buildTime", "rank", "matrix", "invincible", "hallucinated", "speedUpgrade"]); -export const UNIT_NUM_FIELDS: readonly UnitNumField[] = ["hp", "maxHp", "shields", "maxShields", "energy", "owner", "type", "x", "y", "kills", "orderId", "cooldown", "resources", "stim", "ensnare", "plague", "lockdown", "maelstrom", "irradiate", "stasis", "buildTime", "rank", "matrix", "speed"]; +export const UNIT_NUM_FIELDS: readonly UnitNumField[] = ["hp", "maxHp", "shields", "maxShields", "energy", "owner", "type", "x", "y", "kills", "orderId", "cooldown", "resources", "stim", "ensnare", "plague", "lockdown", "maelstrom", "irradiate", "stasis", "buildTime", "rank", "matrix", "speed", "orderTargetX", "orderTargetY"]; /** A true / false of a unit on the map; `invincible`, `hallucinated` and `speedUpgrade` take a write. */ export type UnitFlag = "hallucinated" | "cloaked" | "burrowed" | "invincible" | "underAttack" | "speedUpgrade" | "hasTarget" | "inTransport"; export const UNIT_FLAGS: readonly UnitFlag[] = ["hallucinated", "cloaked", "burrowed", "invincible", "underAttack", "speedUpgrade", "hasTarget", "inTransport"]; @@ -248,7 +248,9 @@ export type UnitExpr = /** A call inlined here whose result is a unit. */ | { kind: "call"; call: Call } /** The unit in slot `index` of this computer's selection (`local.selected` is slot 0; B5), or none: a Local value. */ - | { kind: "selected"; index: number; at: At }; + | { kind: "selected"; index: number; at: At } + /** The unit `unit`'s order is aimed at (`u.orderTarget`), or none. */ + | { kind: "unitOrderTarget"; unit: UnitExpr; at: At }; /** What a unit is told to do. `to` and `target` are known when the script is built; an amount is the program's. */ export type UnitVerb = @@ -260,7 +262,9 @@ export type UnitVerb = /** Hit points down (at 0 the unit dies) or up (to the type's maximum), by points or by a percentage of the maximum. */ | { do: "damage" | "heal"; amount: NumExpr; percent: boolean } /** Centre a location on the unit, its size kept. */ - | { do: "locate"; location: number }; + | { do: "locate"; location: number } + /** A worker sent to mine a mineral field or harvest a gas building, as a right-click on it sends one. */ + | { do: "gather"; target: UnitExpr }; /** * One cell of the game's tables (`tables.ts`): `base + index × stride + key`, `width` bytes or one @@ -780,7 +784,7 @@ export function eachStart(root: unknown, visit: (s: Extract - e.kind === "unitNull" || e.kind === "unitVar" || e.kind === "pick" || e.kind === "unitAt" || (e.kind === "call" && e.call.result?.kind === "unit"); + e.kind === "unitNull" || e.kind === "unitVar" || e.kind === "pick" || e.kind === "unitAt" || e.kind === "unitOrderTarget" || (e.kind === "call" && e.call.result?.kind === "unit"); export const isNumExpr = (e: NumExpr | BoolExpr | UnitExpr | TextExpr): e is NumExpr => { switch (e.kind) { @@ -815,7 +819,7 @@ export function declarations(body: Stmt[]): VarDecl[] { case "textLoop": text(s.of); out.push(s.decl); s.body.forEach(stmt); break; case "unitLoop": out.push(s.decl); if (s.was) out.push(s.was); s.body.forEach(stmt); break; case "unitWrite": unit(s.unit); init(s.value); break; - case "unitDo": unit(s.unit); if (s.verb.do === "damage" || s.verb.do === "heal") expr(s.verb.amount); break; + case "unitDo": unit(s.unit); if (s.verb.do === "damage" || s.verb.do === "heal") expr(s.verb.amount); if (s.verb.do === "gather") unit(s.verb.target); break; case "select": s.units.forEach(unit); break; case "tableWrite": init(s.value); break; case "if": init(s.cond); s.then.forEach(stmt); s.else?.forEach(stmt); break; @@ -858,7 +862,7 @@ export function declarations(body: Stmt[]): VarDecl[] { default: break; } }; - const unit = (u: UnitExpr) => { if (u.kind === "call") call(u.call); else if (u.kind === "unitAt") { expr(u.ptr); expr(u.epd); expr(u.uid); } }; + const unit = (u: UnitExpr): void => { if (u.kind === "call") call(u.call); else if (u.kind === "unitAt") { expr(u.ptr); expr(u.epd); expr(u.uid); } else if (u.kind === "unitOrderTarget") unit(u.unit); }; const expr = (e: NumExpr) => { switch (e.kind) { case "unitField": case "unitPart": unit(e.unit); break; diff --git a/compiler/numbers.ts b/compiler/numbers.ts index d83c3b5..9c5bed2 100644 --- a/compiler/numbers.ts +++ b/compiler/numbers.ts @@ -380,7 +380,7 @@ export function typeNumbers(program: Program): ProgramDiagnostic[] { }; const texts: TextMap = { num: (e) => num(e)[0], bool: (e) => bool(e), call: (c) => { call(c); return c; }, text }; - const unit = (u: UnitExpr) => { if (u.kind === "call") call(u.call); else if (u.kind === "unitAt") { u.ptr = num(u.ptr)[0]; u.epd = num(u.epd)[0]; u.uid = num(u.uid)[0]; } }; + const unit = (u: UnitExpr): void => { if (u.kind === "call") call(u.call); else if (u.kind === "unitAt") { u.ptr = num(u.ptr)[0]; u.epd = num(u.epd)[0]; u.uid = num(u.uid)[0]; } else if (u.kind === "unitOrderTarget") unit(u.unit); }; /** * A value stored into a variable: a `u8` / `u16` takes nothing below zero, anything else keeps the 32 bits as they are. @@ -472,6 +472,7 @@ export function typeNumbers(program: Program): ProgramDiagnostic[] { case "unitDo": unit(s.unit); if (s.verb.do === "damage" || s.verb.do === "heal") s.verb.amount = floor(s.verb.amount, s.at); + if (s.verb.do === "gather") unit(s.verb.target); break; case "tableWrite": s.value = isTextExpr(s.value) ? text(s.value) : s.boolean ? bool(s.value as BoolExpr) : floor(s.value as NumExpr, s.at); diff --git a/compiler/orders.ts b/compiler/orders.ts index 5ec3b36..e9dcb1c 100644 --- a/compiler/orders.ts +++ b/compiler/orders.ts @@ -29,3 +29,11 @@ export const ORDER_NAMES: readonly string[] = [ /** The orders a unit is given by `u.order(…)` and the Order action: move, patrol, attack (an attack-move). */ export const ORDER_OF_VERB: Readonly> = { move: 6, patrol: 152, attack: 14 }; + +/** The workers `u.gather(…)` sends: SCV, Drone, Probe. */ +export const GATHER_WORKERS: readonly number[] = [7, 41, 64]; +/** What `u.gather(…)` makes a worker's order, by its target's type, as a right-click on it does: MoveToMinerals for a mineral field, MoveToGas for a gas building. */ +export const GATHER_ORDERS: readonly { order: number; targets: readonly number[] }[] = [ + { order: 85, targets: [176, 177, 178] }, + { order: 81, targets: [110, 149, 157] }, +]; diff --git a/compiler/ranges.ts b/compiler/ranges.ts index d694e6f..16b4928 100644 --- a/compiler/ranges.ts +++ b/compiler/ranges.ts @@ -339,6 +339,7 @@ export function rangeNumbers(program: Program): void { function unit(u: UnitExpr, facts: Facts): void { if (u.kind === "unitAt") { num(u.ptr, facts); num(u.epd, facts); num(u.uid, facts); } else if (u.kind === "call") call(u.call, new Map()); + else if (u.kind === "unitOrderTarget") unit(u.unit, facts); } /** @@ -435,7 +436,7 @@ export function rangeNumbers(program: Program): void { return; } case "unitWrite": unit(s.unit, facts); if (FLAGS.has(s.field)) bool(s.value as BoolExpr, facts); else num(s.value as NumExpr, facts); return; - case "unitDo": unit(s.unit, facts); if (s.verb.do === "damage" || s.verb.do === "heal") num(s.verb.amount, facts); return; + case "unitDo": unit(s.unit, facts); if (s.verb.do === "damage" || s.verb.do === "heal") num(s.verb.amount, facts); if (s.verb.do === "gather") unit(s.verb.target, facts); return; case "tableWrite": if (isTextExpr(s.value as { kind: string })) text(s.value as TextExpr, facts); else if (s.boolean) bool(s.value as BoolExpr, facts); else num(s.value as NumExpr, facts); return; case "if": { if (holdsCall(s.cond, callCache)) forget(facts); diff --git a/compiler/recursion.ts b/compiler/recursion.ts index cd81d5b..13d27f5 100644 --- a/compiler/recursion.ts +++ b/compiler/recursion.ts @@ -265,6 +265,7 @@ export function settleRecursion(program: Program): ProgramDiagnostic[] { return { ...e, left, right }; } case "intrinsic": return { ...e, args: operands(e.args.map((a) => ({ e: a, kind: "number" as const })), pre, w) as NumExpr[] }; + case "unitOrderTarget": return { ...e, unit: one(e.unit, "unit") as UnitExpr }; case "unitAt": { const [ptr, epd, uid] = operands([e.ptr, e.epd, e.uid].map((x) => ({ e: x, kind: "number" as const })), pre, w) as NumExpr[]; return { ...e, ptr, epd, uid }; @@ -320,9 +321,11 @@ export function settleRecursion(program: Program): ProgramDiagnostic[] { case "unitDo": { const items: { e: Expr; kind: Kind }[] = [{ e: s.unit, kind: "unit" }]; if (s.verb.do === "damage" || s.verb.do === "heal") items.push({ e: s.verb.amount, kind: "number" }); + if (s.verb.do === "gather") items.push({ e: s.verb.target, kind: "unit" }); const done = operands(items, pre, w); s.unit = done[0] as UnitExpr; if (s.verb.do === "damage" || s.verb.do === "heal") s.verb.amount = done[1] as NumExpr; + if (s.verb.do === "gather") s.verb.target = done[1] as UnitExpr; break; } case "tableWrite": s.value = isTextExpr(s.value) ? rewriteText(s.value, pre, w) : (value(s.value, s.boolean ? "boolean" : "number") as NumExpr | BoolExpr); break; diff --git a/compiler/simulateIr.ts b/compiler/simulateIr.ts index 509a8cb..3d5764e 100644 --- a/compiler/simulateIr.ts +++ b/compiler/simulateIr.ts @@ -40,7 +40,7 @@ import { fixedAtan2, fixedDiv, fixedMul, fixedSin, fixedSqrt, fixedText } from "./fixedMath"; import { ActionType, Comparison, ConditionType, SetModifier, SWITCH_COUNT, SwitchAction, SwitchState, type ActionRecord, type ConditionRecord } from "../vendor/triggers"; import { emptyAction, ResourceType } from "../vendor/triggers"; -import { ORDER_OF_VERB } from "./orders"; +import { GATHER_ORDERS, GATHER_WORKERS, ORDER_OF_VERB } from "./orders"; import { BUILD_BYTES, ERROR_CODES, HEAP_CELLS, HEAP_SMALLEST, STACK_DEPTH, STACK_OVERFLOW_MESSAGE, TEXT_BYTES, TEXT_FIELD_BYTES, UNIT_FLAGS, eachStart, heapCells, isTextExpr, programDeclarations, stackDepth } from "./ir"; import type { TextExpr, ArrayDecl, At, BoolExpr, Call, EventSource, NumExpr, Program, ReadSource, Stmt, TableCell, TextPart, UnitExpr, UnitFilter, UnitNumField, UnitVerb, VarDecl } from "./ir"; import { cellMax } from "./tables"; @@ -531,6 +531,7 @@ class ProgramRun { case "unitAt": { const ptr = (yield* this.num(e.ptr)) >>> 0; yield* this.num(e.epd); const uid = (yield* this.num(e.uid)) >>> 0; return ptr >= 1 ? this.sim.game.at(ptr - 1, uid) : null; } case "call": { yield* this.call(e.call); return e.call.result ? this.unitVars.get(e.call.result.decl.id) ?? null : null; } case "selected": return this.sim.selectedUnit(e.index); + case "unitOrderTarget": return (yield* this.living(e.unit))?.orderTarget ?? null; } } @@ -546,6 +547,7 @@ class ProgramRun { const u = yield* this.living(e); // The amount is computed whether or not there is a unit, as the game computes it. const amount = verb.do === "damage" || verb.do === "heal" ? yield* this.amount(verb.amount) : 0; + const target = verb.do === "gather" ? yield* this.living(verb.target) : null; if (!u) return; switch (verb.do) { case "kill": case "remove": this.sim.game.gone(u, verb.do === "kill", undefined, false); this.sim.unitEvent(this, verb.do === "kill" ? ActionType.KillUnit : ActionType.RemoveUnit, u, at); break; @@ -553,6 +555,13 @@ class ProgramRun { // (The unit takes up the order and keeps it here: the simulator moves nothing, so it never arrives.) case "order": u.orderId = ORDER_OF_VERB[verb.order]; this.sim.unitEvent(this, ActionType.Order, u, at, { location: verb.target, text: verb.order }); break; case "locate": this.sim.centre(verb.location, u.x, u.y); break; + // (The worker takes up the order and keeps it here: the simulator mines nothing.) + case "gather": { + if (!target || !GATHER_WORKERS.includes(u.type)) break; + const order = GATHER_ORDERS.find((g) => g.targets.includes(target.type))?.order; + if (order !== undefined) { u.orderId = order; u.orderTarget = target; } + break; + } case "damage": case "heal": { // In the game's own units, 256 to a point, as the lowering computes it. const step = verb.percent ? Math.floor((u.maxHp * 256 * amount) / 100) : amount * 256; diff --git a/compiler/structured.ts b/compiler/structured.ts index 5cfa250..b5cc09b 100644 --- a/compiler/structured.ts +++ b/compiler/structured.ts @@ -11643,6 +11643,10 @@ export class Structured { if (got && got.result?.kind !== "unit") { this.c.error(e, `${got.name ?? "This"} does not give a unit.`); return null; } return got ? this.mark({ kind: "call", call: got }, e) : null; } + if (ts.isPropertyAccessExpression(e) && ts.isIdentifier(e.name) && e.name.text === "orderTarget" && this.isUnitTyped(e.expression)) { + const of = this.unitExpr(e.expression); + return of ? this.mark({ kind: "unitOrderTarget", unit: of, at: this.at(e) }, e) : null; + } if (ts.isIdentifier(e) || ts.isPropertyAccessExpression(e) || ts.isElementAccessExpression(e)) { const kept = this.bindingOf(e); if (kept?.kind === "unitAt") return this.unitAtPlaces(kept, e); @@ -11772,6 +11776,13 @@ export class Structured { emit({ do: "locate", location: at }); return; } + case "gather": { + const a = e.arguments[0]; + if (!a || e.arguments.length > 1 || !this.isUnitTyped(a)) { this.c.error(e, "gather() takes the mineral field or gas building to gather from."); return; } + const target = this.unitExpr(a); + if (target) emit({ do: "gather", target }); + return; + } case "damage": case "heal": { const a = e.arguments[0]; if (!a || e.arguments.length > 1) { this.c.error(e, `${m.name}() takes hit points, or { percent: 50 } of the type's maximum.`); return; } diff --git a/compiler/world.ts b/compiler/world.ts index 16e691e..6e9f8af 100644 --- a/compiler/world.ts +++ b/compiler/world.ts @@ -30,7 +30,9 @@ export interface SimUnit { hp: number; maxHp: number; shields: number; maxShields: number; energy: number; kills: number; orderId: number; cooldown: number; resources: number; stim: number; ensnare: number; plague: number; lockdown: number; maelstrom: number; irradiate: number; stasis: number; - buildTime: number; rank: number; matrix: number; speed: number; + buildTime: number; rank: number; matrix: number; speed: number; orderTargetX: number; orderTargetY: number; + /** The unit its order is aimed at, if any. */ + orderTarget?: SimUnit; hallucinated: boolean; cloaked: boolean; burrowed: boolean; invincible: boolean; underAttack: boolean; speedUpgrade: boolean; hasTarget: boolean; inTransport: boolean; /** Still on the map. */ alive: boolean; @@ -162,7 +164,7 @@ export class World { const shields = init.shields ?? init.maxShields ?? 0; const unit: SimUnit = { x: 0, y: 0, energy: 0, kills: 0, orderId: 3, cooldown: 0, resources: 0, - stim: 0, ensnare: 0, plague: 0, lockdown: 0, maelstrom: 0, irradiate: 0, stasis: 0, buildTime: 0, rank: 0, matrix: 0, speed: 0, + stim: 0, ensnare: 0, plague: 0, lockdown: 0, maelstrom: 0, irradiate: 0, stasis: 0, buildTime: 0, rank: 0, matrix: 0, speed: 0, orderTargetX: 0, orderTargetY: 0, hallucinated: false, cloaked: false, burrowed: false, invincible: false, underAttack: false, speedUpgrade: false, hasTarget: false, inTransport: false, ...init, hp, maxHp: init.maxHp ?? hp, shields, maxShields: init.maxShields ?? shields, alive: true, slot, uid, }; diff --git a/docs/ir.md b/docs/ir.md index 335bd1e..6793796 100644 --- a/docs/ir.md +++ b/docs/ir.md @@ -187,7 +187,7 @@ frame's `saves`, and a `slice` is never declared. | `assignUnit` | `target`, `value` | `target = value` for a unit variable. | | `unitLoop` | `decl`, `filter`, `source?`, `was?`, `event?`, `body` | `for (const u of unitsAt(…))`: the body once for every unit the filter matches, oldest first — the game's unit table from slot 0 and then from 1699 downwards, stopping once every unit in use has been met — within the frame (the compiler refuses a `sleep` inside). `decl` is the unit of the turn; `break` and `continue` are the loop's. With `source` (`on.created` / `on.died`, since version 18; `killed`, `ordered`, `morphed` since 19) the units are this frame's events pass's instead, `was` a number variable set at each turn and `event` a filter of the event's own (*Events*, below). | | `unitWrite` | `unit`, `field`, `value` | `u.hp = 40`, `u.invincible = true`. Nothing happens when the unit is none or gone. Hit points at 0 kill. | -| `unitDo` | `unit`, `verb` | `{ do: "kill" }`, `{ do: "remove" }`, `{ do: "give", to }`, `{ do: "order", order, target }` (a location), `{ do: "damage" \| "heal", amount, percent }`, `{ do: "locate", location }`. Nothing happens when the unit is none or gone; an amount is evaluated either way. | +| `unitDo` | `unit`, `verb` | `{ do: "kill" }`, `{ do: "remove" }`, `{ do: "give", to }`, `{ do: "order", order, target }` (a location), `{ do: "damage" \| "heal", amount, percent }`, `{ do: "locate", location }`, `{ do: "gather", target }` (an SCV, Drone or Probe sent to a mineral field or a gas building: the order MoveToMinerals or MoveToGas, its state 0 and its target written; anything else either way round is left alone). Nothing happens when the unit is none or gone; an amount is evaluated either way. | | `tableWrite` | `cell`, `value`, `scaled?`, `boolean?` | A cell of the game's tables. `value` is a number expression, a boolean one (`boolean`), or `{ kind: "text", text }` for a name. `scaled`: the number is already what the cell stores. | | `if` | `cond`, `then`, `else?` | As it reads. | | `while` | `cond?`, `body` | `cond` absent means `while (true)`, or a condition known true when the script was built. | @@ -652,6 +652,7 @@ Units (`UnitExpr`): | `pick` | `by: first | nearest | random`, `filter`, `near?`, `mouse?`, `within?` — one of the units the filter matches: the first in that order (the oldest), the nearest to the centre of location `near` by \|dx\| + \|dy\| (the first of equals), or one drawn at random; none when nothing matches. With `mouse` (a player: a slot, or 13) in place of `near`, the nearest to that player's mouse and no farther from it than `within` pixels | | `call` | `call` whose result is a unit | | `selected` | `index` — the unit in that slot of this computer's selection (0 is the one the panel shows), or none. Differs from one computer to the next. Since version 23 | +| `unitOrderTarget` | `unit` — the unit `unit`'s order is aimed at (the one it follows, attacks or mines), or none when the order is aimed at a place or at nothing | ``` UnitFilter { type?, owner?, at? } @@ -662,7 +663,7 @@ flags, as a trigger counts them); `owner` a slot or 13; `at` a 1-based location holds the unit's centre, edges included. An absent part matches all, and a unit that is dying matches nothing. Number fields: `hp` (whole points, a started point counting, as the game shows it), `maxHp`, `shields`, `maxShields`, `energy`, `owner`, `type`, `x`, `y`, -`kills`, `orderId`, `cooldown`, `resources`, and the timers `stim` `ensnare` `plague` +`kills`, `orderId`, `orderTargetX`, `orderTargetY` (where the order is aimed, in pixels), `cooldown`, `resources`, and the timers `stim` `ensnare` `plague` `lockdown` `maelstrom` `irradiate` `stasis`. A written value stops at what the game's cell holds: 255 for a byte (kills, cooldown, timers, energy points), 65 535 for resources, 2²⁴ − 1 hit points. diff --git a/ledger/units/unit-gather.ts b/ledger/units/unit-gather.ts new file mode 100644 index 0000000..fa864d0 --- /dev/null +++ b/ledger/units/unit-gather.ts @@ -0,0 +1,6 @@ +// ledger: step 10, takes +// A worker sent to mine a mineral field, as a right-click on it sends one: `scv.gather(field)`. +program(() => { + const field = first({ type: units.MineralFieldType1 }); + if (field) first({ owner: P1, type: units.TerranSCV })?.gather(field); +}); diff --git a/ledger/units/unit-order-target-position-read.ts b/ledger/units/unit-order-target-position-read.ts new file mode 100644 index 0000000..e32996d --- /dev/null +++ b/ledger/units/unit-order-target-position-read.ts @@ -0,0 +1,6 @@ +// ledger: step 10, takes +// Where a unit's order is aimed, in pixels: `u.orderTargetX`, `u.orderTargetY`. +program(() => { + const u = first({ owner: P1 }); + if (u) print(`going to ${u.orderTargetX},${u.orderTargetY}`); +}); diff --git a/ledger/units/unit-order-target-read.ts b/ledger/units/unit-order-target-read.ts new file mode 100644 index 0000000..c0169c3 --- /dev/null +++ b/ledger/units/unit-order-target-read.ts @@ -0,0 +1,9 @@ +// ledger: step 10, takes +// The unit a unit's order is aimed at, or none: `u.orderTarget`. +program(() => { + const u = first({ owner: P1 }); + if (u) { + const aimed = u.orderTarget; + if (aimed) print(`aimed at a unit of type ${aimed.type}`); + } +}); diff --git a/ledger/units/workers-auto-mining.ts b/ledger/units/workers-auto-mining.ts new file mode 100644 index 0000000..e3ebf41 --- /dev/null +++ b/ledger/units/workers-auto-mining.ts @@ -0,0 +1,4 @@ +// ledger: step 10, takes +// trigscript/workers: a human player's new worker rallied to a mineral patch or its own gas building gathers from it: `buildAutoMiningProgram()` at the top of a script. +import { buildAutoMiningProgram } from "trigscript/workers"; +buildAutoMiningProgram(); diff --git a/stdlib/workers.ts b/stdlib/workers.ts new file mode 100644 index 0000000..cd28ff1 --- /dev/null +++ b/stdlib/workers.ts @@ -0,0 +1,71 @@ +/** + * Workers that go to work: the standard library's "trigscript/workers" (TrigScript 4). + * + * import { buildAutoMiningProgram } from "trigscript/workers"; + * + * buildAutoMiningProgram(); // at the top of the script, once: on for the whole game + * + * With auto-mining on, a human player's new SCV, Probe or Drone whose producer's rally point is on a mineral patch + * starts mining that patch, instead of walking there and standing. One rallied to the player's own finished gas + * building (Refinery, Extractor, Assimilator) starts gathering gas from it. Anywhere else — the ground, a bare geyser, + * a gas building still being built or another player's, a patch mined out — it walks to the rally point as it always + * does. It acts once, as the worker comes out: an order the player gives afterwards stands. Computer players' workers + * and those a trigger makes (Create Unit) are left alone, and a busy patch or gas building is the game's to sort out, + * as when the player right-clicks it. + * + * Played in StarCraft: Remastered (2026-11-07 and 2026-11-08): SCVs, Probes and Drones rallied to minerals and to gas + * all went to work. How it sees a new worker, from `map trace` (2026-11-07): an SCV comes out of training with its + * order changing from Nothing, and a Drone from ZergBirth, on the frame the rally is applied (a Probe was not traced; + * in play it went to work as an SCV does). A rally on a patch gives the worker Move to the patch's exact centre with no target; one on a building gives + * Follow with the building as the target. `gather()` then gives the order a right-click would: MoveToMinerals or + * MoveToGas. + */ +import { program, on, isHuman, allUnits, units, orders, P1, P2, P3, P4, P5, P6, P7, P8, type Unit } from "trigscript"; + +function ownerIsHuman(worker: Unit): boolean { + const owner = worker.owner; + if (owner == P1) return isHuman(P1); + if (owner == P2) return isHuman(P2); + if (owner == P3) return isHuman(P3); + if (owner == P4) return isHuman(P4); + if (owner == P5) return isHuman(P5); + if (owner == P6) return isHuman(P6); + if (owner == P7) return isHuman(P7); + if (owner == P8) return isHuman(P8); + return false; +} + +function gatherFromRally(worker: Unit) { + if (!ownerIsHuman(worker)) return; + if (worker.orderId == orders.Follow) { + const gasBuilding = worker.orderTarget; + if (gasBuilding) if (gasBuilding.owner == worker.owner && gasBuilding.buildTime == 0) worker.gather(gasBuilding); + return; + } + if (worker.orderId != orders.Move || worker.hasTarget) return; + const x = worker.orderTargetX, y = worker.orderTargetY; + for (const patch of allUnits({ type: units.MineralFieldType1 })) if (patch.x == x && patch.y == y) { worker.gather(patch); return; } + for (const patch of allUnits({ type: units.MineralFieldType2 })) if (patch.x == x && patch.y == y) { worker.gather(patch); return; } + for (const patch of allUnits({ type: units.MineralFieldType3 })) if (patch.x == x && patch.y == y) { worker.gather(patch); return; } +} + +let programBuilt = false; + +/** + * Build the program that turns auto-mining on for the whole game: every human player's new SCV, Probe or Drone rallied + * to a mineral patch or the player's own finished gas building starts gathering from it. Called at the top of a + * script, as programs are made when the map is built; a call after the first adds nothing. + */ +export function buildAutoMiningProgram() { + if (programBuilt) return; + programBuilt = true; + program(async () => { + on.order((worker, order, was) => { + if (worker.type == units.ZergDrone) { + if (was == orders.ZergBirth) gatherFromRally(worker); + } else if (was == orders.Nothing) { + if (worker.type == units.TerranSCV || worker.type == units.ProtossProbe) gatherFromRally(worker); + } + }); + }); +} diff --git a/tests/emitter.test.ts b/tests/emitter.test.ts index a849311..59ba437 100644 --- a/tests/emitter.test.ts +++ b/tests/emitter.test.ts @@ -1481,6 +1481,8 @@ describe("a map of our own, units", () => { put(at + 0xa2, (u.energy ?? 0) * 256, 2); put(at + 0x38, u.speed ?? 0); put(at + 0x5c, u.hasTarget ? 0x700000 + 4 : 0); + put(at + 0x58, u.orderTargetX ?? 0, 2); + put(at + 0x5a, u.orderTargetY ?? 0, 2); put(at + 0x8e, u.rank ?? 0, 1); if (u.underAttack) put(at + 0x87, 12, 1); put(at + 0xac, u.buildTime ?? 0, 2); @@ -1605,6 +1607,65 @@ describe("a map of our own, units", () => { ].join("\n"), units, HOME); }); + describe("gather()", () => { + const place = (slot: number) => TABLE + 336 * slot; + // Places 0, 1 699, 1 698 …: a mineral field, an SCV moving onto its centre, a Refinery, a Probe following it, a Marine. + const GATHERING: SimUnitInit[] = [ + { type: 176, owner: 11, x: 200, y: 100, hp: 100000, maxHp: 100000 }, + { type: 7, owner: 0, x: 100, y: 100, hp: 60, maxHp: 60, orderId: 6, orderTargetX: 200, orderTargetY: 100 }, + { type: 110, owner: 0, x: 400, y: 100, hp: 750, maxHp: 750 }, + { type: 64, owner: 0, x: 400, y: 150, hp: 20, maxHp: 20, orderId: 49 }, + { type: 0, owner: 0, x: 500, y: 150, hp: 40, maxHp: 40 }, + ]; + const SCRIPT = [ + " const scv = first({ type: units.TerranSCV })!;", + " const probe = first({ type: units.ProtossProbe })!;", + " const marine = first({ type: units.TerranMarine })!;", + " const refinery = first({ type: units.TerranRefinery })!;", + " for (const m of allUnits({ type: units.MineralFieldType1 })) if (m.x == scv.orderTargetX && m.y == scv.orderTargetY) scv.gather(m);", + " probe.gather(refinery);", + " marine.gather(refinery);", + " scv.gather(marine);", + " print(`${scv.orderId} ${probe.orderId} ${marine.orderId} ${scv.orderTarget == first({ type: units.MineralFieldType1 })} ${probe.orderTarget == refinery}`);", + ].join("\n"); + + it("is MoveToMinerals at a mineral field and MoveToGas at a gas building, in the simulator as in the game", () => { + same(SCRIPT, GATHERING); + }); + + it("writes the order target, the order state and the order, and leaves anything but a worker alone", () => { + const r = compileScript(ts, { "main.ts": `program(() => {\n${SCRIPT}\n});\n` }, defaultScriptNames(), { lib: defaultLib() }); + expect(r.diagnostics).toEqual([]); + const o = emitOwn(r); + if (typeof o === "string") throw new Error(o); + const memory = memoryOf(GATHERING, {}); + // (A state the game had moved on from, which the order is to start again.) + for (const slot of [1699, 1697]) memory.set(place(slot) + 0x4c, (memory.get(place(slot) + 0x4c)! | 0x00030000) >>> 0); + const marineWord = memory.get(place(1696) + 0x4c); + // (The game's memory as the first frame left it, read before the second frame runs.) + const after = new Map(); + runOwn(o.runs[0].graph, memory, o.values, undefined, 2, (frame, _write, read) => { + if (frame === 2) for (const slot of [1699, 1697, 1696]) for (const offset of [0x4c, 0x5c]) after.set(place(slot) + offset, read(place(slot) + offset)); + }); + const dword = (slot: number, offset: number) => after.get(place(slot) + offset) ?? 0; + expect([(dword(1699, 0x4c) >>> 8) & 0xff, (dword(1699, 0x4c) >>> 16) & 0xff, dword(1699, 0x5c)]).toEqual([85, 0, place(0)]); + expect([(dword(1697, 0x4c) >>> 8) & 0xff, (dword(1697, 0x4c) >>> 16) & 0xff, dword(1697, 0x5c)]).toEqual([81, 0, place(1698)]); + expect([dword(1696, 0x4c), dword(1696, 0x5c)]).toEqual([marineWord, 0]); + }); + + it("reads the unit a Follow is aimed at", () => { + const r = compileScript(ts, { "main.ts": "program(() => {\n const probe = first({ type: units.ProtossProbe })!;\n const t = probe.orderTarget;\n if (t && t.type == units.TerranRefinery && t.owner == probe.owner && t.buildTime == 0) print(`aimed at ${t.x}`);\n if (!first({ type: units.TerranSCV })!.orderTarget) print(\"none\");\n});\n" }, defaultScriptNames(), { lib: defaultLib() }); + expect(r.diagnostics).toEqual([]); + const o = emitOwn(r); + if (typeof o === "string") throw new Error(o); + const memory = memoryOf(GATHERING, {}); + memory.set(place(1697) + 0x5c, place(1698)); + PRINTED.got = []; + runOwn(o.runs[0].graph, memory, o.values); + expect(PRINTED.got).toEqual(["aimed at 400", "none"].map((text) => shown([...new TextEncoder().encode(text)]))); + }); + }); + it("reads a location's bounds and moves one edge at a time", () => { same([ " const b = bounds(1 as Location);", diff --git a/tests/stdlib.test.ts b/tests/stdlib.test.ts index 5d784de..12f28f1 100644 --- a/tests/stdlib.test.ts +++ b/tests/stdlib.test.ts @@ -1,7 +1,8 @@ /** * The standard library (TrigScript 4): modules of TrigScript shipped with the compiler and imported as * "trigscript/" — fog first. What joins a script's files and when, the location a library reserves, and what the - * fog's functions compile to: a picture's brushes, read back out of the IR, light the picture's tiles. + * fog's functions compile to: a picture's brushes, read back out of the IR, light the picture's tiles. Workers' + * buildAutoMiningProgram(). */ import { readdirSync, readFileSync } from "node:fs"; import { join } from "node:path"; @@ -12,7 +13,7 @@ import { defaultScriptNames, type ScriptNames } from "../compiler/names"; import { defaultLib } from "../bundle/lib.mjs"; import { STDLIB_SOURCES } from "../compiler/generated/stdlib"; import { stdlibImports } from "../compiler/stdlib"; -import type { Program, Stmt } from "../compiler/ir"; +import { bodiesOf, type Program, type Stmt } from "../compiler/ir"; import { ProgramSimulation } from "../compiler/simulateIr"; const LIB = defaultLib(); @@ -285,3 +286,36 @@ program(async () => { const hs: number[] = [80]; const sh: number[] = [1]; while expect(column).toBe(Array.from({ length: 96 }, (_, y) => (lit.has(y) ? "#" : ".")).join("")); }); }); + +describe("trigscript/workers", () => { + const IMPORTED = `import { buildAutoMiningProgram } from "trigscript/workers";\n`; + + it("buildAutoMiningProgram() at the top of a script is the library's program: a listener for new orders that gives the gather order", () => { + const r = ok(`${IMPORTED}buildAutoMiningProgram();`); + expect(r.ir.map((p) => p.at?.file)).toEqual(["__trigscript__/workers.ts"]); + const statements = bodiesOf(r.ir[0]).flatMap((body) => walk(body)); + expect(statements.some((s) => s.kind === "unitLoop" && s.source === "ordered")).toBe(true); + expect(statements.some((s) => s.kind === "unitDo" && s.verb.do === "gather")).toBe(true); + }); + + it("imported and not called, it adds nothing", () => { + expect(ok(`${IMPORTED}program(() => {});`).ir.map((p) => p.at?.file)).toEqual(["main.ts"]); + }); + + it("stands beside the script's own on.order() listeners", () => { + const r = ok(`${IMPORTED}buildAutoMiningProgram();\non.order((u, order) => { if (order == orders.Move) print("moved"); });\nprogram(async () => { on.order((u) => { print("ordered"); }); });`); + expect(r.ir.map((p) => p.at?.file)).toEqual(["__trigscript__/workers.ts", "main.ts", "main.ts"]); + }); + + it("called again, in the same file or another, it adds nothing", () => { + expect(ok(`${IMPORTED}buildAutoMiningProgram();\nbuildAutoMiningProgram();`).ir.map((p) => p.at?.file)).toEqual(["__trigscript__/workers.ts"]); + const r = compileScript(ts, { "main.ts": `${IMPORTED}import "./more";\nbuildAutoMiningProgram();`, "more.ts": `${IMPORTED}buildAutoMiningProgram();` }, NAMES, { lib: LIB }); + expect(r.diagnostics).toEqual([]); + expect(r.ir.map((p) => p.at?.file)).toEqual(["__trigscript__/workers.ts"]); + }); + + it("is on again in the next build", () => { + ok(`${IMPORTED}buildAutoMiningProgram();`); + expect(ok(`${IMPORTED}buildAutoMiningProgram();`).ir.map((p) => p.at?.file)).toEqual(["__trigscript__/workers.ts"]); + }); +});