// Node shapes and pin positions, all in grid units relative to the node's // (x, y). Pins always sit on whole grid points so straight wires line up. import type { CircuitNode, ComponentDef, ConnectorType, FaceShape, LampColor, PanelRow, SymbolKind } from './types' import { benchLayout } from './benchLayout' import { DATA_KEYS, DEVICE_PIN_NAMES } from './devices' export const GRID = 16 export interface PinInfo { key: string label: string dx: number dy: number /** A cable pin: only joins another cable pin. */ bus?: boolean /** A port of a connector type: only joins a port of the same type (and is a cable pin). */ conn?: string /** Side the wire leaves (outputs) or arrives from (inputs): 1 right, -1 left. Default: outputs right, inputs left. */ face?: 1 | -1 /** A line of a port split on a component's box: the port's key. */ port?: string } export interface Shape { body: { x: number; y: number; w: number; h: number } inputs: PinInfo[] outputs: PinInfo[] /** Set when the node draws as a logic gate symbol. */ gate?: SymbolKind /** Vertical centre of the pin area, where a box prints its name. */ nameY?: number /** Lamps and displays from inside the component, shown on its box. */ face?: FaceItem[] /** Where a box prints its name (its middle), or null when it is left off; empty: centred. */ nameAt?: { x: number; y: number } | null /** Drawings on a hand-drawn box, in grid units relative to the chip node. */ drawing?: FaceShape[] } /** What an RGB pixel shows for its red, green and blue inputs (index r + 2g + 4b); black is off. */ export const RGB_HEX = ['', '#ff4d4d', '#3ddc84', '#ffe04d', '#4d7dff', '#ff5cf0', '#4de8ff', '#f2f6fa'] as const export const rgbHex = (r: number, g: number, b: number) => RGB_HEX[(r ? 1 : 0) + (g ? 2 : 0) + (b ? 4 : 0)]! export interface ScreenPixel { /** Pixel node id inside the component. */ id: string /** Lit by its red, green and blue inputs. */ rgb?: boolean col: number row: number color?: LampColor } export interface FaceItem { /** Node id inside the component; for a screen, the first pixel's; a path (chip/…/node) for a display inside. */ id: string /** What a design calls it: the node id, 'screen' or 'screen:', or '/'. */ key: string /** Size and turn from a hand-drawn box. */ scale?: number rotate?: number /** A display of a component inside: that component's name. */ from?: string /** A pixel shown on its own: the key of the screen it is part of. */ screenOf?: string kind: 'lamp' | 'hex' | 'screen' /** Screen only: its pixels and the size of one, in grid units. */ pixels?: ScreenPixel[] px?: number label: string color?: LampColor /** Top-left corner and size in grid units, relative to the chip node. */ x: number y: number w: number h: number } /** Finds a component by id; `conn` finds a connector type (set by `lookup(project)`). */ export type DefLookup = ((id: string) => ComponentDef | undefined) & { conn?: (id: string) => ConnectorType | undefined } const LABEL_CHAR = 0.4 // grid units per character of a pin label const NAME_CHAR = 0.44 const FACE_CHAR = 0.34 export interface ChipPins { inputs: { key: string; label: string }[] outputs: { key: string; label: string }[] /** Connector ports, top to bottom: "in" ones sit with the inputs, "out" ones with the outputs. */ ports?: PortPin[] } export interface PortPin { /** The port node's id inside the component. */ key: string label: string conn: string side: 'in' | 'out' } /** What a pin plugs into: '' a single wire, 'bus' a cable end, 'c:' a port of that connector type. */ export const pinKindOf = (p: { bus?: boolean; conn?: string }) => (p.conn ? `c:${p.conn}` : p.bus ? 'bus' : '') /** Pin key of a panel row: the same key the row has as a switch in the simulator. */ export const rowPin = (panelId: string, rowId: string) => `${panelId}:${rowId}` /** What a port is called on a component's box: its own name, else its connector type's. */ export const portName = (p: PortPin, get?: DefLookup) => p.label || get?.conn?.(p.conn)?.name || 'port' /** Pin key of a line of a port split on a component's box: port.line (a dot, so it never reads as a panel row). */ export const linePin = (port: string, line: string) => `${port}.${line}` export interface SplitLine { /** Pin key on the box. */ key: string name: string /** The port's key, and the line's place in its connector type. */ port: string index: number /** The line goes into the component (an input pin on the box); otherwise it comes out (an output). */ enters: boolean } /** * The lines of the ports split on a placed component's box, top to bottom, * as pins of their own: inputs for lines going into the component, outputs * for lines coming out. An in port brings its forward lines in, an out port * its back lines. */ export function splitLines(node: CircuitNode, pins: ChipPins, get?: DefLookup): SplitLine[] { if (!node.splitPorts?.length) return [] const split = new Set(node.splitPorts) const out: SplitLine[] = [] for (const p of pins.ports ?? []) { if (!split.has(p.key)) continue get?.conn?.(p.conn)?.lines.forEach((l, i) => out.push({ key: linePin(p.key, `l${i}`), name: l.name, port: p.key, index: i, enters: (p.side === 'in') !== !!l.back })) } return out } /** Panel rows that are input pins of their component: switches and buttons, unless the panel keeps them inside. */ export const isPinRow = (panel: CircuitNode, row: PanelRow) => !panel.inner && row.type !== 'clock' /** * A component's pins, ordered top to bottom: its input and output nodes, * and the switch and button rows of its input panels, which count as inputs. */ export function chipPins(def: ComponentDef): ChipPins { const inputs: { key: string; label: string; x: number; y: number }[] = [] for (const n of def.nodes) { if (n.kind === 'input') inputs.push({ key: n.id, label: n.label?.trim() ?? '', x: n.x, y: n.y }) else if (n.kind === 'panel') { const rows = n.rows ?? [] const at = panelOffsets(rows) rows.forEach((r, i) => { if (isPinRow(n, r)) inputs.push({ key: rowPin(n.id, r.id), label: r.label?.trim() || r.name?.trim() || '', x: n.x, y: n.y + at[i]! }) }) } } inputs.sort((a, b) => a.y - b.y || a.x - b.x) // Outputs: output pins and the rows of output panels. const outputs: { key: string; label: string; x: number; y: number }[] = [] for (const n of def.nodes) { if (n.kind === 'output') outputs.push({ key: n.id, label: n.label?.trim() ?? '', x: n.x, y: n.y }) else if (n.kind === 'outpanel' && !n.inner) { const rows = n.rows ?? [] const at = panelOffsets(rows) rows.forEach((r, i) => outputs.push({ key: rowPin(n.id, r.id), label: r.label?.trim() || r.name?.trim() || '', x: n.x, y: n.y + at[i]! })) } } outputs.sort((a, b) => a.y - b.y || a.x - b.x) const ports = def.nodes .filter(n => (n.kind === 'portin' || n.kind === 'portout') && n.conn) .sort((a, b) => a.y - b.y || a.x - b.x) .map(n => ({ key: n.id, label: n.label?.trim() ?? '', conn: n.conn!, side: n.kind === 'portin' ? ('in' as const) : ('out' as const) })) return { inputs: inputs.map((p, i) => ({ key: p.key, label: p.label || `in${i + 1}` })), outputs: outputs.map((p, i) => ({ key: p.key, label: p.label || `out${i + 1}` })), ...(ports.length ? { ports } : {}), } } /** * Lamps and hex displays inside a component, arranged on its box the way * they are placed inside: nodes at about the same height share a row. */ export function faceLayout(def: ComponentDef): { items: FaceItem[]; w: number; h: number } { const empty = { items: [], w: 0, h: 0 } if (def.face === false) return empty return autoFace(def, ownFaceItems(def)) } /** The lamps, displays and screens of a component itself, before they are laid out. */ function ownFaceItems(def: ComponentDef): FaceItem[] { const items: FaceItem[] = [] for (const n of def.nodes) { if (n.kind !== 'lamp' && n.kind !== 'hex') continue const label = n.label?.trim() ?? '' const w = Math.max(n.kind === 'hex' ? 1.6 : 1.4, label.length * FACE_CHAR + 0.4) const h = (n.kind === 'hex' ? 2.2 : 1.2) + (label ? 0.7 : 0) items.push({ id: n.id, key: n.id, kind: n.kind, label, color: n.color, x: n.x, y: n.y, w, h }) } return [...items, ...screenLayouts(def)] } /** * Lays the items out the way they sit inside: lamps and displays at about * the same height share a row, screens go below. */ function autoFace(def: ComponentDef, all: FaceItem[]): { items: FaceItem[]; w: number; h: number } { const empty = { items: [], w: 0, h: 0 } void def // The x and y of an item here are where its node sits inside, used for ordering. const nodes = all.filter(it => it.kind !== 'screen').sort((a, b) => a.y - b.y || a.x - b.x) const rows: FaceItem[][] = [] for (const n of nodes) { const row = rows[rows.length - 1] if (row && Math.abs(n.y - row[0]!.y) <= 1) row.push(n) else rows.push([n]) } const items: FaceItem[] = [] let y = 0 let w = 0 for (const row of rows) { row.sort((a, b) => a.x - b.x) let x = 0 let h = 0 for (const n of row) { items.push({ ...n, x, y }) x += n.w + 0.3 h = Math.max(h, n.h) } w = Math.max(w, x - 0.3) y += h + 0.3 } for (const screen of all.filter(it => it.kind === 'screen')) { w = Math.max(w, screen.w) items.push({ ...screen, x: (w - screen.w) / 2, y }) y += screen.h + 0.3 } if (!items.length) return empty return { items, w, h: y - 0.3 } } /** * What a component shows on its box, for a component placed inside another * one to offer: the items its own design shows (or all, laid out * automatically), including displays of components inside it it shows. */ function shownItems(def: ComponentDef, get: DefLookup, depth: number): FaceItem[] { if (def.face === false || depth > 4) return [] const d = def.design const hide = new Set(d?.hide ?? []) // As its own box shows them: turned and sized the same, screens split into pixels where it does. const looks = (it: FaceItem): FaceItem => ({ ...it, ...(d?.scale?.[it.key] ? { scale: d.scale[it.key] } : {}), ...(d?.rotate?.[it.key] ? { rotate: d.rotate[it.key] } : {}), }) const own = splitScreens(ownFaceItems(def), new Set(d?.split ?? [])).filter(it => !hide.has(it.key)).map(looks) if (!d?.show?.length) return own const show = new Set(d.show) return [...own, ...nestedItems(def, get, depth).filter(it => show.has(it.key)).map(looks)] } /** * Everything a component's box can show, for the box designer: its own * lamps, displays and screens (shown unless left off), and the displays of * components inside it (left off unless shown). */ export function faceCandidates(def: ComponentDef, get: DefLookup): { key: string; label: string; kind: FaceItem['kind']; nested: boolean }[] { if (def.face === false) return [] const own = ownFaceItems(def).map(it => ({ key: it.key, label: it.label || (it.kind === 'screen' ? 'Screen' : it.kind === 'hex' ? 'Display' : 'Lamp'), kind: it.kind, nested: false })) const nested = nestedItems(def, get).map(it => ({ key: it.key, label: [it.from, it.label].filter(Boolean).join(' ') || it.kind, kind: it.kind, nested: true })) return [...own, ...nested] } /** The key of one pixel of a screen shown pixel by pixel. */ export const pixelKey = (pixelId: string) => `px:${pixelId}` /** * Screens listed in `split` shown pixel by pixel: each pixel its own item, * where it sat in the screen (sized and turned as the screen was, `looks`), * so splitting moves nothing. */ export function splitScreens(items: FaceItem[], split: Set, looks: (key: string) => { scale?: number; rotate?: number } = () => ({})): FaceItem[] { if (!split.size) return items return items.flatMap(it => { if (it.kind !== 'screen' || !split.has(it.key) || !it.pixels || !it.px) return [it] const { scale, rotate } = { scale: it.scale, rotate: it.rotate, ...looks(it.key) } const k = scale ?? 1 const px = it.px! // The screen's middle; each pixel's middle turned around it. const cx = it.x + (it.w * k) / 2 const cy = it.y + (it.h * k) / 2 const turn = (((rotate ?? 0) % 360) + 360) % 360 return it.pixels.map(p => { let dx = (p.col + 0.5) * px * k - (it.w * k) / 2 let dy = (p.row + 0.5) * px * k - (it.h * k) / 2 for (let a = 0; a < turn; a += 90) [dx, dy] = [-dy, dx] const item: FaceItem = { ...it, id: p.id, key: pixelKey(p.id), label: '', x: cx + dx - (px * k) / 2, y: cy + dy - (px * k) / 2, w: px, h: px, pixels: [{ ...p, col: 0, row: 0 }], screenOf: it.key, } delete item.rotate if (k !== 1) item.scale = k else delete item.scale return item }) }) } /** A box item's size and turn, as an SVG transform: grown from its top left corner, turned around its middle. */ export function faceTransform(f: FaceItem): string | undefined { if (!f.scale && !f.rotate) return undefined const k = f.scale ?? 1 const x = f.x * GRID const y = f.y * GRID const cx = x + (f.w * k * GRID) / 2 const cy = y + (f.h * k * GRID) / 2 return `${f.rotate ? `rotate(${f.rotate} ${cx} ${cy}) ` : ''}translate(${x} ${y}) scale(${k}) translate(${-x} ${-y})` } /** A drawing on a box turned around its middle, as an SVG transform. */ export function shapeTransform(d: FaceShape): string | undefined { if (!d.rotate) return undefined const w = d.kind === 'text' ? (d.text?.length ?? 1) * 0.42 * (d.size ?? 1) : d.w const h = d.kind === 'text' ? (d.size ?? 1) : d.h return `rotate(${d.rotate} ${(d.x + w / 2) * GRID} ${(d.y + h / 2) * GRID})` } /** Displays of the components inside one: each keyed by its chip node and its own key there. */ export function nestedItems(def: ComponentDef, get: DefLookup, depth = 0): FaceItem[] { const out: FaceItem[] = [] for (const n of def.nodes) { if (n.kind !== 'chip' || !n.chip || n.chip === def.id) continue const child = get(n.chip) if (!child) continue const name = n.label?.trim() || child.name for (const it of shownItems(child, get, depth + 1)) { out.push({ ...it, id: `${n.id}/${it.id}`, key: `${n.id}/${it.key}`, // On the box it keeps its own name; the designer lists it with the part's. from: name, pixels: it.pixels?.map(p => ({ ...p, id: `${n.id}/${p.id}` })), }) } } return out } /** * Pixels inside a component, drawn as one screen without gaps: every * distinct column and row they sit on becomes a column and row of the * screen, so they can be spaced out inside for wiring. */ export function screenLayout(def: ComponentDef): FaceItem | null { return screenLayouts(def)[0] ?? null } /** Pixels make one screen per screen name (those without a name the main screen, listed first). */ export function screenLayouts(def: ComponentDef): FaceItem[] { const groups = new Map() for (const n of def.nodes) { if (n.kind !== 'pixel') continue const g = n.screen?.trim() ?? '' groups.set(g, [...(groups.get(g) ?? []), n]) } return [...groups.entries()] .sort(([a], [b]) => (a === '' ? -1 : b === '' ? 1 : a.localeCompare(b))) .map(([name, pixels]) => screenOf(pixels, name)) } function screenOf(pixels: CircuitNode[], name: string): FaceItem { const xs = [...new Set(pixels.map(n => n.x))].sort((a, b) => a - b) const ys = [...new Set(pixels.map(n => n.y))].sort((a, b) => a - b) const col = new Map(xs.map((x, i) => [x, i])) const row = new Map(ys.map((y, i) => [y, i])) const size = Math.max(xs.length, ys.length) const px = size <= 8 ? 1 : size <= 32 ? 0.5 : 0.25 return { id: pixels[0]!.id, key: name ? `screen:${name}` : 'screen', kind: 'screen', label: name, x: Math.min(...pixels.map(n => n.x)), y: Math.min(...pixels.map(n => n.y)), w: xs.length * px, h: ys.length * px, px, pixels: pixels.map(n => ({ id: n.id, col: col.get(n.x)!, row: row.get(n.y)!, color: n.color, ...(n.rgb ? { rgb: true } : {}) })), } } function gateShape(symbol: SymbolKind, inputs: { key: string; label: string }[], output: { key: string; label: string }): Shape { const n = inputs.length if (n === 1) { return { gate: symbol, body: { x: 0, y: -1, w: 3, h: 2 }, inputs: [{ ...inputs[0]!, dx: 0, dy: 0 }], outputs: [{ ...output, dx: 3, dy: 0 }], } } if (n === 2) { return { gate: symbol, body: { x: 0, y: -0.5, w: 4, h: 3 }, inputs: inputs.map((p, i) => ({ ...p, dx: 0, dy: i * 2 })), outputs: [{ ...output, dx: 4, dy: 1 }], } } return { gate: symbol, body: { x: 0, y: -0.5, w: 4, h: n }, inputs: inputs.map((p, i) => ({ ...p, dx: 0, dy: i })), outputs: [{ ...output, dx: 4, dy: Math.floor((n - 1) / 2) }], } } /** * A box drawn by hand: the size it was given (never shorter than its pins * need), everything placed where it was put, the rest where it would go * anyway, and its drawings. */ function designedShape(def: ComponentDef, pins: ChipPins, face: ReturnType, get: DefLookup, node?: CircuitNode): Shape { const auto = boxShape(def.name, pins, face, get, node) const d = def.design! const top = auto.body.y const hide = new Set(d.hide ?? []) const place = d.place ?? {} // Pins on each edge, top to bottom (in the order set, else as they come): where they were put, the others one row under the pin above. const order = new Map((d.pinOrder ?? []).map((k, i) => [k, i])) const rank = (p: PinInfo) => order.get(p.key) ?? 1e6 + p.dy const placePins = (list: PinInfo[]) => { let prev = -Infinity // The first pin takes the edge's first row, whichever pin that is. const first = Math.min(...list.map(p => p.dy)) return list .sort((a, b) => rank(a) - rank(b) || a.dy - b.dy) .map(p => { const want = d.pinAt?.[p.key] const dy = Math.max(want ?? (prev === -Infinity ? first : prev + 1), prev + 1, 0) prev = dy return [p.key, dy] as const }) } const edgePins = [...auto.inputs, ...auto.outputs] const rightPins = edgePins.filter(p => p.dx > 0) const rows = new Map([...placePins(edgePins.filter(p => p.dx === 0)), ...placePins(rightPins)]) const lowest = Math.max(0, ...rightPins.map(p => d.pinAt?.[p.key] ?? p.dy)) const bottom = Math.max(lowest, ...rows.values()) // Fitted: as wide as its pin names and its name need, as high as its pins; what it shows makes it bigger. const longest = (ps: PinInfo[]) => ps.reduce((m, p) => Math.max(m, p.label.length), 0) const labels = Math.ceil(longest(edgePins.filter(p => p.dx === 0)) * LABEL_CHAR + longest(rightPins) * LABEL_CHAR + (hide.has('name') || place.name ? 0 : def.name.length * NAME_CHAR) + 1.5) const w = d.fit ? Math.max(2, labels) : Math.max(2, d.w) const h = d.fit ? Math.max(bottom - top + 0.5, 2) : Math.max(d.h, bottom - top + 0.5, 2) // Own items where the automatic layout put them unless placed; displays of parts inside only when shown, // each in the first free spot unless placed. Screens split into pixels where asked: each pixel where it // sat in the screen as placed, unless placed on its own. const show = new Set(d.show ?? []) const split = new Set(d.split ?? []) const placed = (it: FaceItem): FaceItem => (place[it.key] ? { ...it, x: place[it.key]!.x, y: top + place[it.key]!.y } : it) const sized = (it: FaceItem) => { const k = d.scale?.[it.key] ?? it.scale ?? 1 const turned = (d.rotate?.[it.key] ?? it.rotate) === 90 || (d.rotate?.[it.key] ?? it.rotate) === 270 return { w: (turned ? it.h : it.w) * k, h: (turned ? it.w : it.h) * k } } const own = (auto.face ?? []).filter(it => !hide.has(it.key)).map(placed) const nestedAll = nestedItems(def, get).filter(it => show.has(it.key) && !hide.has(it.key)) const taken: { x: number; y: number; w: number; h: number }[] = own.map(it => ({ x: it.x, y: it.y, ...sized(it) })) // The name, where it shows. if (!hide.has('name')) { const nw = def.name.length * NAME_CHAR + 0.4 const c = place.name ? { x: place.name.x, y: top + place.name.y } : { x: w / 2, y: auto.nameY ?? 0 } taken.push({ x: c.x - nw / 2, y: c.y - 0.55, w: nw, h: 1.1 }) } for (const it of nestedAll) if (place[it.key]) taken.push({ x: place[it.key]!.x, y: top + place[it.key]!.y, ...sized(it) }) const labelL = longest(edgePins.filter(p => p.dx === 0)) * LABEL_CHAR + 0.6 const labelR = longest(rightPins) * LABEL_CHAR + 0.6 const nested = nestedAll.map(it => { if (place[it.key]) return placed(it) const spot = freeSpot(taken, sized(it), { x0: labelL, x1: Math.max(w - labelR, labelL + sized(it).w), y0: top + 0.3 }) taken.push({ ...spot, ...sized(it) }) return { ...it, ...spot } }) const looks = (key: string) => ({ ...(d.scale?.[key] ? { scale: d.scale[key] } : {}), ...(d.rotate?.[key] ? { rotate: d.rotate[key] } : {}) }) const items = splitScreens([...own, ...nested], split, looks) .filter(it => !hide.has(it.key)) .map(it => (it.screenOf ? placed(it) : it)) // Sized and turned as this box says, else as the part inside shows it. const shown = items.map(it => { const out: FaceItem = { ...it } const scale = d.scale?.[it.key] ?? it.scale const rotate = d.rotate?.[it.key] ?? it.rotate if (scale) out.scale = scale else delete out.scale if (rotate) out.rotate = rotate else delete out.rotate return out }) // The box is never smaller than what it shows (sized and turned as shown), its name and, fitted, its drawings. let right = w let floor = top + h if (d.fit) { for (const sh of d.shapes ?? []) { const tw = sh.kind === 'text' ? (sh.text?.length ?? 1) * 0.42 * (sh.size ?? 1) : 0 right = Math.max(right, sh.x + Math.max(sh.w, 0, tw) + 0.3) floor = Math.max(floor, top + sh.y + Math.max(sh.h, 0, sh.kind === 'text' ? (sh.size ?? 1) : 0) + 0.3) } if (place.name && !hide.has('name')) right = Math.max(right, place.name.x + (def.name.length * NAME_CHAR) / 2 + 0.3) } for (const it of shown) { const k = it.scale ?? 1 const turned = it.rotate === 90 || it.rotate === 270 const iw = (turned ? it.h : it.w) * k const ih = (turned ? it.w : it.h) * k const cx = it.x + (it.w * k) / 2 const cy = it.y + (it.h * k) / 2 right = Math.max(right, cx + iw / 2 + 0.3) floor = Math.max(floor, cy + ih / 2 + 0.3) } const bw = Math.ceil(right * 2) / 2 const onEdge = (p: PinInfo) => ({ ...p, dx: p.dx > 0 ? bw : 0, dy: rows.get(p.key)! }) return { ...auto, inputs: auto.inputs.map(onEdge), outputs: auto.outputs.map(onEdge), body: { x: 0, y: top, w: bw, h: Math.ceil((floor - top) * 2) / 2 }, face: shown, nameAt: hide.has('name') ? null : place.name ? { x: place.name.x, y: top + place.name.y } : undefined, drawing: (d.shapes ?? []).map(sh => ({ ...sh, y: top + sh.y })), } } /** * The first spot for a thing of size `s`, going along rows from the top * left, that keeps clear of everything taken; below them all when none is. */ function freeSpot(taken: { x: number; y: number; w: number; h: number }[], s: { w: number; h: number }, area: { x0: number; x1: number; y0: number }): { x: number; y: number } { const gap = 0.3 const clear = (x: number, y: number) => taken.every(t => x + s.w + gap <= t.x || x >= t.x + t.w + gap || y + s.h + gap <= t.y || y >= t.y + t.h + gap) const lowest = taken.reduce((m, t) => Math.max(m, t.y + t.h), area.y0) for (let y = area.y0; y <= lowest; y += 0.25) { for (let x = area.x0; x + s.w <= area.x1 + 1e-9; x += 0.25) if (clear(x, y)) return { x, y } } return { x: area.x0, y: lowest + gap } } /** A pin on one edge of a component's box, and whether a signal goes in or comes out there. */ interface EdgePin { pin: Omit dir: 'in' | 'out' } function boxShape(name: string, plain: ChipPins, face: ReturnType, get?: DefLookup, node?: CircuitNode): Shape { // Ports sit at the very top of their side, as one cable pin each. A port // split on this box has a pin per line right below it, facing out of its side. const lines = node ? splitLines(node, plain, get) : [] const edge = (side: 'in' | 'out'): EdgePin[] => { const out: EdgePin[] = [] for (const p of plain.ports ?? []) { if (p.side !== side) continue out.push({ dir: side, pin: { key: p.key, label: portName(p, get), bus: true, conn: p.conn } }) for (const l of lines) { if (l.port === p.key) out.push({ dir: l.enters ? 'in' : 'out', pin: { key: l.key, label: l.name, face: side === 'in' ? -1 : 1, port: p.key } }) } } for (const p of side === 'in' ? plain.inputs : plain.outputs) out.push({ dir: side, pin: p }) return out } const left = edge('in') const right = edge('out') const n = Math.max(left.length, right.length, 1) const longest = (ps: EdgePin[]) => ps.reduce((m, p) => Math.max(m, p.pin.label.length), 0) const w = Math.max( 3, Math.ceil(longest(left) * LABEL_CHAR + longest(right) * LABEL_CHAR + name.length * NAME_CHAR + 1.5), Math.ceil(face.w + 1.2), ) // An edge with ports starts at the top; one of single pins only is centred, // on the box as it is without split lines, so splitting a port never moves it. const unsplit = Math.max(...[left, right].map(ps => ps.filter(p => !p.pin.port).length), 1) const place = (ps: EdgePin[], dx: number) => { const off = ps.some(p => p.pin.bus) ? 0 : Math.floor((unsplit - ps.length) / 2) return ps.map((p, i) => ({ dir: p.dir, pin: { ...p.pin, dx, dy: off + i } })) } // Each edge's own pins first: code that takes the first free input or output finds one on its usual edge. const onLeft = place(left, 0) const onRight = place(right, w) const top = n === 1 ? -1 : -0.5 const pinBottom = n === 1 ? 1 : n - 0.5 const faceTop = pinBottom + 0.2 const faceLeft = (w - face.w) / 2 return { body: { x: 0, y: top, w, h: pinBottom - top + (face.items.length ? face.h + 0.6 : 0) }, inputs: [...onLeft, ...onRight].filter(p => p.dir === 'in').map(p => p.pin), outputs: [...onRight, ...onLeft].filter(p => p.dir === 'out').map(p => p.pin), nameY: (top + pinBottom) / 2, face: face.items.map(it => ({ ...it, x: it.x + faceLeft, y: it.y + faceTop })), } } const NAND_SHAPE = gateShape('nand', [{ key: 'a', label: 'A' }, { key: 'b', label: 'B' }], { key: 'q', label: 'Q' }) const SOURCE_SHAPE: Shape = { body: { x: 0, y: -0.75, w: 2, h: 1.5 }, inputs: [], outputs: [{ key: 'q', label: '', dx: 2, dy: 0 }], } // Output pins and lamps pass their signal on: the pin on the right carries the same value. const SINK_SHAPE: Shape = { body: { x: 0, y: -0.75, w: 2, h: 1.5 }, inputs: [{ key: 'a', label: '', dx: 0, dy: 0 }], outputs: [{ key: 'q', label: '', dx: 2, dy: 0 }], } /** Width of a signal tag's flag, from its name. */ function tagWidth(node: CircuitNode): number { return Math.max(2.5, Math.ceil((signalName(node) || '?').length * 0.45 + 1.4)) } /** The name a signal tag sends, or a reference uses. */ export const signalName = (node: CircuitNode) => node.label?.trim() ?? '' /** Output panel: a lamp per row with its name, the wire in on the left and on again on the right. */ function outPanelShape(node: CircuitNode): Shape { const rows = node.rows ?? [] const dys = panelOffsets(rows) const labels = rows.map(rowLabel) const w = Math.max(3, Math.ceil(labels.reduce((m, l) => Math.max(m, l.length), 0) * LABEL_CHAR + 2.4)) const last = dys.length ? dys[dys.length - 1]! : 0 return { body: { x: 0, y: -0.5, w, h: last + 1 }, inputs: rows.map((r, i) => ({ key: r.id, label: labels[i]!, dx: 0, dy: dys[i]! })), outputs: rows.map((r, i) => ({ key: r.id, label: labels[i]!, dx: w, dy: dys[i]! })), } } /** Send: the wire comes in on the left into a flag carrying the name. */ function tagShape(node: CircuitNode): Shape { const w = tagWidth(node) return { body: { x: 0.5, y: -0.6, w, h: 1.2 }, inputs: [{ key: 'a', label: '', dx: 0, dy: 0 }], outputs: [] } } /** Use: a flag with the name, the signal leaves on the right. */ function refShape(node: CircuitNode): Shape { const w = tagWidth(node) return { body: { x: 0, y: -0.6, w, h: 1.2 }, inputs: [], outputs: [{ key: 'q', label: '', dx: w + 0.5, dy: 0 }] } } // A hex display passes its four bits on, so it can sit in the middle of a bus. const HEX_SHAPE: Shape = { body: { x: 0, y: -0.5, w: 3, h: 4 }, inputs: ['1', '2', '4', '8'].map((label, i) => ({ key: `b${i}`, label, dx: 0, dy: i })), outputs: ['1', '2', '4', '8'].map((label, i) => ({ key: `q${i}`, label, dx: 3, dy: i })), } const CLOCK_SHAPE: Shape = { body: { x: 0, y: -0.75, w: 3, h: 1.5 }, inputs: [], outputs: [{ key: 'q', label: '', dx: 3, dy: 0 }], } const MISSING_SHAPE: Shape = { body: { x: 0, y: -1, w: 4, h: 2 }, inputs: [], outputs: [] } export const MAX_BITS = 32 /** Wires in a cable, within range. */ export function cableBits(node: CircuitNode): number { const n = node.bits ?? 4 return Math.min(MAX_BITS, Math.max(2, Math.round(n))) } /** Row of each wire of a cable end below the first: evenly `pitch` apart, or as plugged. */ export function cableOffsets(node: CircuitNode): number[] { const n = cableBits(node) const o = node.offsets if (o?.length === n && o[0] === 0 && o.every((v, i) => i === 0 || v > o[i - 1]!)) return o const pitch = Math.max(1, Math.min(8, Math.round(node.pitch ?? 1))) return Array.from({ length: n }, (_, i) => i * pitch) } /** Bundle: one input per wire on the left, the cable leaves on the right. Split: the mirror image. */ function cableShape(node: CircuitNode): Shape { const dys = cableOffsets(node) const wires = dys.map((dy, i) => ({ key: `b${i}`, label: node.names?.[i] || String(i), dy })) const last = dys[dys.length - 1]! const mid = Math.floor(last / 2) const body = { x: 0, y: -0.5, w: 1, h: last + 1 } if (node.kind === 'bundle') { return { body, inputs: wires.map(p => ({ ...p, dx: 0 })), outputs: [{ key: 'q', label: '', dx: 1, dy: mid, bus: true }] } } return { body, inputs: [{ key: 'a', label: '', dx: 0, dy: mid, bus: true }], outputs: wires.map(p => ({ ...p, dx: 1 })) } } const PIXEL_SHAPE: Shape = { body: { x: 0, y: -0.5, w: 1, h: 1 }, inputs: [{ key: 'a', label: '', dx: 0, dy: 0 }], outputs: [], } const PIXEL_RGB_SHAPE: Shape = { body: { x: 0, y: -0.5, w: 1, h: 3 }, inputs: [ { key: 'r', label: '', dx: 0, dy: 0 }, { key: 'g', label: '', dx: 0, dy: 1 }, { key: 'b', label: '', dx: 0, dy: 2 }, ], outputs: [], } const TERMINAL_SHAPE: Shape = { body: { x: 0, y: -0.5, w: 15, h: 10 }, inputs: [...DATA_KEYS, 'wr', 'clr'].map((key, i) => ({ key, label: DEVICE_PIN_NAMES[key]!, dx: 0, dy: i })), outputs: [], } function benchShape(node: CircuitNode): Shape { const l = benchLayout(node) return { body: { x: 0, y: -0.5, w: l.w, h: l.h }, inputs: l.left.map((p, i) => ({ key: p.key, label: p.label, dx: 0, dy: i })), outputs: l.right.map((p, i) => ({ key: p.key, label: p.label, dx: l.w, dy: i })), } } const KEYBOARD_SHAPE: Shape = { body: { x: 0, y: -0.5, w: 7, h: 9 }, inputs: [{ key: 'next', label: 'NEXT', dx: 0, dy: 8 }], outputs: [...DATA_KEYS, 'rdy'].map((key, i) => ({ key, label: DEVICE_PIN_NAMES[key]!, dx: 7, dy: i })), } /** Grid offset of every panel row below the first one. */ export function panelOffsets(rows: PanelRow[]): number[] { const out: number[] = [] for (const r of rows) { const prev = out.length ? out[out.length - 1]! : -1 out.push(r.dy !== undefined && r.dy > prev ? r.dy : prev + 1) } return out } /** Name shown next to a panel row: the user's, the driven pin's, or its number. */ export function rowLabel(row: PanelRow, i: number): string { return row.label?.trim() || row.name?.trim() || String(i + 1) } /** Width of the control drawn in each panel row, in grid units. */ export const PANEL_CONTROL_W = 2.2 function panelShape(node: CircuitNode): Shape { const rows = node.rows ?? [] const dys = panelOffsets(rows) const labels = rows.map(rowLabel) const keys = rows.some(r => r.key) ? 0.7 : 0 const w = Math.max(4, Math.ceil(labels.reduce((m, l) => Math.max(m, l.length), 0) * LABEL_CHAR + PANEL_CONTROL_W + 1.1 + keys)) const last = dys.length ? dys[dys.length - 1]! : 0 return { body: { x: 0, y: -0.5, w, h: last + 1 }, inputs: [], outputs: rows.map((r, i) => ({ key: r.id, label: labels[i]!, dx: w, dy: dys[i]! })), } } export function noteLines(node: CircuitNode): string[] { return (node.label || 'Note').split('\n') } export function noteScale(node: CircuitNode): number { return node.size === 'sm' ? 0.8 : node.size === 'lg' ? 1.5 : 1 } /** * The lines of a port, each with whether its signal comes into the circuit * through this port (and so is an output pin of the port part) or leaves it * (an input pin). An in port brings the forward lines in and sends the back * lines out; an out port the other way round. */ export function portLines(node: CircuitNode, get: DefLookup): { name: string; enters: boolean; key: string }[] { const type = node.conn ? get.conn?.(node.conn) : undefined return (type?.lines ?? []).map((l, i) => ({ name: l.name, enters: (node.kind === 'portin') !== !!l.back, key: `l${i}` })) } /** * A port inside a component: on its inner side, a pin per line (outputs for * lines coming in, inputs for lines going out) and, at the top, a cable pin * that passes the whole cable on to a part inside with the same port. An in * port sits on the left of a circuit and faces right; an out port the reverse. */ function portShape(node: CircuitNode, get: DefLookup): Shape { const lines = portLines(node, get) // Wide enough for the longest line name, and for the title " in · " (9px letters, about a third of a square each). const title = `${(node.conn && get.conn?.(node.conn)?.name) || 'Port'} out${node.label?.trim() ? ` · ${node.label.trim()}` : ''}` const w = Math.max(4, Math.ceil(lines.reduce((m, l) => Math.max(m, l.name.length), 0) * LABEL_CHAR + 2.6), Math.ceil(title.length * 0.34 + 0.8)) const inner = node.kind === 'portin' ? w : 0 const face: 1 | -1 = node.kind === 'portin' ? 1 : -1 const bus: PinInfo = { key: 'bus', label: '', dx: inner, dy: 0, bus: true, conn: node.conn } const pins = lines.map((l, i) => ({ key: l.key, label: l.name, dx: inner, dy: i + 1, face })) return { body: { x: 0, y: -0.75, w, h: lines.length + 1.5 }, inputs: node.kind === 'portin' ? pins.filter((_, i) => !lines[i]!.enters) : [bus, ...pins.filter((_, i) => !lines[i]!.enters)], outputs: node.kind === 'portin' ? [bus, ...pins.filter((_, i) => lines[i]!.enters)] : pins.filter((_, i) => lines[i]!.enters), } } export function shapeOf(node: CircuitNode, getDef: DefLookup): Shape { switch (node.kind) { case 'nand': return NAND_SHAPE case 'input': case 'high': case 'low': case 'button': return SOURCE_SHAPE case 'clock': return CLOCK_SHAPE case 'output': case 'lamp': return SINK_SHAPE case 'hex': return HEX_SHAPE case 'panel': return panelShape(node) case 'bundle': case 'split': return cableShape(node) case 'pixel': return node.rgb ? PIXEL_RGB_SHAPE : PIXEL_SHAPE case 'terminal': return TERMINAL_SHAPE case 'bench': return benchShape(node) case 'keyboard': return KEYBOARD_SHAPE case 'outpanel': return outPanelShape(node) case 'tag': return tagShape(node) case 'ref': return refShape(node) case 'note': { const lines = noteLines(node) const k = noteScale(node) const w = Math.max(2, Math.ceil(Math.max(...lines.map(l => l.length)) * NAME_CHAR * k + 1)) return { body: { x: 0, y: -0.75 * k, w, h: (lines.length + 0.5) * k }, inputs: [], outputs: [] } } case 'chip': { const def = node.chip ? getDef(node.chip) : undefined if (!def) return MISSING_SHAPE const pins = chipPins(def) const face = faceLayout(def) if (def.design) return designedShape(def, pins, face, getDef, node) if (def.symbol !== 'box' && !face.items.length && !pins.ports && pins.outputs.length === 1 && pins.inputs.length >= 1 && pins.inputs.length <= 16) { return gateShape(def.symbol, pins.inputs, pins.outputs[0]!) } return boxShape(def.name, pins, face, getDef, node) } case 'portin': case 'portout': return portShape(node, getDef) } } export function pinPos(node: CircuitNode, shape: Shape, key: string, dir: 'in' | 'out') { const pin = (dir === 'in' ? shape.inputs : shape.outputs).find(p => p.key === key) return pin ? { x: node.x + pin.dx, y: node.y + pin.dy, face: pin.face ?? (dir === 'in' ? -1 : 1) } : undefined } export type Pt = [number, number] /** Drop repeated points and points in the middle of a straight run (or a spike that doubles back). */ export function simplify(pts: Pt[]): Pt[] { const out: Pt[] = [] for (const p of pts) { out.push(p) for (;;) { const n = out.length const [a, b, c] = [out[n - 3], out[n - 2], out[n - 1]!] if (b && b[0] === c[0] && b[1] === c[1]) out.splice(n - 2, 1) else if (a && b && ((a[0] === b[0] && b[0] === c[0]) || (a[1] === b[1] && b[1] === c[1]))) out.splice(n - 2, 1) else break } } return out } /** * Orthogonal route from an output pin to an input pin, as a list of points. * With corner points set, the route runs through them. Otherwise forward * wires get one vertical segment halfway; backward wires (feedback loops) go * out to the right, around, and back in from the left. */ export function routeWire(a: Pt, b: Pt, corners?: Pt[], aFace: 1 | -1 = 1, bFace: 1 | -1 = -1): Pt[] { const [x1, y1] = a const [x2, y2] = b if (corners?.length) { const out: Pt[] = [a] let prev = a for (const p of corners) { if (p[0] !== prev[0] && p[1] !== prev[1]) out.push([p[0], prev[1]]) out.push(p) prev = p } if (b[0] !== prev[0] && b[1] !== prev[1]) out.push([prev[0], b[1]]) out.push(b) return simplify(out) } // Pins that face the other way (the inner pins of ports): out the side the // source faces, in from the side the target faces. if (aFace === -1 && bFace === 1) return routeWire([-x1, y1], [-x2, y2]).map(([x, y]) => [-x, y] as Pt) if (aFace === bFace) { const x = aFace === 1 ? Math.max(x1, x2) + 1 : Math.min(x1, x2) - 1 return simplify([a, [x, y1], [x, y2], b]) } if (y1 === y2 && x2 > x1) return [a, b] if (x2 >= x1 + 1) { const m = Math.round((x1 + x2) / 2) return [a, [m, y1], [m, y2], b] } const ym = Math.abs(y2 - y1) >= 3 ? Math.round((y1 + y2) / 2) : Math.max(y1, y2) + 2 return [a, [x1 + 1, y1], [x1 + 1, ym], [x2 - 1, ym], [x2 - 1, y2], b] }