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
7 changes: 4 additions & 3 deletions compiler/backend/emit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -230,8 +230,9 @@ export function unlowered(s: Stmt, decls: Map<string, VarDecl>, arrays: Map<stri
case "unitPart": return "a unit's place in the game's memory";
case "unitAlive": return "whether a unit is alive";
case "unitSame": return "two units compared";
case "unitDistance": return "how far apart two units are";
case "unitFlag": return `a unit's flag ${o.flag as string}`;
case "unitNull": case "unitVar": case "pick": case "unitAt": case "selected": return "a unit";
case "unitNull": case "unitVar": case "pick": case "unitAt": case "selected": case "unitOrderTarget": return "a unit";
case "textLength": return "a text's length";
case "textIndexOf": return "a search in a text";
case "textCode": return "a character's code";
Expand Down Expand Up @@ -318,7 +319,7 @@ export function unlowered(s: Stmt, decls: Map<string, VarDecl>, arrays: Map<stri
}

/** What is read of a unit, and what is done to a text: named before the unit or the text it is done to. */
const UNIT_READS = new Set(["unitField", "unitFlag", "unitAlive", "unitSame", "unitPart", "textLength", "textIndexOf", "textCode", "textCompare", "textTest", "textSlice", "textPad", "textRepeat", "textTernary", "textCall"]);
const UNIT_READS = new Set(["unitField", "unitDistance", "unitFlag", "unitAlive", "unitSame", "unitPart", "textLength", "textIndexOf", "textCode", "textCompare", "textTest", "textSlice", "textPad", "textRepeat", "textTernary", "textCall"]);
/** The methods of a text the front end writes as functions of its own (`textCall`). */
const TEXT_METHODS = new Set(["toUpperCase", "toLowerCase", "toLocaleUpperCase", "toLocaleLowerCase", "trim", "trimStart", "trimEnd", "replace", "replaceAll", "split", "join", "at", "charAt", "concat", "parseInt", "Number"]);
/** Set Deaths, which `setMemory()` is when its player is past the groups (26). */
Expand Down Expand Up @@ -4999,7 +5000,7 @@ class Rewriter {
const o = x as Record<string, unknown>;
if (o.kind === "var" && typeof o.id === "string" && (h.written.has(o.id) || isTemp(o.id))) pure = false;
if (o.kind === "element" && h.arrays.has(o.array as string)) pure = false;
if (o.kind === "call" || o.kind === "read" || o.kind === "randomInt" || o.kind === "input" || o.kind === "unitField" || o.kind === "tableRead" || o.kind === "pop") pure = false;
if (o.kind === "call" || o.kind === "read" || o.kind === "randomInt" || o.kind === "input" || o.kind === "unitField" || o.kind === "unitDistance" || o.kind === "tableRead" || o.kind === "pop") pure = false;
Object.values(o).forEach(walk);
};
walk(e);
Expand Down
94 changes: 93 additions & 1 deletion compiler/backend/units.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
*/
import type { ArrayDecl, At, BoolExpr, Call, CompareOp, FuncDecl, NumExpr, Program, Stmt, UnitExpr, UnitFilter, UnitFlag, UnitNumField, VarDecl } from "../ir";
import type { ActionRecord, ConditionRecord } from "../../vendor/triggers";
import { CAST_ORDERS, GATHER_ORDERS, GATHER_WORKERS, STOP_ORDER } from "../orders";
import { UNIT_DIMENSIONS } from "../tables";
import { STATEMENT_KINDS } from "./emit";
import { MOUSE_CELLS } from "./input";

Expand All @@ -32,7 +34,7 @@ const CURRENT = epd(0x6509b0);
/** The game's locations: 20 bytes each, from 1. */
const MRGN = epd(0x58dc60);
/** units.dat: hit points (a dword a type, 256 to a point), shields (a word a type), the group flags (a byte a type). */
const MAX_HP = epd(0x662350), MAX_SHIELDS = epd(0x660e00), GROUPS = epd(0x6637a0);
const MAX_HP = epd(0x662350), MAX_SHIELDS = epd(0x660e00), GROUPS = epd(0x6637a0), DIMENSIONS = epd(UNIT_DIMENSIONS);
/**
* A filter's type that is one type, asked of a unit's type word (16 bits): the game's 0–227, and a data set's past the
* classes (a mod's units from 233 on). 228 is the game's None and 229–232 the trigger's classes.
Expand Down Expand Up @@ -71,11 +73,15 @@ const word = (byte: number, bytes: 1 | 2 | 4): Bits => {
const SPRITE = 0x0c >> 2, POSITION = 0x28 >> 2, UID = word(0xa5, 1);
/** The owner and the order share a dword: the owner its low byte, the order the next. */
const OWNER = word(0x4c, 1), ORDER = word(0x4d, 1), TYPE = word(0x64, 2);
/** The order's state, beside the order in its dword: what `gather()` and `cast()` put back to the start. */
const ORDER_STATE = word(0x4e, 1);
const X = word(0x28, 2), Y = word(0x2a, 2);
const FIELDS: Partial<Record<UnitNumField, Bits>> = {
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),
acidSpores: word(0x126, 1), orderState: ORDER_STATE, queuedOrders: word(0x84, 1),
};
const HP = 0x08 >> 2, SHIELDS = 0x60 >> 2, ENERGY = word(0xa2, 2), STATUS = 0xdc >> 2, USER_ACTION = word(0x93, 1);
/**
Expand All @@ -86,6 +92,8 @@ const HP = 0x08 >> 2, SHIELDS = 0x60 >> 2, ENERGY = word(0xa2, 2), STATUS = 0xdc
* one "recently hit" signal a map may read.
*/
const ATTACKED = word(0x87, 1);
/** Optical Flare: a bit for each player whose Medic flared the unit, all cleared by Restoration. */
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 };
/** 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. */
Expand Down Expand Up @@ -655,6 +663,17 @@ export function unitValues(program: Program, events?: { sources: Set<EventSource
}
case "pick": return pick(e, pre);
case "selected": return fix(e, pre) as Unit;
case "unitOrderTarget": {
// The order's target is a pointer, 0 for none: read as a unit whose uniqueness byte is taken when read, as `selected` is.
const holder = held(unit(e.unit, pre), pre);
if (isNone(holder)) return NONE;
const p = fresh("aim");
pre.push(dec(p, k(0), 0x3fffffff), ...when(alive(holder), [
...through(of(holder.e, ORDER_TARGET), (h) => [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);
Expand Down Expand Up @@ -711,11 +730,51 @@ export function unitValues(program: Program, events?: { sources: Set<EventSource
u = held(u, pre);
if (f === "underAttack") return all([alive(u), cmp(">=", bits(u.e, ATTACKED), k(1))]);
if (f === "hasTarget") return all([alive(u), cmp(">=", peek(of(u.e, ORDER_TARGET)), k(1))]);
if (f === "opticalFlare") return all([alive(u), cmp(">=", bits(u.e, FLARED), k(1))]);
const mask = FLAG_BITS[f];
if (mask === undefined) throw new Leave();
return all([alive(u), cmp("==", peek(of(u.e, STATUS), mask), k(mask))]);
};

/**
* How far apart two units are as the game measures a range (`units_distance`): the gap between their boxes, each its
* type's dimensions around its centre, along x and along y, made one length by the game's `xy_length`. 0 when either
* is none or gone.
*/
const distance = (a0: Unit, b0: Unit, pre: Stmt[]): NumExpr => {
if (isNone(a0) || isNone(b0)) return k(0);
const a = held(a0, pre), b = held(b0, pre);
const t = fresh("d"), body: Stmt[] = [];
// (Every side 256 to the right of where it is, so that none of them is below zero.)
const box = (u: Unit) => {
const [x, y, ty, left, up, right, down] = ["x", "y", "ty", "l", "u", "r", "b"].map((what) => fresh(what));
body.push(...[x, y, ty, left, up, right, down].map((id) => dec(id, k(0), 0xffff)));
body.push(...through(of(u.e, POSITION), (h) => [set(x, h(X.mask, X.shift)), set(y, h(Y.mask, Y.shift))]), ...readInto(ty, u.e, TYPE));
const at_ = bin("+", k(DIMENSIONS), bin("*", ranged(V(ty), 0, 0xffff), k(2)));
body.push(...through(at_, (h) => [set(left, h(0xffff)), set(up, h(0xffff0000, 16))]), ...through(bin("+", at_, k(1)), (h) => [set(right, h(0xffff)), set(down, h(0xffff0000, 16))]));
const w = (id: string) => ranged(V(id), 0, 0xffff);
return { left: bin("-", bin("+", w(x), k(256)), w(left)), top: bin("-", bin("+", w(y), k(256)), w(up)), right: bin("+", bin("+", w(x), w(right)), k(257)), bottom: bin("+", bin("+", w(y), w(down)), k(257)) };
};
const p = box(a), q = box(b);
const gap = (id: string, from1: NumExpr, to1: NumExpr, from2: NumExpr, to2: NumExpr): Stmt[] => {
const s = [fresh("s1"), fresh("e1"), fresh("s2"), fresh("e2")];
const [f1, t1, f2, t2] = s.map((v) => ranged(V(v), 0, 0x20000));
return [dec(s[0], from1, 0x20000), dec(s[1], to1, 0x20000), dec(s[2], from2, 0x20000), dec(s[3], to2, 0x20000), dec(id, k(0), 0x20000),
...when(cmp(">", f1, t2), [set(id, bin("-", f1, t2))], when(cmp(">", f2, t1), [set(id, bin("-", f2, t1))]))];
};
const longer = fresh("dl"), shorter = fresh("ds"), swap = fresh("dt");
body.push(...gap(longer, p.left, p.right, q.left, q.right), ...gap(shorter, p.top, p.bottom, q.top, q.bottom));
const x = ranged(V(longer), 0, 0x20000), y = ranged(V(shorter), 0, 0x20000);
// The longer side first, then the game's xy_length: a share of the shorter added once the two are far enough from a line.
body.push(...when(cmp("<", x, y), [dec(swap, x, 0x20000), set(longer, y), set(shorter, ranged(V(swap), 0, 0x20000))]));
const y3 = bin("*", y, k(3));
body.push(set(t, x), ...when(cmp("<", bin(">>>", x, k(2)), y), [
set(t, bin("+", bin("-", bin("+", bin("-", x, bin(">>>", x, k(4))), bin(">>>", y3, k(3))), bin(">>>", x, k(6))), bin(">>>", y3, k(8)))),
]));
pre.push(dec(t, k(0), 0x20000), ...when(all([present(a), present(b)]), body));
return ranged(V(t), 0, 0x20000);
};

/** The order Die: what kills a unit, as eudplib's `CUnit.die()`. */
const die = (e: NumExpr): Stmt => poke(of(e, ORDER.dword), k(0), ORDER.mask);

Expand Down Expand Up @@ -767,12 +826,16 @@ export function unitValues(program: Program, events?: { sources: Set<EventSource
const v = s.verb;
// (The amount is worked out whether or not there is a unit.)
const amount = v.do === "damage" || v.do === "heal" ? plain(fix(v.amount, pre) as NumExpr, pre) : null;
const target = v.do === "gather" || v.do === "cast" ? held(unit(v.target, pre), pre) : null;
if (isNone(u0)) return;
const u = held(u0, pre);
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))));
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;
// (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 @@ -825,6 +888,34 @@ export function unitValues(program: Program, events?: { sources: Set<EventSource
);
break;
}
case "gather": {
// The order's target, its state back to the start and the order itself, as the game's right-click leaves them.
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)]), [
...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 "cast": {
// The spell's order at the target, its state back to the start, as a player's command leaves them.
const spell = CAST_ORDERS.find((c) => c.tech === v.tech);
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)]), [
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),
]));
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");
Expand Down Expand Up @@ -971,6 +1062,7 @@ export function unitValues(program: Program, events?: { sources: Set<EventSource
case "unitAlive": return alive(held(unit((o as { unit: UnitExpr }).unit, pre), pre));
case "unitFlag": { const e = o as unknown as Extract<BoolExpr, { kind: "unitFlag" }>; return flag(unit(e.unit, pre), e.flag, pre); }
case "unitSame": { const e = o as unknown as Extract<BoolExpr, { kind: "unitSame" }>; return same(unit(e.left, pre), unit(e.right, pre), pre); }
case "unitDistance": { const e = o as unknown as Extract<NumExpr, { kind: "unitDistance" }>; return distance(unit(e.from, pre), unit(e.to, pre), pre); }
case "selected": {
// `local.selected` (step 12): the unit in a slot of this computer's selection, re-checked before use as a kept
// unit is (its uniqueness byte taken when read). The slot holds a pointer, or 0 for none.
Expand Down
16 changes: 12 additions & 4 deletions compiler/check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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); };
Expand All @@ -45,6 +45,7 @@ function expressions(body: Stmt[], visit: (e: NumExpr | BoolExpr) => void, pick?
switch (e.kind) {
case "unitField": case "unitPart": case "unitAlive": case "unitFlag": unit(e.unit); break;
case "unitSame": unit(e.left); unit(e.right); break;
case "unitDistance": unit(e.from); unit(e.to); break;
case "unary": case "cast": expr(e.expr); break;
case "element": expr(e.index); break;
case "binary": case "compare": expr(e.left); expr(e.right); break;
Expand Down Expand Up @@ -76,7 +77,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" || s.verb.do === "cast") 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;
Expand Down Expand Up @@ -280,6 +281,12 @@ const THE_GAME = "(the game)";
let WINDOWS = new Map<string, string>();
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<string>): 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<string>()): Set<string> {
// A text reads the variables it is made from; a list of texts the script has never changes.
Expand All @@ -292,8 +299,9 @@ function reads(e: NumExpr | BoolExpr, into = new Set<string>()): Set<string> {
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 "unitDistance": into.add(THE_GAME); for (const u of [e.from, e.to]) 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;
Expand Down
Loading
Loading