logigate/app/lib/logic/ops.ts

558 lines
23 KiB
TypeScript
Raw Normal View History

// Project operations that don't depend on the UI: creating, packaging,
// copying and cleaning up components. They mutate the project in place.
import type { Challenge } from './challenges'
import { inputKeys, outputKeys } from './compile'
import { exampleLibrary, starterCircuit } from './examples'
import { chipPins, shapeOf, splitLines, type DefLookup } from './geometry'
import type { CircuitNode, ComponentDef, NodeKind, Project, PuzzleSpec, Wire } from './types'
export function uid(prefix = ''): string {
return prefix + Math.random().toString(36).slice(2, 10)
}
/** Deep copy that also works on Vue reactive proxies (structuredClone does not). */
function clone<T>(value: T): T {
return JSON.parse(JSON.stringify(value)) as T
}
export function lookup(project: Project): DefLookup {
const map = new Map(project.components.map(d => [d.id, d]))
const conns = new Map((project.connectors ?? []).map(c => [c.id, c]))
const get: DefLookup = id => map.get(id)
get.conn = id => conns.get(id)
return get
}
export function createProject(opts: { examples: boolean; name?: string; campaign?: boolean }): Project {
const campaign = !!opts.campaign
return {
version: 1,
name: opts.name ?? (campaign ? 'Campaign' : opts.examples ? 'NAND to computer' : 'New project'),
components: [starterCircuit(), ...(opts.examples && !campaign ? exampleLibrary() : [])],
openId: 'main',
settings: { symbols: 'iec', flow: true },
solved: [],
...(campaign ? { mode: 'campaign' as const } : {}),
}
}
/** Starts a puzzle: a component with its pins, set up like a challenge. */
export function startPuzzle(project: Project, spec: PuzzleSpec): ComponentDef {
const existing = project.components.find(d => d.challenge === spec.id)
if (existing) return existing
if (!project.puzzles?.some(p => p.id === spec.id)) project.puzzles = [...(project.puzzles ?? []), spec]
const def: ComponentDef = {
id: uid('c'),
name: uniqueName(project, spec.name),
symbol: 'box',
description: spec.goal,
challenge: spec.id,
group: 'Puzzles',
nodes: [
...spec.inputs.map((label, i) => ({ id: uid('n'), kind: 'input' as const, x: 0, y: i * 3, label })),
...spec.outputs.map((label, i) => ({ id: uid('n'), kind: 'output' as const, x: 24, y: i * 3, label })),
],
wires: [],
}
project.components.push(def)
return def
}
/** Adds the example parts that are missing. Returns how many were added. */
export function addExamples(project: Project): number {
const have = new Set(project.components.map(d => d.id))
const missing = exampleLibrary().filter(d => !have.has(d.id))
project.components.push(...missing)
return missing.length
}
/**
* Adds components from another project. Identical ones are skipped; a
* different component with a clashing id gets a new id (and references to it
* inside the imported set follow). Returns how many were added.
*/
export function mergeComponents(project: Project, incoming: ComponentDef[]): number {
const existing = new Map(project.components.map(d => [d.id, d]))
const remap = new Map<string, string>()
const added: ComponentDef[] = []
for (const d of incoming) {
const have = existing.get(d.id)
if (have && JSON.stringify(have) === JSON.stringify(d)) continue
const copy = clone(d)
if (have) {
copy.id = uid('c')
remap.set(d.id, copy.id)
copy.name = uniqueName({ ...project, components: [...project.components, ...added] }, copy.name)
}
added.push(copy)
}
for (const d of added) {
for (const n of d.nodes) if (n.kind === 'chip' && n.chip && remap.has(n.chip)) n.chip = remap.get(n.chip)
}
project.components.push(...added)
return added.length
}
/** True when `defId` is `targetId` or has it somewhere inside. */
export function containsDef(project: Project, defId: string, targetId: string): boolean {
const get = lookup(project)
const seen = new Set<string>()
const walk = (id: string): boolean => {
if (id === targetId) return true
if (seen.has(id)) return false
seen.add(id)
const def = get(id)
return !!def && def.nodes.some(n => n.kind === 'chip' && !!n.chip && walk(n.chip))
}
return walk(defId)
}
/** Components that can go into `openId` without making it contain itself. */
export function placeable(project: Project, openId: string): ComponentDef[] {
return project.components.filter(d => !containsDef(project, d.id, openId))
}
export function usages(project: Project, defId: string): ComponentDef[] {
return project.components.filter(d => d.id !== defId && d.nodes.some(n => n.kind === 'chip' && n.chip === defId))
}
export function uniqueName(project: Project, base: string): string {
const names = new Set(project.components.map(d => d.name.toLowerCase()))
if (!names.has(base.toLowerCase())) return base
for (let i = 2; ; i++) if (!names.has(`${base} ${i}`.toLowerCase())) return `${base} ${i}`
}
export function newComponent(project: Project, name: string): ComponentDef {
const def: ComponentDef = {
id: uid('c'),
name: uniqueName(project, name),
symbol: 'box',
nodes: [
{ id: uid('n'), kind: 'input', x: 0, y: 0, label: 'A' },
{ id: uid('n'), kind: 'output', x: 16, y: 0, label: 'Q' },
],
wires: [],
}
project.components.push(def)
return def
}
export function startChallenge(project: Project, c: Challenge): ComponentDef {
const def: ComponentDef = {
id: uid('c'),
name: uniqueName(project, project.components.some(d => d.name.toLowerCase() === c.name.toLowerCase()) ? `My ${c.name}` : c.name),
symbol: c.symbol ?? 'box',
description: c.goal,
challenge: c.id,
nodes: [
...c.inputs.map((label, i) => ({ id: uid('n'), kind: 'input' as const, x: 0, y: i * 3, label })),
...c.outputs.map((label, i) => ({ id: uid('n'), kind: 'output' as const, x: 24, y: i * 3, label })),
],
wires: [],
}
project.components.push(def)
return def
}
export function duplicateComponent(project: Project, id: string): ComponentDef | undefined {
const src = project.components.find(d => d.id === id)
if (!src) return undefined
const copy: ComponentDef = { ...clone(src), id: uid('c'), name: uniqueName(project, `${src.name} copy`) }
delete copy.challenge
project.components.push(copy)
return copy
}
/** Deletes a component. Refuses when other components still use it. */
export function deleteComponent(project: Project, id: string): string | null {
const users = usages(project, id)
if (users.length) return `Still used in ${users.map(u => u.name).join(', ')}`
if (project.components.length <= 1) return 'The last circuit cannot be deleted'
project.components = project.components.filter(d => d.id !== id)
if (project.openId === id) project.openId = project.components[0]!.id
return null
}
/**
* Removes wires whose pins no longer exist (a component lost a pin) and
* keeps one wire per input pin. Returns true if anything changed.
*/
export function pruneWires(project: Project): boolean {
const get = lookup(project)
let changed = false
for (const def of project.components) {
const ins = new Set<string>()
const outs = new Set<string>()
// What each cable pin takes: a cable end, or a port of one connector type. Ends must match.
const kinds = new Map<string, string>()
for (const n of def.nodes) {
const pins = n.kind === 'chip' && n.chip && get(n.chip) ? chipPins(get(n.chip)!) : undefined
for (const k of inputKeys(n, pins, get)) ins.add(`${n.id}:${k}`)
for (const k of outputKeys(n, pins, get)) outs.add(`${n.id}:${k}`)
for (const p of pins?.ports ?? []) kinds.set(`${n.id}:${p.key}`, `c:${p.conn}`)
if ((n.kind === 'portin' || n.kind === 'portout') && n.conn) kinds.set(`${n.id}:bus`, `c:${n.conn}`)
if (n.kind === 'bundle') kinds.set(`${n.id}:q`, 'bus')
if (n.kind === 'split') kinds.set(`${n.id}:a`, 'bus')
}
const taken = new Set<string>()
const kept: Wire[] = []
for (let i = def.wires.length - 1; i >= 0; i--) {
const w = def.wires[i]!
const to = `${w.to.node}:${w.to.pin}`
if (!ins.has(to) || !outs.has(`${w.from.node}:${w.from.pin}`) || taken.has(to)) continue
// A port only joins a port of the same connector type.
const ka = kinds.get(`${w.from.node}:${w.from.pin}`) ?? ''
const kb = kinds.get(to) ?? ''
if ((ka.startsWith('c:') || kb.startsWith('c:')) && ka !== kb) continue
taken.add(to)
kept.push(w)
}
if (kept.length !== def.wires.length) {
def.wires = kept.reverse()
changed = true
}
}
return changed
}
export interface Clip {
nodes: CircuitNode[]
wires: Wire[]
}
export function copySelection(def: ComponentDef, ids: Set<string>): Clip {
return clone({
nodes: def.nodes.filter(n => ids.has(n.id)),
wires: def.wires.filter(w => ids.has(w.from.node) && ids.has(w.to.node)),
})
}
/** Pastes a clip shifted by (dx, dy). Returns the new node ids. */
export function pasteClip(def: ComponentDef, clip: Clip, dx: number, dy: number): string[] {
const ids = new Map<string, string>()
for (const n of clip.nodes) {
const id = uid('n')
ids.set(n.id, id)
def.nodes.push({ ...clone(n), id, x: n.x + dx, y: n.y + dy })
}
const fresh = new Set(ids.values())
redock(def.nodes.filter(n => fresh.has(n.id)), ids)
for (const w of clip.wires) {
const from = ids.get(w.from.node)
const to = ids.get(w.to.node)
if (!from || !to) continue
const wire: Wire = { id: uid('w'), from: { node: from, pin: w.from.pin }, to: { node: to, pin: w.to.pin } }
if (w.pts) wire.pts = w.pts.map(([x, y]) => [x + dx, y + dy])
def.wires.push(wire)
}
return [...ids.values()]
}
/**
* Copied panels dock to the copy of their component, copied cable ends plug
* into the copy of their part and copied latched parts latch onto the copy of
* theirs, or to nothing when it was not copied along.
*/
function redock(nodes: CircuitNode[], ids: Map<string, string>) {
for (const n of nodes) {
for (const k of ['plug', 'latch'] as const) {
const was = n[k]
if (!was) continue
const to = ids.get(was)
if (to) n[k] = to
else delete n[k]
}
if (!n.attach) continue
const to = ids.get(n.attach)
if (to) n.attach = to
else {
delete n.attach
delete n.skip
}
}
}
/**
* Turns the selected parts into a new component and puts one instance of it
* in their place. Wires that crossed the selection border become pins.
*/
export function packageSelection(
project: Project,
defId: string,
ids: Set<string>,
name: string,
): { ok: true; def: ComponentDef; chipNode: string } | { ok: false; error: string } {
const get = lookup(project)
const def = get(defId)
if (!def) return { ok: false, error: 'Circuit not found' }
const sel = def.nodes.filter(n => ids.has(n.id))
if (sel.some(n => n.kind === 'input' || n.kind === 'output')) {
return { ok: false, error: 'Leave the circuit’s own input/output pins out of the selection' }
}
if (!sel.some(n => n.kind !== 'note')) return { ok: false, error: 'Select some parts first' }
const inside = (id: string) => ids.has(id)
const incoming = def.wires.filter(w => !inside(w.from.node) && inside(w.to.node))
const outgoing = def.wires.filter(w => inside(w.from.node) && !inside(w.to.node))
const internal = def.wires.filter(w => inside(w.from.node) && inside(w.to.node))
const minX = Math.min(...sel.map(n => n.x))
const minY = Math.min(...sel.map(n => n.y))
const maxX = Math.max(...sel.map(n => n.x + shapeOf(n, get).body.w))
const ox = 6 - minX
const oy = -minY
const nodeById = new Map(def.nodes.map(n => [n.id, n]))
const pinY = (ref: { node: string; pin: string }, dir: 'in' | 'out') => {
const n = nodeById.get(ref.node)!
const s = shapeOf(n, get)
const p = (dir === 'in' ? s.inputs : s.outputs).find(p => p.key === ref.pin)
return n.y + (p?.dy ?? 0)
}
const labelOf = (nodeId: string) => {
const n = nodeById.get(nodeId)
return n && ['input', 'output', 'lamp', 'button', 'clock'].includes(n.kind) ? n.label?.trim() : undefined
}
// One input pin per distinct outside source, one output pin per distinct inside source.
const group = (wires: Wire[], dir: 'in' | 'out') => {
const map = new Map<string, { src: Wire['from']; wires: Wire[]; y: number }>()
for (const w of wires) {
const key = `${w.from.node}:${w.from.pin}`
const y = dir === 'in' ? pinY(w.to, 'in') : pinY(w.from, 'out')
const g = map.get(key)
if (g) {
g.wires.push(w)
g.y = Math.min(g.y, y)
} else map.set(key, { src: w.from, wires: [w], y })
}
return [...map.values()].sort((a, b) => a.y - b.y)
}
const ins = group(incoming, 'in')
const outs = group(outgoing, 'out')
const child: ComponentDef = { id: uid('c'), name: uniqueName(project, name.trim() || 'Part'), symbol: 'box', nodes: [], wires: [] }
for (const n of sel) child.nodes.push({ ...clone(n), x: n.x + ox, y: n.y + oy })
for (const w of internal) {
const copy = clone(w)
if (copy.pts) copy.pts = copy.pts.map(([x, y]) => [x + ox, y + oy])
child.wires.push(copy)
}
const used = new Set<string>()
const pinLabel = (preferred: string | undefined, fallback: string) => {
let label = preferred || fallback
for (let i = 2; used.has(label); i++) label = `${preferred || fallback}${i}`
used.add(label)
return label
}
let nextY = -Infinity
const inPins = ins.map((g, i) => {
const y = Math.max(nextY, g.y + oy)
nextY = y + 2
const node: CircuitNode = { id: uid('n'), kind: 'input', x: 0, y, label: pinLabel(labelOf(g.src.node), `I${i + 1}`) }
child.nodes.push(node)
for (const w of g.wires) child.wires.push({ id: uid('w'), from: { node: node.id, pin: 'q' }, to: w.to })
return { group: g, node }
})
nextY = -Infinity
const outPins = outs.map((g, i) => {
const y = Math.max(nextY, g.y + oy)
nextY = y + 2
const node: CircuitNode = { id: uid('n'), kind: 'output', x: maxX + ox + 4, y, label: pinLabel(labelOf(g.wires[0]!.to.node), `O${i + 1}`) }
child.nodes.push(node)
child.wires.push({ id: uid('w'), from: g.src, to: { node: node.id, pin: 'a' } })
return { group: g, node }
})
project.components.push(child)
// Replace the selection with one chip.
const chipNode: CircuitNode = { id: uid('n'), kind: 'chip', chip: child.id, x: minX, y: minY }
def.nodes = def.nodes.filter(n => !inside(n.id))
def.nodes.push(chipNode)
def.wires = def.wires.filter(w => !inside(w.from.node) && !inside(w.to.node))
for (const { group: g, node } of inPins) {
def.wires.push({ id: uid('w'), from: g.src, to: { node: chipNode.id, pin: node.id } })
}
for (const { group: g, node } of outPins) {
for (const w of g.wires) def.wires.push({ id: uid('w'), from: { node: chipNode.id, pin: node.id }, to: w.to })
}
return { ok: true, def: child, chipNode: chipNode.id }
}
// ── Changing placed parts ───────────────────────────────────────────
export type SwapTarget = { kind: NodeKind; chip?: string }
/** Kinds that can replace each other because they play the same role. */
export const SOURCE_KINDS: NodeKind[] = ['input', 'button', 'clock', 'high', 'low']
export const SINK_KINDS: NodeKind[] = ['output', 'lamp', 'hex']
/** Pin keys of a node, in pin order. */
export function pinKeys(node: CircuitNode, get: DefLookup): { ins: string[]; outs: string[] } {
const def = node.kind === 'chip' && node.chip ? get(node.chip) : undefined
const pins = def ? chipPins(def) : undefined
return { ins: inputKeys(node, pins, get), outs: outputKeys(node, pins, get) }
}
/**
* Replaces a placed part with another one without unwiring it: wires stay on
* the pin in the same position (first input to first input, and so on).
* Wires on pins the new part doesn't have are removed; returns how many.
*/
export function swapNode(project: Project, def: ComponentDef, nodeId: string, target: SwapTarget): number {
const get = lookup(project)
const node = def.nodes.find(n => n.id === nodeId)
if (!node) return 0
const before = pinKeys(node, get)
const after = pinKeys({ ...node, kind: target.kind, chip: target.chip }, get)
const map = (pin: string, from: string[], to: string[]) => {
const i = from.indexOf(pin)
return i >= 0 && i < to.length ? to[i] : undefined
}
let removed = 0
def.wires = def.wires.filter(w => {
const to = w.to.node === nodeId ? map(w.to.pin, before.ins, after.ins) : w.to.pin
const from = w.from.node === nodeId ? map(w.from.pin, before.outs, after.outs) : w.from.pin
if (!to || !from) {
removed++
return false
}
w.to = { node: w.to.node, pin: to }
w.from = { node: w.from.node, pin: from }
return true
})
// Bubbles stay on the input in the same position, like wires.
if (node.invert?.length) {
const kept = node.invert.map(k => map(k, before.ins, after.ins)).filter((k): k is string => !!k)
if (kept.length && ['nand', 'chip', 'output', 'lamp'].includes(target.kind)) node.invert = [...new Set(kept)]
else delete node.invert
}
node.kind = target.kind
if (target.chip) node.chip = target.chip
else delete node.chip
// Drop settings the new kind doesn't use.
if (target.kind !== 'clock') delete node.hz
if (target.kind !== 'input') delete node.on
if (target.kind !== 'input' && target.kind !== 'button') delete node.key
if (target.kind !== 'lamp' && target.kind !== 'hex') delete node.color
if (target.kind !== 'note') delete node.size
if (target.kind !== 'chip') delete node.splitPorts
return removed
}
/**
* Shows a port of a placed component split into a pin per line below its
* socket, to wire lines by hand, or joined into the socket alone again.
* Joining removes the wires on its lines; returns how many.
*/
export function splitPort(project: Project, def: ComponentDef, nodeId: string, port: string, split: boolean): number {
const get = lookup(project)
const node = def.nodes.find(n => n.id === nodeId)
const child = node?.kind === 'chip' && node.chip ? get(node.chip) : undefined
if (!node || !child || !chipPins(child).ports?.some(p => p.key === port)) return 0
const ports = new Set(node.splitPorts ?? [])
if (split) ports.add(port)
else ports.delete(port)
if (ports.size) node.splitPorts = [...ports]
else delete node.splitPorts
// The lines' pins are gone, and so are the wires on them.
const before = def.wires.length
pruneWires(project)
return before - def.wires.length
}
/**
* The line of a component's port a single wire takes when dropped on its
* socket: the first free one going into the component (`enters`, for a wire
* from an output), or coming out of it (for a wire to an input; every line
* can feed more wires, an unused one first). Null when no line runs that way.
*/
export function lineForWire(project: Project, def: ComponentDef, nodeId: string, port: string, enters: boolean): string | null {
const get = lookup(project)
const node = def.nodes.find(n => n.id === nodeId)
const child = node?.kind === 'chip' && node.chip ? get(node.chip) : undefined
if (!node || !child) return null
const lines = splitLines({ ...node, splitPorts: [port] }, chipPins(child), get).filter(l => l.enters === enters)
const used = new Set(enters ? def.wires.filter(w => w.to.node === nodeId).map(w => w.to.pin) : def.wires.filter(w => w.from.node === nodeId).map(w => w.from.pin))
return (lines.find(l => !used.has(l.key)) ?? (enters ? undefined : lines[0]))?.key ?? null
}
/**
* Removes every wire attached to the given parts. Returns how many. A cable
* (bundle to split) is part of the cable, not a connection: it stays, only
* the wires into the bundle and out of the split go.
*/
export function unlinkWires(def: ComponentDef, ids: Set<string>): number {
const kind = new Map(def.nodes.map(n => [n.id, n.kind]))
const cable = (w: Wire) => kind.get(w.from.node) === 'bundle' && kind.get(w.to.node) === 'split'
const before = def.wires.length
def.wires = def.wires.filter(w => cable(w) || (!ids.has(w.from.node) && !ids.has(w.to.node)))
return before - def.wires.length
}
/**
* Replaces a placed component with the parts inside it (the reverse of
* "Make component"). Its pins disappear: outside wires are joined straight
* to the parts they reached inside. Returns the ids of the new parts.
*/
export function unpackChip(project: Project, defId: string, nodeId: string): { ok: true; nodes: string[] } | { ok: false; error: string } {
const get = lookup(project)
const def = get(defId)
const chip = def?.nodes.find(n => n.id === nodeId)
const child = chip?.chip ? get(chip.chip) : undefined
if (!def || !chip || chip.kind !== 'chip' || !child) return { ok: false, error: 'Not a component' }
const inner = child.nodes.filter(n => n.kind !== 'input' && n.kind !== 'output')
const minX = inner.length ? Math.min(...inner.map(n => n.x)) : 0
const minY = inner.length ? Math.min(...inner.map(n => n.y)) : 0
const ox = chip.x - minX
const oy = chip.y - minY
const ids = new Map<string, string>()
for (const n of inner) {
const id = uid('n')
ids.set(n.id, id)
def.nodes.push({ ...clone(n), id, x: n.x + ox, y: n.y + oy })
}
const fresh = new Set(ids.values())
redock(def.nodes.filter(n => fresh.has(n.id)), ids)
const kindOf = new Map(child.nodes.map(n => [n.id, n.kind]))
const feed = new Map<string, Wire['from']>()
for (const w of def.wires) if (w.to.node === chip.id) feed.set(w.to.pin, w.from)
const resolve = (ref: Wire['from']): Wire['from'] | undefined =>
kindOf.get(ref.node) === 'input' ? feed.get(ref.node) : ids.has(ref.node) ? { node: ids.get(ref.node)!, pin: ref.pin } : undefined
const added: Wire[] = []
for (const w of child.wires) {
if (!ids.has(w.to.node)) continue
const from = resolve(w.from)
if (!from) continue
const wire: Wire = { id: uid('w'), from, to: { node: ids.get(w.to.node)!, pin: w.to.pin } }
if (ids.has(w.from.node) && w.pts) wire.pts = w.pts.map(([x, y]) => [x + ox, y + oy])
if (w.color) wire.color = w.color
added.push(wire)
}
for (const w of def.wires) {
if (w.from.node !== chip.id) continue
const inside = child.wires.find(x => x.to.node === w.from.pin)
const from = inside && resolve(inside.from)
if (from) added.push({ id: uid('w'), from, to: w.to })
}
def.nodes = def.nodes.filter(n => n !== chip)
def.wires = [...def.wires.filter(w => w.from.node !== chip.id && w.to.node !== chip.id), ...added]
return { ok: true, nodes: [...ids.values()] }
}
/** Points one placed component at its own copy of the definition, so edits to it don't change the others. */
export function makeUnique(project: Project, def: ComponentDef, nodeId: string): ComponentDef | undefined {
const node = def.nodes.find(n => n.id === nodeId)
if (!node?.chip) return undefined
const copy = duplicateComponent(project, node.chip)
if (copy) node.chip = copy.id
return copy
}