Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions compiler/backend/units.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,11 @@ const ATTACKED = word(0x87, 1);
const FLARED = word(0x123, 1);
/** The status bits a flag is (cloaked: both of two). */
const FLAG_BITS: Partial<Record<UnitFlag, number>> = { invincible: 0x04000000, hallucinated: 0x40000000, burrowed: 0x10, cloaked: 0x300, speedUpgrade: 0x10000000, inTransport: 0x40 };
/**
* Burrowed, or loaded in a transport or a Bunker: a unit the player has no command for. `gather()`, `cast()` and
* `stop()` write an order into the unit past everything a command checks, so they leave such a unit as it is.
*/
const TAKES_NO_ORDER = 0x10 | 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 most a field written holds, as the simulator stops it: points for hit points and shields, a byte, a word. */
Expand Down Expand Up @@ -832,10 +837,12 @@ export function unitValues(program: Program, events?: { sources: Set<EventSource
const e = u.e;
const body: Stmt[] = [];
const is = (id: string, types: readonly number[]) => any(types.map((type) => cmp("==", ranged(V(id), 0, 0xffff), k(type))));
/** Neither burrowed nor loaded: the unit may be handed an order (`TAKES_NO_ORDER`). */
const free = (): BoolExpr => cmp("==", peek(of(e, STATUS), TAKES_NO_ORDER), k(0));
switch (v.do) {
case "kill": body.push(die(e)); break;
// (The order and its state share a dword: both written at once, the state back to the start.)
case "stop": body.push(poke(of(e, ORDER.dword), k(STOP_ORDER * 2 ** ORDER.shift), (ORDER.mask | ORDER_STATE.mask) >>> 0)); break;
case "stop": body.push(...when(free(), [poke(of(e, ORDER.dword), k(STOP_ORDER * 2 ** ORDER.shift), (ORDER.mask | ORDER_STATE.mask) >>> 0)])); break;
// (eudplib's `CUnit.remove()`: the unit leaves without dying.)
case "remove": body.push(poke(of(e, USER_ACTION.dword), k(4 * 2 ** USER_ACTION.shift), USER_ACTION.mask), die(e)); break;
case "locate": {
Expand Down Expand Up @@ -893,7 +900,7 @@ export function unitValues(program: Program, events?: { sources: Set<EventSource
if (!target || isNone(target)) break;
const worker = fresh("ty"), aimed = fresh("ty"), order = fresh("order");
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)]), [
body.push(...when(all([is(worker, GATHER_WORKERS), free(), alive(target)]), [
...readInto(aimed, target.e, TYPE),
...GATHER_ORDERS.flatMap((g) => when(is(aimed, g.targets), [set(order, k(g.order))])),
]));
Expand All @@ -910,7 +917,7 @@ export function unitValues(program: Program, events?: { sources: Set<EventSource
if (!spell || !target || isNone(target)) break;
const caster = fresh("ty");
body.push(dec(caster, k(0), 0xffff), ...readInto(caster, e, TYPE));
body.push(...when(all([is(caster, spell.casters), alive(target)]), [
body.push(...when(all([is(caster, spell.casters), free(), alive(target)]), [
poke(of(e, ORDER_TARGET), bin("+", bin("*", target.e, k(4)), k(DEATHS))),
poke(of(e, ORDER.dword), k(spell.order * 2 ** ORDER.shift), (ORDER.mask | ORDER_STATE.mask) >>> 0),
]));
Expand Down
17 changes: 11 additions & 6 deletions compiler/declarations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,17 +217,22 @@ ${kw}interface Unit {
/** 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.
* Send an SCV, Probe or Drone to mine a mineral field or harvest a Refinery, Extractor or Assimilator: the order a
* right-click on it gives. The order is written into the worker, with no command sent, so nothing a command checks is
* checked. A worker that is burrowed or loaded in a transport is left as it is, and so is anything else, either way round.
*/
gather(target: Unit): void;
/**
* Cast a spell at a unit, as a player's command does: \`medic.cast(techs.Restoration, marine)\`. Restoration is the one
* spell so far, cast by a Medic; any other technology is an error when the script is built. Nothing checks the
* research or the energy: the game drops a cast it has no energy for, and walks the caster into range.
* Cast a spell at a unit: \`medic.cast(techs.Restoration, marine)\`, the order a player's command gives. Restoration is
* the one spell so far, cast by a Medic; any other technology is an error when the script is built. The order is
* written into the caster, with no command sent: nothing checks the research or the energy (the game drops a cast it
* has no energy for, and walks the caster into range), and a caster loaded in a transport or a Bunker is left as it is.
*/
cast(tech: Tech, target: Unit): void;
/** Stop, as the Stop button does: the unit gives up its order where it stands and takes up the next one it has queued, or stands idle. */
/**
* Stop: the order the Stop button gives. The unit gives up its order where it stands and takes up the next one it has
* queued, or stands idle. A unit that is burrowed or loaded in a transport is left as it is.
*/
stop(): void;
/**
* How far apart two units are, in pixels, as the game measures a weapon's or a spell's range: from the edge of one's
Expand Down
14 changes: 12 additions & 2 deletions compiler/gameSim.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,8 +164,10 @@ class GameUnit implements SimUnit {
private readonly at: number;
private last: Partial<SimUnit> = {};
private readonly game: GameHandle;
constructor(game: GameHandle, slot: number) {
private readonly unitOf: (slot: number) => SimUnit;
constructor(game: GameHandle, slot: number, unitOf: (slot: number) => SimUnit) {
this.game = game;
this.unitOf = unitOf;
this.slot = slot;
this.at = UNITS + UNIT_BYTES * slot;
this.uid = game.u8[this.at + 0xa5];
Expand Down Expand Up @@ -205,6 +207,14 @@ 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)); }
/** The unit the order is aimed at: the pointer `hasTarget` reads, to a slot of the unit table. None once this unit is gone. */
get orderTarget(): SimUnit | undefined {
if (!this.alive) return undefined;
const slot = (this.m.getUint32(this.at + 0x5c, true) - UNITS) / UNIT_BYTES;
if (!Number.isInteger(slot) || slot < 0 || slot >= UNIT_COUNT) return undefined;
const target = this.unitOf(slot);
return target.alive ? target : undefined;
}
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)); }
get orderState() { return this.read("orderState", () => this.game.u8[this.at + 0x4e]); }
Expand Down Expand Up @@ -302,7 +312,7 @@ export class GameSim implements TestWorldLike {
const u8 = this.game.u8, uid = u8[UNITS + UNIT_BYTES * slot + 0xa5];
const was = this.units_.get(slot);
if (was && was.uid === uid) return was;
const u = new GameUnit(this.game, slot);
const u = new GameUnit(this.game, slot, (other) => this.unit(other));
this.units_.set(slot, u);
return u;
}
Expand Down
7 changes: 3 additions & 4 deletions compiler/generated/stdlib.ts

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions compiler/simulateIr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -557,19 +557,19 @@ class ProgramRun {
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;
if (!target || !GATHER_WORKERS.includes(u.type) || u.burrowed || u.inTransport) break;
const order = GATHER_ORDERS.find((g) => g.targets.includes(target.type))?.order;
if (order !== undefined) { u.orderId = order; u.orderTarget = target; }
break;
}
// (The caster takes up the order and keeps it here: the simulator casts nothing.)
case "cast": {
const spell = CAST_ORDERS.find((c) => c.tech === verb.tech);
if (!target || !spell?.casters.includes(u.type)) break;
if (!target || !spell?.casters.includes(u.type) || u.burrowed || u.inTransport) break;
u.orderId = spell.order; u.orderState = 0; u.orderTarget = target;
break;
}
case "stop": u.orderId = STOP_ORDER; u.orderState = 0; u.orderTarget = undefined; break;
case "stop": if (u.burrowed || u.inTransport) break; u.orderId = STOP_ORDER; u.orderState = 0; u.orderTarget = undefined; 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;
Expand Down
2 changes: 1 addition & 1 deletion docs/ir.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 }`, `{ 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), `{ do: "cast", tech, target }` (a spell at a unit: for Restoration, a Medic's CastRestoration, its state 0 and its target written; a caster of another type or a target gone is left alone), `{ do: "stop" }` (the order Stop, its state 0). 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), `{ do: "cast", tech, target }` (a spell at a unit: for Restoration, a Medic's CastRestoration, its state 0 and its target written; a caster of another type or a target gone is left alone), `{ do: "stop" }` (the order Stop, its state 0). These three write the order into the unit, so a unit that is burrowed or loaded (status bits 0x10 and 0x40), which the player has no command for, 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. |
Expand Down
38 changes: 38 additions & 0 deletions docs/v4-plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -7049,6 +7049,44 @@ case, never `trigscript`). A script imports `"<id>/<module>"`, or `"<id>"` for `
- *Libraries without a plugin* (a GitHub folder of `.ts` files read the same way as the map's copy): not started.
- *scm-js*: the guide's TrigScript page and `docs/plugins.md` say nothing of libraries until a release pins this.

## Workers, spells and a unit's orders (built 2026-11-11 to 14)

A contributor's work (mstephenhunt, PR #96, with issues #91 and #94), merged as it was and then changed in a
follow-up on `library-names-and-guards`.

- *Language:* `u.orderTarget` (a unit or null), `u.orderTargetX` / `orderTargetY`, `u.orderState`, `u.queuedOrders`,
`u.acidSpores`, `u.opticalFlare`, `a.distanceTo(b)` (the game's `units_distance`: the gap between the two boxes,
made one length by `xy_length`), `stats(P).allied[Q]`; the verbs `u.gather(target)` (MoveToMinerals / MoveToGas),
`u.cast(techs.Restoration, target)` and `u.stop()`. The three verbs write the order, its state and its target into
the unit; no command is sent. They leave a burrowed or loaded unit as it is (status bits 0x10 and 0x40).
- *Libraries:* `trigscript/workers` `autoMining()` (a new worker rallied to a mineral field or its player's finished gas
building gathers from it) and `trigscript/spells` `autoRestore({ switch, keepEnergy })` (an idle Medic casts
Restoration on the nearest afflicted friendly unit in range). Each makes a program, so each is called at the top of a
script; inside a program it is the error #90 added.
- *Fixes:* `stats(P).researched` and `.upgrades` read Brood War's own rows (`0x58F140` by 20 from tech 24, `0x58F32C`
by 15 from upgrade 46); before, `stats(P1).researched[techs.Restoration]` was Player 2's Stim Packs. The simulator's
camera moves on Center View; `TestWorld.mapSize`.
- *Local reads:* `local.mouse.buttons`, `local.card.buttonSet`, `local.screen.width`.

**Open:**
- *`trigscript/card` and auto-restore's right-click toggle* are on the `card-right-click` branch, not on main. The
card library finds which graphics are on by sending the view to the map's middle and back at the start, and its
button positions were measured on one Mac. Before it comes back: play it on Windows, on a 4:3 and an ultrawide
display, and on a map that is not square (the minimap check is for square maps only); with two people playing,
each player's copy of the program handles every human's Medics, so one player's "off" does not hold; importing
`trigscript/spells` reserved the card's location even with the toggle off.
- *Not played in Remastered yet:* `autoMining()` as the library (the same logic was played as a map's own script);
the Brood War rows of `researched` and `upgrades`, read and written in a game; the auto-restore test map; the three
verbs on a burrowed or loaded unit (the guard has emitter tests only).
- *A unit in stasis, under Lockdown or Maelstrom* is still written to by the three verbs. Expected, not traced: the
game runs no orders for it, so the order waits until the unit wakes. `autoRestore()` passes over such a Medic.
- *Workers and casters are fixed types:* SCV, Drone, Probe; Medic. The game takes a worker from its units.dat flag, so
a mod's own worker gets nothing from `gather()` or `autoMining()`. Proposed: read the flag.
- *`cast()` is Restoration only:* every other technology is an error when the script is built.
- *The simulator's `local.card.buttonSet`* is the selection's type, which is the game's number for most units, not all.
- *scm-js:* the guides (PR #233 there) wait on a release with this; the command line's build does not pass `mapSize`
to the test world yet, so its simulator takes a map to be 128 by 128.

## Work outside this repository

- **scm-sim:** the EUD-permitting module build (A0); the trigger hooks (A1); `run(…)` with
Expand Down
16 changes: 0 additions & 16 deletions ledger/units/card-right-click.ts

This file was deleted.

4 changes: 0 additions & 4 deletions ledger/units/spells-auto-restore-toggle.ts

This file was deleted.

6 changes: 3 additions & 3 deletions ledger/units/spells-auto-restore.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// ledger: step 10, takes
// trigscript/spells: a human player's idle Medic restores the nearest afflicted unit of its owner's or an ally's in range: `buildAutoRestoreProgram()` at the top of a script.
import { buildAutoRestoreProgram } from "trigscript/spells";
buildAutoRestoreProgram();
// trigscript/spells: a human player's idle Medic restores the nearest afflicted unit of its owner's or an ally's in range: `autoRestore()` at the top of a script.
import { autoRestore } from "trigscript/spells";
autoRestore();
6 changes: 3 additions & 3 deletions ledger/units/workers-auto-mining.ts
Original file line number Diff line number Diff line change
@@ -1,4 +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();
// trigscript/workers: a human player's new worker rallied to a mineral patch or its own gas building gathers from it: `autoMining()` at the top of a script.
import { autoMining } from "trigscript/workers";
autoMining();
Loading
Loading