Open History to see the last commit
1import { z } from "zod";
2import { CATALOGUE, COLORS } from "./catalogue";
3import { bounds, connectorList, mask, mating, validPart } from "./geometry";
4import { CATALOGUE_VERSION, MAX_AI_PARTS, type Part } from "./types";
5import { expandDesign } from "./design";
6
7export { MAX_AI_PARTS } from "./types";
8export const blueprintSchema = z.object({
9 version: z.literal(1),
10 catalogue: z.literal(CATALOGUE_VERSION),
11 title: z.string().min(1).max(64),
12 summary: z.string().max(240),
13 parts: z
14 .array(
15 z.object({
16 id: z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,39}$/),
17 part: z.enum(CATALOGUE.map((p) => p.key) as [string, ...string[]]),
18 colour: z.enum(
19 COLORS.map((c) => c.name.toLowerCase()) as [string, ...string[]],
20 ),
21 turn: z.number().int().min(0).max(3),
22 // A homogeneous array produces a portable JSON Schema. Native Gateway
23 // structured output rejects tuple schemas with an array-valued `items`.
24 at: z.array(z.number()).length(3).nullable(),
25 attach: z
26 .object({
27 to: z.string().max(40),
28 connector: z.string().max(40),
29 ownConnector: z.string().max(40),
30 })
31 .nullable(),
32 }),
33 )
34 .min(1)
35 .max(MAX_AI_PARTS),
36});
37export type Blueprint = z.infer<typeof blueprintSchema>;
38export type BlueprintIssue = { code: string; parts: string[]; message: string };
39export type BlueprintEdge = {
40 a: string;
41 b: string;
42 ca: string;
43 cb: string;
44 exclusiveA: boolean;
45 exclusiveB: boolean;
46};
47export type CompiledBlueprint = {
48 blueprint: Blueprint;
49 parts: Part[];
50 edges: BlueprintEdge[];
51 issues: BlueprintIssue[];
52 issueCounts: Record<string, number>;
53};
54
55// Both the preview and server use this compiler. Attachment coordinates come
56// from the catalogue's actual connectors, rather than model arithmetic.
57export function compileBlueprint(input: unknown): CompiledBlueprint {
58 const blueprint = blueprintSchema.parse(
59 input &&
60 typeof input === "object" &&
61 "version" in input &&
62 input.version === 2
63 ? expandDesign(input)
64 : input,
65 );
66 const issues: BlueprintIssue[] = [];
67 const issueCounts: Record<string, number> = {};
68 const issue = (code: string, parts: string[], message: string) => {
69 issueCounts[code] = (issueCounts[code] || 0) + 1;
70 if (issues.length < 30) issues.push({ code, parts, message });
71 };
72 const specs = new Map(blueprint.parts.map((p) => [p.id, p]));
73 if (specs.size !== blueprint.parts.length)
74 issue("duplicate_id", [], "Every part must have a unique local id.");
75 const resolved = new Map<string, Part>();
76 const visiting = new Set<string>();
77 const resolve = (id: string): Part | undefined => {
78 if (resolved.has(id)) return resolved.get(id);
79 const spec = specs.get(id);
80 if (!spec) return undefined;
81 if (visiting.has(id)) {
82 issue("attachment_cycle", [id], "Attachments must not form a cycle.");
83 return;
84 }
85 visiting.add(id);
86 const p: Part = {
87 id,
88 key: spec.part,
89 color: COLORS.find((c) => c.name.toLowerCase() === spec.colour)!.hex,
90 position: { x: 0, y: 0, z: 0 },
91 rotation: spec.turn,
92 revision: 1,
93 };
94 if ((spec.at === null) === (spec.attach === null)) {
95 issue(
96 "placement",
97 [id],
98 "Provide exactly one of at or attach; set the other to null.",
99 );
100 } else if (spec.at) {
101 const values = [spec.at[0] * 6, spec.at[1] * 2, spec.at[2] * 6];
102 if (
103 !values.every(
104 (v) =>
105 Number.isSafeInteger(Math.round(v)) &&
106 Math.abs(v - Math.round(v)) < 1e-8,
107 )
108 )
109 issue(
110 "grid",
111 [id],
112 "Horizontal coordinates must be sixth-stud aligned; vertical coordinates must be half-plate aligned.",
113 );
114 p.position = {
115 x: Math.round(values[0]),
116 y: Math.round(values[1]),
117 z: Math.round(values[2]),
118 };
119 } else if (spec.attach) {
120 const target = resolve(spec.attach.to);
121 const a =
122 target &&
123 connectorList(target).find((c) => c.id === spec.attach!.connector);
124 const b = connectorList(p).find(
125 (c) => c.id === spec.attach!.ownConnector,
126 );
127 if (!a || !b)
128 issue(
129 "connector",
130 [id, spec.attach.to],
131 "Attachment names an unknown part or connector.",
132 );
133 else {
134 p.position = {
135 x: a.at.x - b.at.x,
136 y: a.at.y - b.at.y,
137 z: a.at.z - b.at.z,
138 };
139 const moved = connectorList(p).find((c) => c.id === b.id)!;
140 if (!mating(a, moved))
141 issue(
142 "connector_fit",
143 [id, spec.attach.to],
144 "Connectors do not mate with this turn. Check connector types and axes.",
145 );
146 }
147 }
148 visiting.delete(id);
149 if (!validPart(p))
150 issue(
151 "bounds",
152 [id],
153 "Part is outside the 32 × 32 stud board or 48-plate height.",
154 );
155 resolved.set(id, p);
156 return p;
157 };
158 blueprint.parts.forEach((p) => resolve(p.id));
159 const parts = [...resolved.values()];
160 if (issues.length)
161 return { blueprint, parts, edges: [], issues, issueCounts };
162
163 const occupied = new Map<string, string>();
164 const clashes = new Set<string>();
165 const cells = new Map(parts.map((p) => [p.id, mask(p)]));
166 for (const p of parts)
167 for (const cell of cells.get(p.id)!) {
168 const k = `${cell.x},${cell.y},${cell.z}`,
169 other = occupied.get(k);
170 if (other) {
171 const pair = [other, p.id].sort().join("/");
172 if (!clashes.has(pair)) {
173 clashes.add(pair);
174 issue(
175 "overlap",
176 [other, p.id],
177 "Parts overlap. Adjust the placement or attachment.",
178 );
179 }
180 } else occupied.set(k, p.id);
181 }
182
183 const connectors = new Map<
184 string,
185 { part: Part; connector: ReturnType<typeof connectorList>[number] }[]
186 >();
187 const edges: BlueprintEdge[] = [],
188 slots = new Map<string, string>();
189 const graph = new Map(parts.map((p) => [p.id, new Set<string>()]));
190 for (const p of parts)
191 for (const connector of connectorList(p)) {
192 const k = `${connector.axis}/${connector.at.x},${connector.at.y},${connector.at.z}`;
193 const previous = connectors.get(k) || [];
194 for (const other of previous)
195 if (other.part.id !== p.id && mating(connector, other.connector)) {
196 const edge = {
197 a: other.part.id,
198 b: p.id,
199 ca: other.connector.id,
200 cb: connector.id,
201 exclusiveA: other.connector.exclusive,
202 exclusiveB: connector.exclusive,
203 };
204 edges.push(edge);
205 graph.get(edge.a)!.add(edge.b);
206 graph.get(edge.b)!.add(edge.a);
207 for (const [partId, c] of [
208 [p.id, connector],
209 [other.part.id, other.connector],
210 ] as const)
211 if (c.exclusive) {
212 const slot = `${partId}/${c.id}`;
213 // Colliding parts also create duplicate connector claims. Keep
214 // repair feedback focused on the geometric cause in that case.
215 if (slots.has(slot) && !clashes.size)
216 issue(
217 "connector_taken",
218 [partId, p.id, other.part.id],
219 `Connector ${c.id} is claimed by multiple connections.`,
220 );
221 slots.set(slot, k);
222 }
223 }
224 previous.push({ part: p, connector });
225 connectors.set(k, previous);
226 }
227 const grounded = new Set(
228 parts.filter((p) => bounds(p).miny === 0).map((p) => p.id),
229 );
230 // Mechanical mounts have no stud sockets. A part can also rest on a real
231 // upward surface. These directed support edges are quality evidence only;
232 // they never become invented connector records in the database.
233 const supportedBy = new Map(parts.map((p) => [p.id, new Set<string>()]));
234 for (const p of parts) {
235 const contacts = new Map<string, number>();
236 const bottom = bounds(p).miny;
237 for (const cell of cells.get(p.id)!) {
238 if (cell.y !== bottom) continue;
239 const below = occupied.get(`${cell.x},${cell.y - 1},${cell.z}`);
240 if (below && below !== p.id)
241 contacts.set(below, (contacts.get(below) || 0) + 1);
242 }
243 for (const [lower, area] of contacts)
244 if (area >= 9) supportedBy.get(lower)!.add(p.id);
245 }
246 const queue = [...grounded];
247 for (let i = 0; i < queue.length; i++)
248 for (const neighbour of [
249 ...graph.get(queue[i])!,
250 ...supportedBy.get(queue[i])!,
251 ])
252 if (!grounded.has(neighbour)) {
253 grounded.add(neighbour);
254 queue.push(neighbour);
255 }
256 for (const p of parts)
257 if (!grounded.has(p.id))
258 issue(
259 "unattached",
260 [p.id],
261 "Part has no supported path to the board. Connect it, rest its bottom on a supported surface, or place it on the board.",
262 );
263 return { blueprint, parts, edges, issues, issueCounts };
264}
265
266export function catalogueForAI() {
267 return CATALOGUE.map((d) => {
268 const p: Part = {
269 id: "example",
270 key: d.key,
271 color: COLORS[0].hex,
272 position: { x: 0, y: 0, z: 0 },
273 rotation: 0,
274 revision: 1,
275 };
276 return {
277 part: d.key,
278 size: [d.w, d.h, d.d],
279 connectors: connectorList(p).map((c) => ({
280 id: c.id,
281 type: c.type,
282 at: [c.at.x / 6, c.at.y / 2, c.at.z / 6],
283 axis: c.axis,
284 })),
285 };
286 });
287}