@team-antioch/sc2-adjutant 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/README.md +2 -0
  2. package/data/blizzard-baseline.json +3061 -0
  3. package/data/button-hotkeys.json +5722 -0
  4. package/data/game-assets.json +50909 -0
  5. package/data/package-entries.json +32361 -2
  6. package/dist/capture/bank-fixtures.d.ts +13 -0
  7. package/dist/capture/bank-fixtures.js +35 -0
  8. package/dist/capture/bank-snapshots.d.ts +95 -0
  9. package/dist/capture/bank-snapshots.js +302 -0
  10. package/dist/capture/editor-broker-client.d.ts +27 -4
  11. package/dist/capture/editor-broker-client.js +3 -3
  12. package/dist/capture/editor-broker.js +154 -9
  13. package/dist/capture/effect-tour.d.ts +113 -0
  14. package/dist/capture/effect-tour.js +283 -0
  15. package/dist/capture/effect-video.d.ts +74 -0
  16. package/dist/capture/effect-video.js +173 -0
  17. package/dist/capture/exemplar-capture.d.ts +4 -0
  18. package/dist/capture/exemplar-capture.js +4 -1
  19. package/dist/capture/shots.d.ts +6 -1
  20. package/dist/capture/shots.js +1 -1
  21. package/dist/capture/stop-tour.d.ts +3 -1
  22. package/dist/capture/stop-tour.js +1 -1
  23. package/dist/capture/style-pack-captures.d.ts +67 -0
  24. package/dist/capture/style-pack-captures.js +172 -0
  25. package/dist/catalog/stock-catalog.d.ts +8 -0
  26. package/dist/catalog/stock-catalog.js +13 -0
  27. package/dist/cli/capture-exemplars.js +18 -32
  28. package/dist/cli/effect-tour.d.ts +2 -0
  29. package/dist/cli/effect-tour.js +378 -0
  30. package/dist/cli/make-frames.d.ts +1 -0
  31. package/dist/cli/make-frames.js +21 -0
  32. package/dist/cli/sound-mix.d.ts +1 -0
  33. package/dist/cli/sound-mix.js +75 -0
  34. package/dist/cli/study.js +6 -26
  35. package/dist/domain/blueprint-trigger.d.ts +355 -3
  36. package/dist/domain/blueprint-trigger.js +149 -8
  37. package/dist/domain/library-interface.d.ts +50 -29
  38. package/dist/domain/library-interface.js +54 -41
  39. package/dist/domain/mission-blueprint.d.ts +13 -6
  40. package/dist/domain/mission-blueprint.js +6 -0
  41. package/dist/domain/mod-blueprint.d.ts +4 -4
  42. package/dist/host/game-logs.d.ts +63 -0
  43. package/dist/host/game-logs.js +178 -0
  44. package/dist/host/game-ownership.d.ts +37 -0
  45. package/dist/host/game-ownership.js +84 -0
  46. package/dist/host/game-run-report.d.ts +63 -0
  47. package/dist/host/game-run-report.js +119 -0
  48. package/dist/host/known-errors.d.ts +34 -0
  49. package/dist/host/known-errors.js +73 -0
  50. package/dist/init/init-workspace.d.ts +3 -1
  51. package/dist/init/init-workspace.js +10 -1
  52. package/dist/map/convert-mission-triggers.d.ts +115 -7
  53. package/dist/map/convert-mission-triggers.js +527 -47
  54. package/dist/map/editor-changes.d.ts +1 -1
  55. package/dist/map/editor-form.d.ts +5 -0
  56. package/dist/map/editor-form.js +72 -0
  57. package/dist/map/game-packages.d.ts +3 -2
  58. package/dist/map/game-packages.js +5 -2
  59. package/dist/map/kept-references.js +47 -1
  60. package/dist/map/kept-session.js +3 -1
  61. package/dist/map/outline-diff.d.ts +24 -0
  62. package/dist/map/outline-diff.js +95 -0
  63. package/dist/map/outline-trigger.d.ts +7 -0
  64. package/dist/map/outline-trigger.js +29 -20
  65. package/dist/map/ownership-plan.d.ts +6 -2
  66. package/dist/map/ownership-plan.js +1 -1
  67. package/dist/map/package-output.js +13 -8
  68. package/dist/map/tune-kept-triggers.d.ts +7 -0
  69. package/dist/map/tune-kept-triggers.js +33 -6
  70. package/dist/map/write-blueprint-trigger.d.ts +9 -4
  71. package/dist/map/write-blueprint-trigger.js +46 -13
  72. package/dist/map/write-map-package.js +20 -9
  73. package/dist/mcp/capture-jobs.d.ts +2 -0
  74. package/dist/mcp/capture-jobs.js +2 -0
  75. package/dist/mcp/server.d.ts +11 -2
  76. package/dist/mcp/server.js +17 -4
  77. package/dist/mcp/tools/bank-report.d.ts +19 -0
  78. package/dist/mcp/tools/bank-report.js +51 -0
  79. package/dist/mcp/tools/blueprint.js +18 -14
  80. package/dist/mcp/tools/capture.d.ts +4 -0
  81. package/dist/mcp/tools/capture.js +22 -5
  82. package/dist/mcp/tools/catalog.d.ts +1 -1
  83. package/dist/mcp/tools/catalog.js +30 -1
  84. package/dist/mcp/tools/compile.d.ts +1 -1
  85. package/dist/mcp/tools/compile.js +100 -9
  86. package/dist/mcp/tools/editor-handoff.d.ts +4 -1
  87. package/dist/mcp/tools/editor-handoff.js +6 -3
  88. package/dist/mcp/tools/style-pack.d.ts +11 -0
  89. package/dist/mcp/tools/style-pack.js +245 -0
  90. package/dist/mcp/tools/tool-group.d.ts +9 -0
  91. package/dist/mods/button-hotkeys.d.ts +45 -0
  92. package/dist/mods/button-hotkeys.js +185 -0
  93. package/dist/mods/compile-mod.js +19 -5
  94. package/dist/mods/custom-doodads.d.ts +21 -1
  95. package/dist/mods/custom-doodads.js +53 -7
  96. package/dist/mods/data-rules.js +8 -1
  97. package/dist/mods/effective-entry.d.ts +18 -0
  98. package/dist/mods/effective-entry.js +52 -0
  99. package/dist/mods/function-search.js +12 -0
  100. package/dist/mods/library-xml.d.ts +34 -5
  101. package/dist/mods/library-xml.js +94 -22
  102. package/dist/mods/sound-mix.d.ts +92 -0
  103. package/dist/mods/sound-mix.js +195 -0
  104. package/dist/plugins/check-workspace.js +22 -3
  105. package/dist/plugins/plugin-api.d.ts +59 -5
  106. package/dist/plugins/plugin-api.js +6 -0
  107. package/dist/plugins/plugin-sdk.d.ts +13 -1
  108. package/dist/plugins/plugin-sdk.js +16 -1
  109. package/dist/plugins/plugin-sources.js +1 -0
  110. package/dist/plugins/registry.d.ts +4 -0
  111. package/dist/plugins/registry.js +6 -2
  112. package/dist/plugins/workspace.d.ts +5 -0
  113. package/dist/plugins/workspace.js +10 -2
  114. package/dist/study/blizzard-baseline.d.ts +76 -0
  115. package/dist/study/blizzard-baseline.js +137 -0
  116. package/dist/study/exemplar-report.d.ts +71 -0
  117. package/dist/study/exemplar-report.js +163 -0
  118. package/dist/study/find-places.d.ts +127 -0
  119. package/dist/study/find-places.js +306 -0
  120. package/dist/study/load-map-package.d.ts +3 -0
  121. package/dist/study/load-map-package.js +11 -0
  122. package/dist/study/map-study.d.ts +1 -0
  123. package/dist/study/map-study.js +3 -0
  124. package/dist/study/measure-lighting.d.ts +6 -0
  125. package/dist/study/measure-lighting.js +1 -1
  126. package/dist/study/measures.d.ts +225 -0
  127. package/dist/study/measures.js +366 -0
  128. package/dist/study/scaffold-style-pack.d.ts +58 -0
  129. package/dist/study/scaffold-style-pack.js +261 -0
  130. package/dist/study/study-exemplars.d.ts +67 -0
  131. package/dist/study/study-exemplars.js +133 -0
  132. package/dist/triggers/blueprint-triggers.d.ts +71 -11
  133. package/dist/triggers/blueprint-triggers.js +403 -48
  134. package/dist/triggers/kept-trigger-galaxy.d.ts +29 -0
  135. package/dist/triggers/kept-trigger-galaxy.js +103 -7
  136. package/dist/triggers/splice-map-script.d.ts +2 -0
  137. package/dist/triggers/splice-map-script.js +309 -8
  138. package/dist/triggers/write-triggers-xml.js +20 -5
  139. package/dist/ui/frame-path-check.d.ts +43 -4
  140. package/dist/ui/frame-path-check.js +121 -13
  141. package/dist/ui/frame-paths.d.ts +21 -1
  142. package/dist/ui/frame-paths.js +26 -6
  143. package/dist/ui/toast.d.ts +4 -5
  144. package/dist/ui/toast.js +6 -10
  145. package/examples/example-campaign/README.md +27 -0
  146. package/examples/example-campaign/missions/ashfall-relay/blueprint.json +11 -1
  147. package/examples/example-campaign/missions/ashfall-relay/triggers/ash-tremors.json +69 -0
  148. package/examples/example-campaign/missions/ashfall-relay/triggers/start-ash-tremors.json +31 -0
  149. package/package.json +3 -3
@@ -16,15 +16,47 @@
16
16
  import { readFile } from "node:fs/promises";
17
17
  import path from "node:path";
18
18
  import { heldIds, isComment, LIBRARY_ITEM_TYPES, statementIds } from "../domain/library-interface.js";
19
- import { BlueprintTriggerSchema } from "../domain/blueprint-trigger.js";
19
+ import { BlueprintElementSchema, BlueprintTriggerSchema } from "../domain/blueprint-trigger.js";
20
20
  import { gameTriggerLibraries } from "../mods/library-galaxy.js";
21
- import { ElementWriter, escapeXml, mapLabelLine } from "../mods/library-xml.js";
21
+ import { ElementWriter, escapeXml, functionStrings, functionXml, mapLabelLine, scriptCodeLines } from "../mods/library-xml.js";
22
22
  import { KeptGalaxyRenderer } from "./kept-trigger-galaxy.js";
23
- import { libraryItems } from "./splice-triggers.js";
23
+ import { itemKind, libraryItems } from "./splice-triggers.js";
24
24
  import { CORE_PRIMITIVES } from "./trigger-catalog.js";
25
25
  import { elementKey, readTriggersFile } from "./triggers-file.js";
26
- /** Whether the Blueprint declares any trigger element of its own: a trigger, a global or a folder. */
27
- export const hasAuthoredTriggers = (authored) => authored !== undefined && authored.triggers.length + (authored.variables ?? []).length + authored.folders.length > 0;
26
+ /** Whether the Blueprint declares any trigger element of its own: a trigger, a function, a comment, a preset type, a record, custom script, a global or a folder. */
27
+ export const hasAuthoredTriggers = (authored) => authored !== undefined &&
28
+ authored.triggers.length + (authored.functions ?? []).length + (authored.comments ?? []).length + (authored.presets ?? []).length + (authored.records ?? []).length + (authored.customScripts ?? []).length + (authored.variables ?? []).length + authored.folders.length > 0;
29
+ /** What a refusal names a Blueprint preset type, record or custom script by. */
30
+ const describeItem = (what, { file, item }) => `the Blueprint ${what} "${item.name}" (${item.id}, ${file})`;
31
+ /** Every element Id a Blueprint preset type gives: its own, its values' and its comments'. */
32
+ export const blueprintPresetIds = (preset) => [preset.id, ...preset.values.map((value) => value.id)];
33
+ /** Every element Id a Blueprint record gives: its own, its members' and their initial values'. */
34
+ export const blueprintRecordIds = (record) => [record.id, ...record.members.flatMap((member) => [member.id, ...(member.value ? heldIds(member.value) : [])])];
35
+ /** A Blueprint function as the library writer and reader have one: its interface (LibraryFunction) and its GUI body. */
36
+ export function libraryForm(fn) {
37
+ const { kind: _, functionKind, variables, actions, strings: __, ...rest } = fn;
38
+ return { fn: { ...rest, kind: functionKind }, body: { variables, actions } };
39
+ }
40
+ /** A map function as the library reader reads it (readMapFunctionWhole) as a Blueprint function, with no words yet. */
41
+ export function blueprintFunctionOf(fn, body) {
42
+ const { kind, flags, parameters, subFunctions, gui: _, galaxy: __, script: ___, ...rest } = fn;
43
+ return { kind: "function", ...rest, functionKind: kind, flags, parameters, subFunctions, variables: body?.variables ?? [], actions: body?.actions ?? [] };
44
+ }
45
+ /** A Blueprint function's elements as the Editor writes them in a map's Triggers (LF): its FunctionDef, then every element it owns, in the order the Editor reaches them. */
46
+ export function blueprintFunctionXml(fn) {
47
+ const { fn: form, body } = libraryForm(fn);
48
+ return functionXml(undefined, form, body).elements;
49
+ }
50
+ /** Every element Id a Blueprint function gives: its own, its parameters' and their defaults', its block slots', its variables' and their values', its statements'. */
51
+ export function blueprintFunctionIds(fn) {
52
+ return [
53
+ fn.id,
54
+ ...fn.parameters.flatMap((parameter) => [parameter.id, ...(parameter.default ? heldIds(parameter.default) : [])]),
55
+ ...fn.subFunctions.map((slot) => slot.id),
56
+ ...fn.variables.flatMap((variable) => [variable.id, ...(variable.value ? heldIds(variable.value) : [])]),
57
+ ...fn.actions.flatMap(statementIds),
58
+ ];
59
+ }
28
60
  const ELEMENT = " ";
29
61
  const CHILD = " ";
30
62
  const RULE = "//--------------------------------------------------------------------------------------------------";
@@ -32,15 +64,19 @@ const RULE = "//----------------------------------------------------------------
32
64
  const describeGlobal = (variable) => `the Blueprint global "${variable.name}" (${variable.id}, triggerVariables)`;
33
65
  /** What a refusal names a Blueprint trigger by. */
34
66
  const describeTrigger = ({ file, trigger }) => `the Blueprint trigger "${trigger.name}" (${trigger.id}, ${file})`;
67
+ /** What a refusal names a Blueprint function by. */
68
+ const describeFunction = ({ file, fn }) => `the Blueprint function "${fn.name}" (${fn.id}, ${file})`;
35
69
  /** A Blueprint trigger's file, as convert_triggers and write_blueprint_trigger write it: its element in the schema's order, as JSON. */
36
70
  export const blueprintTriggerFile = (trigger) => `${JSON.stringify(BlueprintTriggerSchema.parse(trigger), null, 2)}\n`;
71
+ /** Any Blueprint trigger element's file (a trigger's, a function's), as convert_triggers writes it: its element in its schema's order, as JSON. */
72
+ export const blueprintElementFile = (element) => `${JSON.stringify(BlueprintElementSchema.parse(element), null, 2)}\n`;
37
73
  /**
38
74
  * The Blueprint's own trigger elements, each read from its file in `triggers` (relative to the
39
- * Blueprint), and its folders. A file that can't be read or isn't a trigger element is refused,
40
- * naming it and why.
75
+ * Blueprint), split by kind, and its globals and folders. A file that can't be read or isn't a
76
+ * trigger element is refused, naming it and why.
41
77
  */
42
78
  export async function readAuthoredTriggers(blueprint, blueprintPath) {
43
- const triggers = await Promise.all((blueprint.triggers ?? []).map(async (file) => {
79
+ const elements = await Promise.all((blueprint.triggers ?? []).map(async (file) => {
44
80
  const full = path.join(path.dirname(blueprintPath), ...file.split("/"));
45
81
  let raw;
46
82
  try {
@@ -49,12 +85,18 @@ export async function readAuthoredTriggers(blueprint, blueprintPath) {
49
85
  catch (error) {
50
86
  throw new Error(`${blueprintPath}'s trigger element ${file} can't be read: ${error instanceof Error ? error.message : String(error)}`);
51
87
  }
52
- const parsed = BlueprintTriggerSchema.safeParse(raw);
88
+ const parsed = BlueprintElementSchema.safeParse(raw);
53
89
  if (!parsed.success)
54
90
  throw new Error(`${blueprintPath}'s trigger element ${file} isn't one: ${parsed.error.issues.map((issue) => `${issue.path.join(".") || "(file)"}: ${issue.message}`).join("; ")}`);
55
- return { file, trigger: parsed.data };
91
+ return { file, element: parsed.data };
56
92
  }));
57
- return { triggers, variables: blueprint.triggerVariables ?? [], folders: blueprint.triggerFolders ?? [] };
93
+ const triggers = elements.flatMap(({ file, element }) => (element.kind === "trigger" ? [{ file, trigger: element }] : []));
94
+ const functions = elements.flatMap(({ file, element }) => (element.kind === "function" ? [{ file, fn: element }] : []));
95
+ const comments = elements.flatMap(({ file, element }) => (element.kind === "comment" ? [{ file, comment: element }] : []));
96
+ const presets = elements.flatMap(({ file, element }) => (element.kind === "preset" ? [{ file, item: element }] : []));
97
+ const records = elements.flatMap(({ file, element }) => (element.kind === "record" ? [{ file, item: element }] : []));
98
+ const customScripts = elements.flatMap(({ file, element }) => (element.kind === "custom-script" ? [{ file, item: element }] : []));
99
+ return { triggers, functions, comments, presets, records, customScripts, variables: blueprint.triggerVariables ?? [], folders: blueprint.triggerFolders ?? [] };
58
100
  }
59
101
  /** A reference line in a trigger element: `<Event Type="FunctionCall" Id="…"/>`, a comment's `Type="Comment"`. */
60
102
  const statementLine = (tag, statement) => `${CHILD}<${tag} Type="${isComment(statement) ? "Comment" : "FunctionCall"}" Id="${statement.id}"/>`;
@@ -82,8 +124,44 @@ export function blueprintTriggerXml(trigger) {
82
124
  writer.statement(statement);
83
125
  return writer.elements;
84
126
  }
127
+ /** A Blueprint preset type's elements as the Editor writes them in a map's Triggers (LF): its Preset, filing its values and comments in order, then each of theirs. */
128
+ export function blueprintPresetXml(preset) {
129
+ const writer = new ElementWriter(undefined, ELEMENT);
130
+ writer.element("Preset", preset.id, [
131
+ ...(preset.integer ? [`${CHILD}<PresetInteger/>`] : []),
132
+ `${CHILD}<BaseType Value="${escapeXml(preset.baseType)}"/>`,
133
+ ...(preset.constants ? [`${CHILD}<PresetGenConstVar/>`] : []),
134
+ ...preset.values.map((value) => `${CHILD}<Item Type="${"comment" in value ? "Comment" : "PresetValue"}" Id="${value.id}"/>`),
135
+ ]);
136
+ for (const value of preset.values) {
137
+ if ("comment" in value)
138
+ writer.statement({ id: value.id, comment: value.comment });
139
+ else
140
+ writer.element("PresetValue", value.id, []);
141
+ }
142
+ return writer.elements;
143
+ }
144
+ /** A Blueprint record's elements as the Editor writes them in a map's Triggers (LF): its Structure, naming its members, then each member's Variable and what it owns. */
145
+ export function blueprintRecordXml(record) {
146
+ const writer = new ElementWriter(undefined, ELEMENT);
147
+ writer.element("Structure", record.id, record.members.map((member) => `${CHILD}<Variable Type="Variable" Id="${member.id}"/>`));
148
+ for (const member of record.members)
149
+ writer.variable(member);
150
+ return writer.elements;
151
+ }
152
+ /** A Blueprint custom script's element as the Editor writes it in a map's Triggers (LF): its script, then its init function. */
153
+ export function blueprintCustomScriptXml(script) {
154
+ const writer = new ElementWriter(undefined, ELEMENT);
155
+ writer.element("CustomScript", script.id, [...scriptCodeLines(script.script, CHILD, `${CHILD} `), ...(script.initFunction ? [`${CHILD}<InitFunc>${escapeXml(script.initFunction)}</InitFunc>`] : [])]);
156
+ return writer.elements;
157
+ }
158
+ /**
159
+ * A Blueprint custom script's block of Galaxy as the Editor writes it in the Custom Script section
160
+ * (CRLF): a ruled heading with its name, its script as it stands, then a blank line.
161
+ */
162
+ export const customScriptGalaxy = (script) => [RULE, `// Custom Script: ${script.name}`, RULE, ...script.script.replace(/\s+$/, "").split(/\r?\n/), "", ""].join("\r\n");
85
163
  /** A Blueprint folder's Category element (LF): its icon, then the item lines of what it files. */
86
- function folderXml(folder) {
164
+ export function folderXml(folder) {
87
165
  const items = folder.items.map((item) => `${CHILD}${itemLine(item)}`);
88
166
  return [`${ELEMENT}<Element Type="Category" Id="${folder.id}">`, ...(folder.label ? [mapLabelLine(folder.label, CHILD)] : []), ...items, `${ELEMENT}</Element>`].join("\n");
89
167
  }
@@ -111,7 +189,7 @@ export function blueprintTriggerLibraries(authored) {
111
189
  if (value?.includes("/"))
112
190
  used.add(value.split("/")[0]);
113
191
  };
114
- for (const parts of [...authored.triggers.map(({ trigger }) => triggerParts(trigger)), ...(authored.variables ?? []).map(globalParts)]) {
192
+ for (const parts of [...authored.triggers.map(({ trigger }) => triggerParts(trigger)), ...(authored.functions ?? []).map(({ fn }) => functionParts(fn)), ...(authored.variables ?? []).map(globalParts)]) {
115
193
  walk(parts, {
116
194
  call: (call) => ref(call.function),
117
195
  value: (value) => {
@@ -128,6 +206,11 @@ export function blueprintTriggerLibraries(authored) {
128
206
  }
129
207
  /** A trigger's parts: its local variables' initial values, its events, conditions and actions. */
130
208
  const triggerParts = (trigger) => ({ values: trigger.variables.flatMap((variable) => (variable.value ? [variable.value] : [])), statements: [...trigger.events, ...trigger.conditions, ...trigger.actions] });
209
+ /** A function's parts: its parameters' defaults, its variables' initial values, its actions. */
210
+ const functionParts = (fn) => ({
211
+ values: [...fn.parameters.flatMap((parameter) => (parameter.default ? [parameter.default] : [])), ...fn.variables.flatMap((variable) => (variable.value ? [variable.value] : []))],
212
+ statements: fn.actions,
213
+ });
131
214
  /** A global's parts: its initial value. */
132
215
  const globalParts = (variable) => ({ values: variable.value ? [variable.value] : [], statements: [] });
133
216
  /** The variables a structure member path names, outermost first. */
@@ -207,10 +290,19 @@ export class BlueprintTriggerError extends Error {
207
290
  this.name = "BlueprintTriggerError";
208
291
  }
209
292
  }
210
- /** The folders' tree: each folder's items resolved, filed once, with no folder inside itself; the Root items, folders first, then globals, then triggers. */
211
- function folderTree(authored, problems) {
293
+ /** The folders' tree: each folder's items resolved, filed once, with no folder inside itself; the Root items, folders first, then custom script, preset types, records, globals, functions, triggers and comments. */
294
+ function folderTree(authored, problems,
295
+ /** Whether the package has a Kept element of this type and Id, which a Blueprint folder may file (one converted from a Kept folder keeps filing what it did). */
296
+ keptHas = () => false,
297
+ /** The items a Kept folder files, as `<kind>:<id>`. */
298
+ keptFolderItems = () => []) {
212
299
  const triggers = new Set(authored.triggers.map(({ trigger }) => `trigger:${trigger.id}`));
300
+ const functions = new Set((authored.functions ?? []).map(({ fn }) => `function:${fn.id}`));
301
+ const comments = new Set((authored.comments ?? []).map(({ comment }) => `comment:${comment.id}`));
213
302
  const variables = new Set((authored.variables ?? []).map((variable) => `variable:${variable.id}`));
303
+ const presets = new Set((authored.presets ?? []).map(({ item }) => `preset:${item.id}`));
304
+ const records = new Set((authored.records ?? []).map(({ item }) => `structure:${item.id}`));
305
+ const customScripts = new Set((authored.customScripts ?? []).map(({ item }) => `custom-script:${item.id}`));
214
306
  const folders = new Map();
215
307
  for (const folder of authored.folders) {
216
308
  if (folders.has(folder.id))
@@ -218,12 +310,41 @@ function folderTree(authored, problems) {
218
310
  folders.set(folder.id, folder);
219
311
  }
220
312
  const filed = new Map();
313
+ const keptItems = new Set();
314
+ const blueprintHas = (item) => [triggers, functions, comments, variables, presets, records, customScripts].some((set) => set.has(item));
221
315
  for (const folder of authored.folders) {
222
316
  for (const item of folder.items) {
223
317
  const { kind, id } = parseItem(item);
224
- const [known, list] = kind === "trigger" ? [triggers.has(item), "Blueprint trigger the triggers list"] : kind === "variable" ? [variables.has(item), "global of triggerVariables"] : [folders.has(id), "folder of triggerFolders"];
318
+ // A Kept item the folder files, by its line alone.
319
+ if (!(kind === "category" && folders.has(id)) && !blueprintHas(item) && keptHas(LIBRARY_ITEM_TYPES[kind], id)) {
320
+ keptItems.add(item);
321
+ // A Kept folder filing a Blueprint folder that files it would be a folder inside itself.
322
+ const back = kind === "category" ? keptFolderItems(id).find((inner) => inner.startsWith("category:") && folders.has(inner.slice("category:".length))) : undefined;
323
+ if (back !== undefined)
324
+ problems.push(`the Trigger Folder "${folder.name}" (${folder.id}) files the Kept folder ${id}, which files ${back} of triggerFolders: a folder can't be inside itself`);
325
+ const other = filed.get(item);
326
+ if (other !== undefined)
327
+ problems.push(`${item} is filed in both ${other} and ${folder.id}: an item is filed once`);
328
+ filed.set(item, folder.id);
329
+ continue;
330
+ }
331
+ const [known, list] = kind === "trigger"
332
+ ? [triggers.has(item), "Blueprint trigger the triggers list"]
333
+ : kind === "function"
334
+ ? [functions.has(item), "Blueprint function the triggers list"]
335
+ : kind === "comment"
336
+ ? [comments.has(item), "Blueprint comment the triggers list"]
337
+ : kind === "variable"
338
+ ? [variables.has(item), "global of triggerVariables"]
339
+ : kind === "category"
340
+ ? [folders.has(id), "folder of triggerFolders"]
341
+ : kind === "preset"
342
+ ? [presets.has(item), "Blueprint preset type the triggers list"]
343
+ : kind === "structure"
344
+ ? [records.has(item), "Blueprint record the triggers list"]
345
+ : [customScripts.has(item), "Blueprint custom script the triggers list"];
225
346
  if (!known)
226
- problems.push(`the Trigger Folder "${folder.name}" (${folder.id}) files ${item}, which is no ${list}`);
347
+ problems.push(`the Trigger Folder "${folder.name}" (${folder.id}) files ${item}, which is no ${list}, nor a Kept one`);
227
348
  const other = filed.get(item);
228
349
  if (other !== undefined)
229
350
  problems.push(`${item} is filed in both ${other} and ${folder.id}: an item is filed once`);
@@ -241,8 +362,8 @@ function folderTree(authored, problems) {
241
362
  seen.add(at);
242
363
  }
243
364
  }
244
- const root = [...authored.folders.map((folder) => `category:${folder.id}`), ...variables, ...triggers].filter((item) => !filed.has(item));
245
- return { root, folders };
365
+ const root = [...authored.folders.map((folder) => `category:${folder.id}`), ...customScripts, ...presets, ...records, ...variables, ...functions, ...triggers, ...comments].filter((item) => !filed.has(item));
366
+ return { root, folders, keptItems };
246
367
  }
247
368
  /** The Ids every Blueprint element gives, checked: each given once, and none a Kept element's or the compile's own. */
248
369
  function checkIds(authored, kept, generated, problems) {
@@ -268,6 +389,19 @@ function checkIds(authored, kept, generated, problems) {
268
389
  for (const entry of authored.triggers)
269
390
  for (const id of blueprintTriggerIds(entry.trigger))
270
391
  check(id, describeTrigger(entry));
392
+ for (const entry of authored.functions ?? [])
393
+ for (const id of blueprintFunctionIds(entry.fn))
394
+ check(id, describeFunction(entry));
395
+ for (const { file, comment } of authored.comments ?? [])
396
+ check(comment.id, `the Blueprint comment ${comment.id} (${file})`);
397
+ for (const entry of authored.presets ?? [])
398
+ for (const id of blueprintPresetIds(entry.item))
399
+ check(id, describeItem("preset type", entry));
400
+ for (const entry of authored.records ?? [])
401
+ for (const id of blueprintRecordIds(entry.item))
402
+ check(id, describeItem("record", entry));
403
+ for (const entry of authored.customScripts ?? [])
404
+ check(entry.item.id, describeItem("custom script", entry));
271
405
  for (const variable of authored.variables ?? [])
272
406
  for (const id of [variable.id, ...(variable.value ? heldIds(variable.value) : [])])
273
407
  check(id, describeGlobal(variable));
@@ -284,7 +418,14 @@ function checkIds(authored, kept, generated, problems) {
284
418
  function checkReferences(authored, kept, libraries, problems, concepts = new Map()) {
285
419
  const blueprintTriggers = new Set(authored.triggers.map(({ trigger }) => trigger.id));
286
420
  const globals = new Set((authored.variables ?? []).map((variable) => variable.id));
287
- const keptHas = (type, id) => kept.has(elementKey(type, id));
421
+ // The Blueprint's functions, with their parameter definitions and block slots, which a call names as it does a Kept function's.
422
+ // Its preset types and their values, and its records, which a type or a value names as it does a Kept one's.
423
+ const blueprintOwn = new Set([
424
+ ...(authored.functions ?? []).flatMap(({ fn }) => [elementKey("FunctionDef", fn.id), ...fn.parameters.map((parameter) => elementKey("ParamDef", parameter.id)), ...fn.subFunctions.map((slot) => elementKey("SubFuncType", slot.id))]),
425
+ ...(authored.presets ?? []).flatMap(({ item }) => [elementKey("Preset", item.id), ...item.values.flatMap((value) => ("name" in value ? [elementKey("PresetValue", value.id)] : []))]),
426
+ ...(authored.records ?? []).map(({ item }) => elementKey("Structure", item.id)),
427
+ ]);
428
+ const keptHas = (type, id) => kept.has(elementKey(type, id)) || blueprintOwn.has(elementKey(type, id));
288
429
  /** Why a bare Id of `type` can't be named when it is one of the concepts' elements: they're the compile's, and a trigger reacts to a concept through its cues. */
289
430
  const conceptRefusal = (type, id) => {
290
431
  if (!concepts.has(elementKey(type, id)))
@@ -293,10 +434,27 @@ function checkReferences(authored, kept, libraries, problems, concepts = new Map
293
434
  return `${name === undefined ? "" : ` ("${name}")`}, which the compile writes for a Blueprint concept and may change: ${REACT_THROUGH_CUES}`;
294
435
  };
295
436
  const elements = [
296
- ...authored.triggers.map((entry) => ({ by: describeTrigger(entry), parts: triggerParts(entry.trigger), locals: new Set(entry.trigger.variables.map((variable) => variable.id)), types: entry.trigger.variables.map((variable) => variable.type) })),
297
- ...(authored.variables ?? []).map((variable) => ({ by: describeGlobal(variable), parts: globalParts(variable), locals: new Set(), types: [variable.type] })),
437
+ ...authored.triggers.map((entry) => ({ by: describeTrigger(entry), parts: triggerParts(entry.trigger), locals: new Set(entry.trigger.variables.map((variable) => variable.id)), parameters: new Set(), types: entry.trigger.variables.map((variable) => ({ spec: variable.type, what: "declares a variable" })), presets: [] })),
438
+ ...(authored.functions ?? []).map((entry) => ({
439
+ by: describeFunction(entry),
440
+ parts: functionParts(entry.fn),
441
+ locals: new Set(entry.fn.variables.map((variable) => variable.id)),
442
+ parameters: new Set(entry.fn.parameters.map((parameter) => parameter.id)),
443
+ types: [...entry.fn.variables.map((variable) => ({ spec: variable.type, what: "declares a variable" })), ...entry.fn.parameters.map((parameter) => ({ spec: parameter.type, what: "has a parameter" })), ...(entry.fn.returns ? [{ spec: entry.fn.returns, what: "returns a value" }] : [])],
444
+ presets: entry.fn.parameters.flatMap((parameter) => [parameter.preset ?? []].flat()),
445
+ })),
446
+ ...(authored.variables ?? []).map((variable) => ({ by: describeGlobal(variable), parts: globalParts(variable), locals: new Set(), parameters: new Set(), types: [{ spec: variable.type, what: "declares a variable" }], presets: [] })),
447
+ // A record's members, as globals are: their types and initial values.
448
+ ...(authored.records ?? []).map((entry) => ({
449
+ by: describeItem("record", entry),
450
+ parts: { values: entry.item.members.flatMap((member) => (member.value ? [member.value] : [])), statements: [] },
451
+ locals: new Set(),
452
+ parameters: new Set(),
453
+ types: entry.item.members.map((member) => ({ spec: member.type, what: "has a member" })),
454
+ presets: [],
455
+ })),
298
456
  ];
299
- for (const { by, parts, locals, types } of elements) {
457
+ for (const { by, parts, locals, parameters, types, presets } of elements) {
300
458
  const out = new Set();
301
459
  const refuse = (problem) => {
302
460
  if (!out.has(problem))
@@ -345,17 +503,30 @@ function checkReferences(authored, kept, libraries, problems, concepts = new Map
345
503
  }
346
504
  return undefined;
347
505
  };
348
- // A variable's preset type, from a library in reach (a map's own preset or structure isn't an Editor form a Blueprint variable takes).
349
- for (const type of types) {
350
- if (type.type !== "preset" || type.element === undefined)
351
- continue;
352
- const why = inReach(type.element, "presets", "Preset");
506
+ // A variable's or parameter's preset type, from a library in reach or the map's own.
507
+ for (const { spec: type, what } of types) {
508
+ if (type.type === "preset" && type.element !== undefined) {
509
+ const why = inReach(type.element, "presets", "Preset");
510
+ if (why)
511
+ refuse(`${what} of the preset type ${type.element}, which is out of reach: ${why}`);
512
+ }
513
+ // The map's own record type and the constant an array is sized by, among the Kept elements and the Blueprint's (a library's are checked when the library is read).
514
+ if (type.type === "struct" && type.element !== undefined && !type.element.includes("/") && !keptHas("Structure", type.element))
515
+ refuse(`${what} of the record type ${type.element}, which is out of reach: the map has no Kept Structure ${type.element}`);
516
+ for (const bound of type.array ?? []) {
517
+ if ("variable" in bound && !bound.variable.includes("/") && !globals.has(bound.variable) && !keptHas("Variable", bound.variable))
518
+ refuse(`${what} that is an array sized by the variable ${bound.variable}, which is neither a Blueprint nor a Kept global`);
519
+ }
520
+ }
521
+ for (const preset of presets) {
522
+ const why = inReach(preset, "presets", "Preset");
353
523
  if (why)
354
- refuse(`declares a variable of the preset type ${type.element}, which is out of reach: ${why}`);
524
+ refuse(`limits a parameter to the preset type ${preset}, which is out of reach: ${why}`);
355
525
  }
356
526
  walk(parts, {
357
527
  call: (call) => {
358
- const concept = call.function.includes("/") ? undefined : conceptRefusal("FunctionDef", call.function);
528
+ // A Blueprint function the last compile wrote is the Blueprint's own, not a concept's.
529
+ const concept = call.function.includes("/") || blueprintOwn.has(elementKey("FunctionDef", call.function)) ? undefined : conceptRefusal("FunctionDef", call.function);
359
530
  const why = concept ? undefined : inReach(call.function, "functions", "FunctionDef");
360
531
  if (concept)
361
532
  refuse(`calls ${call.function}${concept}`);
@@ -394,6 +565,8 @@ function checkReferences(authored, kept, libraries, problems, concepts = new Map
394
565
  refuse(concept ? `names the variable ${value.variable}${concept}` : `names the variable ${value.variable}, which is neither its own nor a Blueprint or Kept global`);
395
566
  }
396
567
  }
568
+ if ("parameter" in value && value.parameter !== undefined && !parameters.has(value.parameter))
569
+ refuse(`names the parameter ${value.parameter}, which isn't one of its own`);
397
570
  if ("trigger" in value && value.trigger !== undefined && !blueprintTriggers.has(value.trigger) && !keptHas("Trigger", value.trigger)) {
398
571
  const concept = conceptRefusal("Trigger", value.trigger);
399
572
  refuse(concept ? `names the trigger ${value.trigger}${concept}` : `names the trigger ${value.trigger}, which is neither a Blueprint trigger nor a Kept one`);
@@ -413,8 +586,8 @@ export function blueprintReferenceProblems(authored, kept, libraries = gameTrigg
413
586
  return problems;
414
587
  }
415
588
  /**
416
- * Each Blueprint trigger's and global's Galaxy name (gt_, gv_), checked: none the compile's own
417
- * script declares, a Kept trigger or global has, or another Blueprint element has, since the script
589
+ * Each Blueprint element's Galaxy name (a trigger's gt_, a global's gv_, a function's gf_, a record's gs_, a preset value's ge_), checked: none the compile's own
590
+ * script declares, a Kept element has, or another Blueprint element has, since the script
418
591
  * would declare it twice and the game refuse it.
419
592
  */
420
593
  function checkScriptNames(authored, renderer, script, kept, converted, problems) {
@@ -422,11 +595,21 @@ function checkScriptNames(authored, renderer, script, kept, converted, problems)
422
595
  for (const match of script.matchAll(/^(?:trigger|\S+) (g[tv]_\w+);\r?$/gm))
423
596
  taken.set(match[1], "one of the compile's own");
424
597
  for (const [key, item] of kept ? libraryItems(kept.triggers) : []) {
425
- // A Kept trigger the Blueprint converts is the Blueprint trigger itself.
426
- if (kept.compiled.has(key) || (item.type !== "Trigger" && item.type !== "Variable") || (item.type === "Trigger" && converted.has(item.id)))
598
+ // A Kept trigger or function the Blueprint converts is the Blueprint's element itself.
599
+ if (kept.compiled.has(key) || !["Trigger", "Variable", "FunctionDef", "Structure", "Preset"].includes(item.type) || converted.has(elementKey(item.type, item.id)))
427
600
  continue;
428
601
  try {
429
- taken.set(item.type === "Trigger" ? renderer.triggerName(item.id) : renderer.variableGalaxyName(item.id), `the Kept ${item.type} ${item.id}`);
602
+ const names = item.type === "Trigger"
603
+ ? [renderer.triggerName(item.id)]
604
+ : item.type === "FunctionDef"
605
+ ? [renderer.functionName(item.id)]
606
+ : item.type === "Structure"
607
+ ? [renderer.structureName(item.id)]
608
+ : item.type === "Preset"
609
+ ? renderer.presetValueNames(item.id)
610
+ : [renderer.variableGalaxyName(item.id)];
611
+ for (const name of names)
612
+ taken.set(name, `the Kept ${item.type} ${item.id}`);
430
613
  }
431
614
  catch {
432
615
  // A Kept element with no name in TriggerStrings has no Galaxy name to clash with here; the splice checks the script itself.
@@ -444,6 +627,13 @@ function checkScriptNames(authored, renderer, script, kept, converted, problems)
444
627
  for (const entry of authored.triggers)
445
628
  if (!entry.trigger.disabled)
446
629
  claim(renderer.triggerName(entry.trigger.id), describeTrigger(entry));
630
+ for (const entry of authored.functions ?? [])
631
+ claim(renderer.functionName(entry.fn.id), describeFunction(entry));
632
+ for (const entry of authored.records ?? [])
633
+ claim(renderer.structureName(entry.item.id), describeItem("record", entry));
634
+ for (const entry of authored.presets ?? [])
635
+ for (const name of renderer.presetValueNames(entry.item.id))
636
+ claim(name, describeItem("preset type", entry));
447
637
  }
448
638
  /** Why a Blueprint trigger's Galaxy can't be written, from the renderer's unknown parts. */
449
639
  function unrenderable(entry, unknown) {
@@ -488,8 +678,9 @@ function withGlobals(script, globals) {
488
678
  * depth first through the folders as the Editor writes them: the splice keeps each where the
489
679
  * package has it, while the compile's own go to the end, so the order holds from one compile to the
490
680
  * next. In the script each trigger's declaration, section and _Init call go before the compile's
491
- * own, in that same order, as the Editor writes the tree's. A Blueprint trigger with a Kept
492
- * trigger's Id is that one converted (convert-mission-triggers.ts): it may give the Kept one's
681
+ * own, in that same order, as the Editor writes the tree's; each function's declaration and
682
+ * definition in sections of their own (withFunctions), and each record's, preset type's and custom script's too (withItems). A Blueprint element with a Kept
683
+ * one's Id is that one converted (convert-mission-triggers.ts): it may give the Kept one's
493
684
  * Ids, and is returned in `converted`, for the Equivalence Check. Refused, naming each element and
494
685
  * why, when an Id clashes or a reference is out of reach (BlueprintTriggerError), or when its
495
686
  * Galaxy can't be written.
@@ -500,7 +691,7 @@ export function compileBlueprintTriggers(authored, generated, { kept, libraries
500
691
  const problems = [];
501
692
  const keptOwn = keptElements(kept);
502
693
  const generatedFile = readTriggersFile(generated.triggers);
503
- const tree = folderTree(authored, problems);
694
+ const tree = folderTree(authored, problems, (type, id) => keptOwn.has(elementKey(type, id)), (id) => [...(keptOwn.get(elementKey("Category", id)) ?? "").matchAll(/<Item Type="(\w+)"(?: Library="[^"]*")? Id="([0-9A-F]{8})"\/>/g)].map((match) => `${itemKind(match[1]) ?? match[1]}:${match[2]}`));
504
695
  // A Blueprint trigger with a Kept trigger's Id is that one converted (convert-mission-triggers): it gives the Ids the Kept one's elements have.
505
696
  const converting = convertedKept(authored, kept);
506
697
  const replaced = new Set([...converting.values()].flat());
@@ -510,12 +701,42 @@ export function compileBlueprintTriggers(authored, generated, { kept, libraries
510
701
  throw new BlueprintTriggerError(problems);
511
702
  // Triggers: the Root lines, then the elements, depth first.
512
703
  const byId = new Map(authored.triggers.map((entry) => [entry.trigger.id, entry]));
704
+ const functionsById = new Map((authored.functions ?? []).map((entry) => [entry.fn.id, entry]));
705
+ const commentsById = new Map((authored.comments ?? []).map((entry) => [entry.comment.id, entry]));
513
706
  const globalsById = new Map((authored.variables ?? []).map((variable) => [variable.id, variable]));
707
+ const presetsById = new Map((authored.presets ?? []).map((entry) => [entry.item.id, entry]));
708
+ const recordsById = new Map((authored.records ?? []).map((entry) => [entry.item.id, entry]));
709
+ const customScriptsById = new Map((authored.customScripts ?? []).map((entry) => [entry.item.id, entry]));
514
710
  const order = [];
711
+ const functionOrder = [];
515
712
  const globalOrder = [];
713
+ const presetOrder = [];
714
+ const recordOrder = [];
715
+ const customScriptOrder = [];
516
716
  const elements = [];
517
717
  const visit = (item) => {
718
+ // A Kept item is the package's: the folder files it by its line alone.
719
+ if (tree.keptItems.has(item))
720
+ return;
518
721
  const { kind, id } = parseItem(item);
722
+ if (kind === "preset") {
723
+ const entry = presetsById.get(id);
724
+ presetOrder.push(entry);
725
+ elements.push(...blueprintPresetXml(entry.item));
726
+ return;
727
+ }
728
+ if (kind === "structure") {
729
+ const entry = recordsById.get(id);
730
+ recordOrder.push(entry);
731
+ elements.push(...blueprintRecordXml(entry.item));
732
+ return;
733
+ }
734
+ if (kind === "custom-script") {
735
+ const entry = customScriptsById.get(id);
736
+ customScriptOrder.push(entry);
737
+ elements.push(...blueprintCustomScriptXml(entry.item));
738
+ return;
739
+ }
519
740
  if (kind === "category") {
520
741
  const folder = tree.folders.get(id);
521
742
  elements.push(folderXml(folder));
@@ -530,6 +751,18 @@ export function compileBlueprintTriggers(authored, generated, { kept, libraries
530
751
  elements.push(...writer.elements);
531
752
  return;
532
753
  }
754
+ if (kind === "comment") {
755
+ const writer = new ElementWriter(undefined, ELEMENT);
756
+ writer.statement(commentsById.get(id).comment);
757
+ elements.push(...writer.elements);
758
+ return;
759
+ }
760
+ if (kind === "function") {
761
+ const entry = functionsById.get(id);
762
+ functionOrder.push(entry);
763
+ elements.push(...blueprintFunctionXml(entry.fn));
764
+ return;
765
+ }
533
766
  const entry = byId.get(id);
534
767
  order.push(entry);
535
768
  elements.push(...blueprintTriggerXml(entry.trigger));
@@ -554,10 +787,28 @@ export function compileBlueprintTriggers(authored, generated, { kept, libraries
554
787
  for (const variable of trigger.variables)
555
788
  triggerStrings[`Variable/Name/${variable.id}`] = variable.name;
556
789
  }
790
+ for (const { fn } of authored.functions ?? []) {
791
+ const { fn: form, body } = libraryForm(fn);
792
+ Object.assign(triggerStrings, functionStrings(undefined, form, body));
793
+ }
794
+ for (const { item: preset } of authored.presets ?? []) {
795
+ triggerStrings[`Preset/Name/${preset.id}`] = preset.name;
796
+ for (const value of preset.values)
797
+ if ("name" in value)
798
+ triggerStrings[`PresetValue/Name/${value.id}`] = value.name;
799
+ }
800
+ for (const { item: record } of authored.records ?? []) {
801
+ triggerStrings[`Structure/Name/${record.id}`] = record.name;
802
+ for (const member of record.members)
803
+ triggerStrings[`Variable/Name/${member.id}`] = member.name;
804
+ }
805
+ for (const { item: script } of authored.customScripts ?? [])
806
+ triggerStrings[`CustomScript/Name/${script.id}`] = script.name;
557
807
  const gameStrings = {};
558
- for (const { trigger } of authored.triggers)
559
- for (const [file, strings] of Object.entries(trigger.strings ?? {}))
808
+ for (const element of [...authored.triggers.map(({ trigger }) => trigger), ...(authored.functions ?? []).map(({ fn }) => fn)]) {
809
+ for (const [file, strings] of Object.entries(element.strings ?? {}))
560
810
  Object.assign((gameStrings[file] ??= {}), strings);
811
+ }
561
812
  // Galaxy, by the Kept renderer, from the Triggers with the Kept elements in reach.
562
813
  const writtenFile = readTriggersFile(triggers);
563
814
  const keptText = [...keptOwn].filter(([key]) => !writtenFile.elements.has(key) && !replaced.has(key)).map(([, text]) => crlf(text).replace(/(\r\n)?$/, "\r\n")).join("");
@@ -589,10 +840,38 @@ export function compileBlueprintTriggers(authored, generated, { kept, libraries
589
840
  else if (section !== "")
590
841
  written.push({ name: renderer.triggerName(entry.trigger.id), section });
591
842
  }
843
+ const functionGalaxy = [];
844
+ for (const entry of functionOrder) {
845
+ const definition = renderer.renderFunction(entry.fn.id);
846
+ const declaration = definition === undefined ? undefined : functionDeclaration(definition, renderer.functionName(entry.fn.id));
847
+ if (definition === undefined)
848
+ problems.push(`${describeFunction(entry)} can't be written as Galaxy: it holds ${unknownParts(renderer.unknown)}`);
849
+ else if (declaration === undefined)
850
+ problems.push(`${describeFunction(entry)} can't be written as Galaxy: its definition has no signature to declare it by`);
851
+ else
852
+ functionGalaxy.push({ declaration, definition });
853
+ }
854
+ const structures = [];
855
+ for (const entry of recordOrder) {
856
+ const struct = renderer.renderStructure(entry.item.id);
857
+ if (struct === undefined)
858
+ problems.push(`${describeItem("record", entry)} can't be written as Galaxy: it holds ${unknownParts(renderer.unknown)}`);
859
+ else
860
+ structures.push(struct);
861
+ }
862
+ const presetValues = [];
863
+ for (const entry of presetOrder) {
864
+ const constants = renderer.renderPreset(entry.item.id);
865
+ if (constants === undefined)
866
+ problems.push(`${describeItem("preset type", entry)} can't be written as Galaxy: it holds ${unknownParts(renderer.unknown)}`);
867
+ else
868
+ presetValues.push(...constants.map(({ line }) => line));
869
+ }
870
+ const customScripts = customScriptOrder.map(({ item }) => ({ block: customScriptGalaxy(item), ...(item.initFunction ? { init: ` ${item.initFunction}();\r\n` } : {}) }));
592
871
  if (problems.length > 0)
593
872
  throw new BlueprintTriggerError(problems);
594
873
  // Each before the compile's own, as in Triggers.
595
- let script = withGlobals(generated.script, globals);
874
+ let script = withItems(withFunctions(withGlobals(generated.script, globals), functionGalaxy), { structures, presetValues, customScripts });
596
875
  const declarations = find(script, /^\/\/ Trigger Variables\r\n\/\/-+\r\n/m, "map script's Trigger Variables");
597
876
  script = insertAt(script, declarations.index + declarations[0].length, written.map(({ name }) => `trigger ${name};\r\n`).join(""));
598
877
  const firstSection = script.search(new RegExp(`^${RULE}\\r\\n// Trigger: `, "m"));
@@ -600,23 +879,99 @@ export function compileBlueprintTriggers(authored, generated, { kept, libraries
600
879
  script = insertAt(script, firstSection >= 0 && firstSection < initialization.index ? firstSection : initialization.index, written.map(({ section }) => section).join(""));
601
880
  const inits = find(script, /^void InitTriggers \(\) \{\r\n/m, "map script's InitTriggers");
602
881
  script = insertAt(script, inits.index + inits[0].length, written.map(({ name }) => ` ${name}_Init();\r\n`).join(""));
603
- const converted = [...converting.keys()].map((id) => ({ id, scriptName: renderer.triggerName(id), disabled: byId.get(id).trigger.disabled === true }));
882
+ const converted = [...converting.keys()].map((key) => {
883
+ const [type, id] = key.split("/");
884
+ const named = (kind, prefixes, name) => ({ kind, id, blocks: prefixes.map((prefix) => `${prefix}:${name}`) });
885
+ if (type === "FunctionDef")
886
+ return named("function", ["function-declaration", "function"], renderer.functionName(id));
887
+ if (type === "Variable")
888
+ return named("variable", ["variable", "variable-init"], renderer.variableGalaxyName(id));
889
+ if (type === "Structure")
890
+ return named("structure", ["structure"], renderer.structureName(id));
891
+ if (type === "Preset")
892
+ return { kind: "preset", id, blocks: renderer.presetValueNames(id).map((name) => `preset-value:${name}`) };
893
+ if (type === "CustomScript") {
894
+ const { item } = customScriptsById.get(id);
895
+ return { kind: "custom-script", id, blocks: [`custom-script:${item.name}`, ...(item.initFunction ? [`custom-script-init:${item.initFunction}`] : [])] };
896
+ }
897
+ // A comment or a folder has no Galaxy, nor a disabled trigger.
898
+ if (type === "Comment")
899
+ return { kind: "comment", id, blocks: [] };
900
+ if (type === "Category")
901
+ return { kind: "category", id, blocks: [] };
902
+ return byId.get(id).trigger.disabled === true ? { kind: "trigger", id, blocks: [] } : named("trigger", ["trigger-variable", "trigger", "trigger-init"], renderer.triggerName(id));
903
+ });
604
904
  return { triggers, script, triggerStrings, gameStrings, converted };
605
905
  }
606
906
  /**
607
- * The Blueprint triggers that are Kept triggers converted: each Blueprint trigger whose Id a Kept
608
- * Trigger in the package has, by Id, with the element keys of the Kept one's elements, which it
609
- * writes over.
907
+ * `script` (the compile's, CRLF) with the records' structs, the preset types' constants and the
908
+ * custom scripts in their sections, as the Editor writes them: Global Structures after the libraries
909
+ * (and Constants), before Global Preset Declarations and the globals; Global Preset Declarations
910
+ * before the globals, and an empty Global Presets after Trigger Variables; Custom Script before
911
+ * Global Functions and the trigger sections, ending with InitCustomScript, which InitMap calls after
912
+ * InitGlobals. The compile writes none of its own, so each section is made here.
913
+ */
914
+ function withItems(script, { structures, presetValues, customScripts }) {
915
+ const before = (titles, what) => find(script, new RegExp(`^${RULE}\\r\\n// (?:${titles})\\r?\\n`, "m"), what).index;
916
+ if (structures.length > 0)
917
+ script = insertAt(script, before("Global Preset Declarations|Global Variables|Global Function Declarations|Trigger Variables", "map script's Trigger Variables"), `${RULE}\r\n// Global Structures\r\n${RULE}\r\n${structures.join("")}`);
918
+ if (presetValues.length > 0) {
919
+ script = insertAt(script, before("Global Variables|Global Function Declarations|Trigger Variables", "map script's Trigger Variables"), `${RULE}\r\n// Global Preset Declarations\r\n${RULE}\r\n${presetValues.join("")}\r\n`);
920
+ script = insertAt(script, before("Global Functions|Trigger: [^\\r\\n]*|Trigger Initialization", "map script's Trigger Initialization"), `${RULE}\r\n// Global Presets\r\n${RULE}\r\n\r\n`);
921
+ }
922
+ if (customScripts.length > 0) {
923
+ const inits = customScripts.flatMap(({ init }) => (init ? [init] : [])).join("");
924
+ script = insertAt(script, before("Global Functions|Trigger: [^\\r\\n]*|Trigger Initialization", "map script's Trigger Initialization"), `${RULE}\r\n// Custom Script\r\n${RULE}\r\n${customScripts.map(({ block }) => block).join("")}void InitCustomScript () {\r\n${inits}}\r\n\r\n`);
925
+ const map = find(script, /^void InitMap \(\) \{\r\n {4}InitLibs\(\);\r\n(?: {4}InitGlobals\(\);\r\n)?/m, "map script's InitMap");
926
+ script = insertAt(script, map.index + map[0].length, " InitCustomScript();\r\n");
927
+ }
928
+ return script;
929
+ }
930
+ /** A function's declaration, from its definition (renderFunction's): its signature line, ended `;` in place of ` {`; undefined where it has none. */
931
+ export function functionDeclaration(definition, name) {
932
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
933
+ const signature = new RegExp(`^(\\S[^\\r\\n(]* ${escaped} \\([^\\r\\n]*\\)) \\{\\r?$`, "m").exec(definition);
934
+ return signature ? `${signature[1]};` : undefined;
935
+ }
936
+ /**
937
+ * `script` (the compile's, CRLF) with the functions' declarations in a Global Function Declarations
938
+ * section and their definitions in a Global Functions section, as the Editor writes them: the first
939
+ * after Global Variables, before Trigger Variables, the second before the first trigger's section.
940
+ * The compile writes no function of its own, so both sections are made here.
941
+ */
942
+ function withFunctions(script, functions) {
943
+ if (functions.length === 0)
944
+ return script;
945
+ const variables = find(script, new RegExp(`^${RULE}\\r\\n// Trigger Variables\\r\\n`, "m"), "map script's Trigger Variables").index;
946
+ script = insertAt(script, variables, `${RULE}\r\n// Global Function Declarations\r\n${RULE}\r\n${functions.map(({ declaration }) => `${declaration}\r\n`).join("")}\r\n`);
947
+ const initialization = find(script, new RegExp(`^${RULE}\\r\\n// Trigger Initialization\\r\\n`, "m"), "map script's Trigger Initialization").index;
948
+ const firstSection = script.search(new RegExp(`^${RULE}\\r\\n// Trigger: `, "m"));
949
+ return insertAt(script, firstSection >= 0 && firstSection < initialization ? firstSection : initialization, `${RULE}\r\n// Global Functions\r\n${RULE}\r\n${functions.map(({ definition }) => definition).join("")}`);
950
+ }
951
+ /**
952
+ * The Blueprint elements that are Kept ones converted: each Blueprint element, folder or global
953
+ * whose Id a Kept item of its type in the package has (a Trigger, FunctionDef, Comment, Category,
954
+ * Variable, Preset, Structure or CustomScript), by its element key (`Trigger/<id>`), with the
955
+ * element keys of the Kept one's elements, which it writes over.
610
956
  */
611
957
  function convertedKept(authored, kept) {
612
958
  const out = new Map();
613
959
  if (!kept)
614
960
  return out;
615
- const ids = new Set(authored.triggers.map(({ trigger }) => trigger.id));
961
+ const keys = new Set([
962
+ ...authored.triggers.map(({ trigger }) => elementKey("Trigger", trigger.id)),
963
+ ...(authored.functions ?? []).map(({ fn }) => elementKey("FunctionDef", fn.id)),
964
+ ...(authored.comments ?? []).map(({ comment }) => elementKey("Comment", comment.id)),
965
+ ...(authored.variables ?? []).map((variable) => elementKey("Variable", variable.id)),
966
+ ...authored.folders.map((folder) => elementKey("Category", folder.id)),
967
+ ...(authored.presets ?? []).map(({ item }) => elementKey("Preset", item.id)),
968
+ ...(authored.records ?? []).map(({ item }) => elementKey("Structure", item.id)),
969
+ ...(authored.customScripts ?? []).map(({ item }) => elementKey("CustomScript", item.id)),
970
+ ]);
616
971
  for (const [key, item] of libraryItems(kept.triggers)) {
617
- if (item.type !== "Trigger" || kept.compiled.has(key) || !ids.has(item.id))
972
+ if (kept.compiled.has(key) || !keys.has(elementKey(item.type, item.id)))
618
973
  continue;
619
- out.set(item.id, item.elements.flatMap((text) => {
974
+ out.set(elementKey(item.type, item.id), item.elements.flatMap((text) => {
620
975
  const match = /<Element Type="(\w+)" Id="([0-9A-F]+)"/.exec(text);
621
976
  return match ? [elementKey(match[1], match[2])] : [];
622
977
  }));