logigate/app/lib/logic/bulk.ts

201 lines
8.2 KiB
TypeScript
Raw Normal View History

// Working on many parts at once: grouping a selection, numbered names,
// the list of a circuit's inputs and outputs, where its transistors are,
// and lining parts up.
import { TRANSISTORS_PER_NAND } from './analyze'
import { invertedPins } from './compile'
import { chipPins, isPinRow, rowPin } from './geometry'
import type { DefLookup } from './geometry'
import { pinKeys, SINK_KINDS, SOURCE_KINDS } from './ops'
import type { CircuitNode, ComponentDef, PanelRow } from './types'
/** Top to bottom, then left to right: the order pins and names follow. */
export const byPosition = (a: CircuitNode, b: CircuitNode) => a.y - b.y || a.x - b.x
/**
* Names for `count` parts from a pattern. Each run of # becomes a number
* counting up from `start`, padded to the run's length (D# → D0, D1;
* Q## → Q00, Q01). Without #, several parts get the number appended.
*/
export function numberedNames(pattern: string, count: number, start = 0): string[] {
const p = pattern.trim()
return Array.from({ length: count }, (_, i) => {
const n = start + i
if (p.includes('#')) return p.replace(/#+/g, run => String(n).padStart(run.length, '0'))
return count === 1 ? p : `${p}${n}`
})
}
/** What sort of part a node is: its kind, or the component it places. */
export const typeKey = (n: CircuitNode) => (n.kind === 'chip' ? `chip:${n.chip}` : n.kind)
export type Family = 'logic' | 'source' | 'sink'
/** The swap family all nodes share (they can all become the same part), or null. */
export function sharedFamily(nodes: CircuitNode[]): Family | null {
const fam = (n: CircuitNode): Family | null =>
n.kind === 'nand' || n.kind === 'chip' ? 'logic' : SOURCE_KINDS.includes(n.kind) ? 'source' : SINK_KINDS.includes(n.kind) ? 'sink' : null
const first = nodes[0] && fam(nodes[0])
return first && nodes.every(n => fam(n) === first) ? first : null
}
export interface IoEntry {
node: CircuitNode
/** For a panel: the row this entry stands for. */
row?: PanelRow
/** Pins are what the circuit shows when used as a component; the rest stays inside. */
pin: boolean
}
/**
* A circuit's inputs and outputs, for renaming them in one place. Pins come
* first, in pin order (top to bottom), then switches, buttons, clocks and
* panel rows that stay inside, then lamps and displays.
*/
export function ioList(def: ComponentDef): { inputs: IoEntry[]; outputs: IoEntry[] } {
const of = (kinds: string[]) => def.nodes.filter(n => kinds.includes(n.kind)).sort(byPosition)
// Pins in pin order: input switches and panel rows by where they sit.
const at = new Map<string, IoEntry>()
for (const node of of(['input'])) at.set(node.id, { node, pin: true })
const inside: IoEntry[] = []
for (const node of of(['panel'])) {
for (const row of node.rows ?? []) {
if (isPinRow(node, row)) at.set(rowPin(node.id, row.id), { node, row, pin: true })
else inside.push({ node, row, pin: false })
}
}
const inputs: IoEntry[] = [
...chipPins(def).inputs.map(p => at.get(p.key)!).filter(Boolean),
...of(['button', 'clock']).map(node => ({ node, pin: false })),
...inside,
]
const outputs: IoEntry[] = [...of(['output']).map(node => ({ node, pin: true })), ...of(['lamp', 'hex']).map(node => ({ node, pin: false }))]
return { inputs, outputs }
}
export const entryLabel = (e: IoEntry) => (e.row ? (e.row.label ?? '') : (e.node.label ?? '')).trim()
/** Names that more than one entry uses (pins must be told apart, e.g. for challenges and truth tables). */
export function duplicateNames(entries: IoEntry[]): Set<string> {
const seen = new Set<string>()
const dup = new Set<string>()
for (const e of entries) {
const l = entryLabel(e).toLowerCase()
if (!l) continue
if (seen.has(l)) dup.add(l)
seen.add(l)
}
return dup
}
export interface CostLine {
key: string
name: string
count: number
/** Transistors in one of them. */
each: number
total: number
ids: string[]
}
/**
* Where a circuit's transistors are: its own parts grouped by type, most
* transistors first. Parts without gates (switches, lamps, cables) are left out.
*/
export function transistorBreakdown(def: ComponentDef, nandsPerDef: Map<string, number>, get: DefLookup): CostLine[] {
const lines = new Map<string, CostLine>()
const bubbles: CostLine = { key: 'invert', name: 'Inverted inputs', count: 0, each: TRANSISTORS_PER_NAND, total: 0, ids: [] }
for (const n of def.nodes) {
const child = n.kind === 'chip' && n.chip ? get(n.chip) : undefined
const inv = invertedPins(n, child ? chipPins(child) : undefined).length
if (inv) {
bubbles.count += inv
bubbles.total += inv * TRANSISTORS_PER_NAND
bubbles.ids.push(n.id)
}
let each = 0
let name = ''
if (n.kind === 'nand') {
each = TRANSISTORS_PER_NAND
name = 'NAND'
} else if (n.kind === 'chip' && n.chip) {
each = (nandsPerDef.get(n.chip) ?? 0) * TRANSISTORS_PER_NAND
name = get(n.chip)?.name ?? 'Missing component'
}
if (!each) continue
const key = typeKey(n)
const line = lines.get(key) ?? { key, name, count: 0, each, total: 0, ids: [] }
line.count++
line.total += each
line.ids.push(n.id)
lines.set(key, line)
}
if (bubbles.count) lines.set('invert', bubbles)
return [...lines.values()].sort((a, b) => b.total - a.total || a.name.localeCompare(b.name))
}
export type Arrange = 'left' | 'right' | 'top' | 'bottom' | 'spread-x' | 'spread-y'
/** Lines parts up on their left/right/top/bottom position, or spreads them evenly between the outermost two. */
export function arrangeNodes(nodes: CircuitNode[], how: Arrange): void {
if (nodes.length < 2) return
const xs = nodes.map(n => n.x)
const ys = nodes.map(n => n.y)
if (how === 'left') for (const n of nodes) n.x = Math.min(...xs)
else if (how === 'right') for (const n of nodes) n.x = Math.max(...xs)
else if (how === 'top') for (const n of nodes) n.y = Math.min(...ys)
else if (how === 'bottom') for (const n of nodes) n.y = Math.max(...ys)
else {
const axis = how === 'spread-x' ? 'x' : 'y'
const sorted = [...nodes].sort((a, b) => a[axis] - b[axis])
const lo = sorted[0]![axis]
const step = (sorted[sorted.length - 1]![axis] - lo) / (sorted.length - 1)
sorted.forEach((n, i) => (n[axis] = Math.round(lo + i * step)))
}
}
export interface Link {
from: { node: string; pin: string }
to: { node: string; pin: string }
}
/**
* Wiring several parts to one other part in one go. One wire was dragged
* from pin `from` of a selected part to pin `to` of `target`; the other
* selected parts follow in position order, each from its pin in the same
* place, to the target's next pins. Parts beyond the target's last pin are
* left out. Returns every link to make, the dragged one included.
*/
export function seriesLinks(
def: ComponentDef,
get: DefLookup,
selected: string[],
from: { node: string; pin: string; dir: 'in' | 'out' },
to: { node: string; pin: string },
): Link[] {
const side = (n: CircuitNode, dir: 'in' | 'out') => (dir === 'out' ? pinKeys(n, get).outs : pinKeys(n, get).ins)
const single = from.dir === 'out' ? [{ from: { node: from.node, pin: from.pin }, to }] : [{ from: to, to: { node: from.node, pin: from.pin } }]
const source = def.nodes.find(n => n.id === from.node)
const target = def.nodes.find(n => n.id === to.node)
if (!source || !target || !selected.includes(from.node)) return single
const k = side(source, from.dir).indexOf(from.pin)
// Only parts with a pin in the same place take part (a note or a lamp among outputs is skipped).
const ids = new Set(selected)
ids.delete(to.node)
const nodes = def.nodes.filter(n => ids.has(n.id) && side(n, from.dir)[k] !== undefined).sort(byPosition)
const dragged = nodes.findIndex(n => n.id === from.node)
const targetPins = side(target, from.dir === 'out' ? 'in' : 'out')
const t = targetPins.indexOf(to.pin)
if (k < 0 || t < 0) return single
const links: Link[] = []
nodes.forEach((n, i) => {
const mine = side(n, from.dir)[k]
const theirs = targetPins[t + i - dragged]
if (!mine || !theirs) return
const a = { node: n.id, pin: mine }
const b = { node: target.id, pin: theirs }
links.push(from.dir === 'out' ? { from: a, to: b } : { from: b, to: a })
})
return links
}