diff --git a/app/composables/useEditor.ts b/app/composables/useEditor.ts
index eeaf5b1..acf6975 100644
--- a/app/composables/useEditor.ts
+++ b/app/composables/useEditor.ts
@@ -23,6 +23,7 @@ import { challengeName, challengeOpen, defUsable, isCampaign, KIND_NAMES, kindUn
import { apiId, makePuzzle, scoreSolution, weekKey, weeklyId } from '~/lib/logic/puzzles'
import { baseOf, MAX_GATE_INPUTS, NAND_BASE, wideGate } from '~/lib/logic/wide'
import { CHALLENGES, challengeSteps, type Challenge } from '~/lib/logic/challenges'
+import { latchedTo, latchInto, latchTarget, syncLatches } from '~/lib/logic/latch'
import { compile, INVERTIBLE, invertedPins, rowSource } from '~/lib/logic/compile'
import { chipPins, MAX_BITS, panelOffsets, pinKindOf, shapeOf, type Pt } from '~/lib/logic/geometry'
import { adoptName, continueSeries, newPinLabel, uniqueLabel, usedLabels } from '~/lib/logic/labels'
@@ -242,6 +243,7 @@ function create() {
const canRedo = ref(false)
function resetHistory() {
+ syncLatches(project.value)
syncCables(project.value)
undoStack.length = 0
redoStack.length = 0
@@ -252,13 +254,14 @@ function create() {
/**
* Record a change. Structural changes (parts, wires) rebuild the simulation.
- * Cables follow every change: a new name or a moved part shows on them.
+ * Latched parts and cables follow every change: a moved part takes them along.
*/
function commit(structural = true) {
if (structural) {
syncPanels(project.value)
pruneWires(project.value)
}
+ syncLatches(project.value)
syncCables(project.value)
const s = snap()
if (s === last) return
@@ -680,7 +683,7 @@ function create() {
const set = new Set(ids)
for (let size = -1; size !== set.size; ) {
size = set.size
- for (const p of [...dockedPanels(def.value, set), ...pluggedInto(def.value, set)]) set.add(p.id)
+ for (const p of [...dockedPanels(def.value, set), ...pluggedInto(def.value, set), ...latchedTo(def.value, set)]) set.add(p.id)
}
return set
}
@@ -1058,7 +1061,34 @@ function create() {
/** Ends dragged away from the part they are plugged into come loose. */
function unplugMoved(ids: Set) {
- for (const n of def.value.nodes) if (n.plug && ids.has(n.id) && !ids.has(n.plug)) delete n.plug
+ for (const n of def.value.nodes) {
+ if (n.plug && ids.has(n.id) && !ids.has(n.plug)) delete n.plug
+ if (n.latch && ids.has(n.id) && !ids.has(n.latch)) delete n.latch
+ }
+ }
+
+ /** The part a part could latch onto: wired to it, its pins lining up exactly. */
+ function latchTargetOf(n: CircuitNode): CircuitNode | undefined {
+ return n.latch ? undefined : latchTarget(def.value, n, getDef.value)
+ }
+
+ /** Latches a part onto the part it fits: it moves onto that part's pins and goes along with it. */
+ function latchPart(n: CircuitNode) {
+ const host = latchTarget(def.value, n, getDef.value)
+ if (!host || !latchInto(def.value, n, host.id, getDef.value)) {
+ return notify('Its pins must line up with the pins it is wired to, one for one', 'error')
+ }
+ commit()
+ play('connect')
+ }
+
+ /** Lets a latched part go: it steps two squares away and its wires show again. */
+ function unlatch(n: CircuitNode) {
+ const host = n.latch ? def.value.nodes.find(x => x.id === n.latch) : undefined
+ if (!host) return
+ delete n.latch
+ n.x += n.x >= host.x ? 2 : -2
+ commit()
}
function setPitch(end: CircuitNode, pitch: number) {
@@ -2329,6 +2359,9 @@ function create() {
fitHover,
connectFit,
unplugMoved,
+ latchTargetOf,
+ latchPart,
+ unlatch,
moveRow,
setRowGap,
setRowKey,
diff --git a/app/composables/useMenu.ts b/app/composables/useMenu.ts
index 9bf265a..3ffb1db 100644
--- a/app/composables/useMenu.ts
+++ b/app/composables/useMenu.ts
@@ -150,6 +150,16 @@ export function useMenu() {
if (NAMED.includes(n.kind)) out.push({ label: n.kind === 'note' ? 'Edit text' : 'Rename', icon: 'lucide:pencil', keys: 'Double-click', run: () => rename(n.id) })
const swaps = swapChoices([n])
if (swaps.length) out.push({ label: 'Change to', icon: 'lucide:replace', children: swaps })
+ // Latching: straight onto the part it is wired to, when its pins line up with that part's.
+ const host = n.latch ? ed.def.value.nodes.find(x => x.id === n.latch) : ed.latchTargetOf(n)
+ if (host) {
+ const name = host.label?.trim() && !host.autoLabel ? host.label.trim() : partName(host)
+ out.push(
+ n.latch
+ ? { label: `Unlatch from ${name}`, icon: 'lucide:unlink', run: () => ed.unlatch(n) }
+ : { label: `Latch onto ${name}`, icon: 'lucide:link', run: () => ed.latchPart(n) },
+ )
+ }
const base = baseOf(n, get)
if (base && gateFamily(get, base)) {
const now = inputCount(n, get)
diff --git a/app/lib/logic/latch.ts b/app/lib/logic/latch.ts
new file mode 100644
index 0000000..1a205c4
--- /dev/null
+++ b/app/lib/logic/latch.ts
@@ -0,0 +1,178 @@
+// Latching: a part set right against another so that every pin it shares
+// with it touches that part's pin, like a display on a CPU's outputs or a
+// switch on a component's input. A latched part moves with the part it is
+// latched to; dragging it away (or "Unlatch") lets go and its wires show
+// again. Parts whose shared pins touch latch by themselves. Cable ends plug
+// in the same way (cables.ts); docked panels follow their own rule (panels.ts).
+
+import { shapeOf, type DefLookup, type PinInfo, type Shape } from './geometry'
+import type { CircuitNode, ComponentDef, Project } from './types'
+import { lookup } from './ops'
+
+/** Parts that never latch: cable ends plug instead, notes are not wired. */
+const SKIP = new Set(['bundle', 'split', 'note'])
+
+const canLatch = (n: CircuitNode) => !SKIP.has(n.kind) && !n.attach
+
+interface Pair {
+ /** The guest's pin, relative to the guest. */
+ g: PinInfo
+ /** The host's pin, on the canvas. */
+ hx: number
+ hy: number
+}
+
+/**
+ * The pins a guest shares with a host, as pairs, all on one side: the
+ * guest's inputs fed by the host's outputs (it sits on the host's right),
+ * or its outputs feeding the host's inputs (on its left). Null when its
+ * wires to the host run both ways, or a pin is used twice.
+ */
+function pairsOf(def: ComponentDef, guest: CircuitNode, host: CircuitNode, gs: Shape, hs: Shape): { right: boolean; list: Pair[] } | null {
+ const right: Pair[] = []
+ const left: Pair[] = []
+ for (const w of def.wires) {
+ const fed = w.from.node === host.id && w.to.node === guest.id
+ const feeds = w.from.node === guest.id && w.to.node === host.id
+ if (!fed && !feeds) continue
+ const g = (fed ? gs.inputs : gs.outputs).find(p => p.key === (fed ? w.to.pin : w.from.pin))
+ const h = (fed ? hs.outputs : hs.inputs).find(p => p.key === (fed ? w.from.pin : w.to.pin))
+ if (!g || !h || g.bus || h.bus) return null
+ // Pins facing the usual way only: an output's wire leaves right, an input's arrives from the left.
+ const gFace = g.face ?? (fed ? -1 : 1)
+ const hFace = h.face ?? (fed ? 1 : -1)
+ if (gFace !== (fed ? -1 : 1) || hFace !== (fed ? 1 : -1)) return null
+ ;(fed ? right : left).push({ g, hx: host.x + h.dx, hy: host.y + h.dy })
+ }
+ if (right.length && left.length) return null
+ const list = right.length ? right : left
+ if (!list.length || new Set(list.map(p => p.g.key)).size !== list.length) return null
+ return { right: right.length > 0, list }
+}
+
+/**
+ * Where a guest sits latched to a host: every pin it shares with the host on
+ * that pin, all moved by the same step. It has to fit exactly: no other pin
+ * of either part may land on a pin of the other without a wire between them.
+ */
+export function latchLayout(def: ComponentDef, guest: CircuitNode, host: CircuitNode, get: DefLookup): { x: number; y: number; right: boolean } | null {
+ if (guest.id === host.id || !canLatch(guest) || SKIP.has(host.kind)) return null
+ const gs = shapeOf(guest, get)
+ const hs = shapeOf(host, get)
+ const pairs = pairsOf(def, guest, host, gs, hs)
+ if (!pairs) return null
+ const first = pairs.list[0]!
+ const sx = first.hx - (guest.x + first.g.dx)
+ const sy = first.hy - (guest.y + first.g.dy)
+ if (pairs.list.some(p => p.hx - (guest.x + p.g.dx) !== sx || p.hy - (guest.y + p.g.dy) !== sy)) return null
+ const x = guest.x + sx
+ const y = guest.y + sy
+ // Facing pins that would touch without a wire between them would look connected.
+ const mine = pairs.right ? gs.inputs : gs.outputs
+ const theirs = pairs.right ? hs.outputs : hs.inputs
+ const wired = new Set(pairs.list.map(p => `${p.g.key}@${p.hx},${p.hy}`))
+ for (const g of mine) {
+ const gx = x + g.dx
+ const gy = y + g.dy
+ const h = theirs.find(t => host.x + t.dx === gx && host.y + t.dy === gy)
+ if (h && !wired.has(`${g.key}@${gx},${gy}`)) return null
+ }
+ return { x, y, right: pairs.right }
+}
+
+/** The part a part can latch onto: one it is wired to whose pins it fits exactly (most shared pins first). */
+export function latchTarget(def: ComponentDef, guest: CircuitNode, get: DefLookup): CircuitNode | undefined {
+ if (!canLatch(guest)) return
+ const ids = new Set()
+ for (const w of def.wires) {
+ if (w.from.node === guest.id) ids.add(w.to.node)
+ if (w.to.node === guest.id) ids.add(w.from.node)
+ }
+ ids.delete(guest.id)
+ let best: CircuitNode | undefined
+ let most = 0
+ for (const id of ids) {
+ const host = def.nodes.find(n => n.id === id)
+ if (!host || !latchLayout(def, guest, host, get) || hostChain(def, host).has(guest.id)) continue
+ const n = def.wires.filter(w => (w.from.node === id && w.to.node === guest.id) || (w.from.node === guest.id && w.to.node === id)).length
+ if (n > most) {
+ best = host
+ most = n
+ }
+ }
+ return best
+}
+
+/** The parts a part is latched to, directly or through others. */
+function hostChain(def: ComponentDef, n: CircuitNode): Set {
+ const out = new Set()
+ let at: CircuitNode | undefined = n
+ while (at?.latch && !out.has(at.latch)) {
+ out.add(at.latch)
+ at = def.nodes.find(x => x.id === at!.latch)
+ }
+ return out
+}
+
+/** Latches a part onto a host: it moves onto the host's pins and its wires to it lose their bends. False when it doesn't fit. */
+export function latchInto(def: ComponentDef, guest: CircuitNode, hostId: string, get: DefLookup): boolean {
+ const host = def.nodes.find(n => n.id === hostId)
+ const lay = host && !hostChain(def, host).has(guest.id) ? latchLayout(def, guest, host, get) : null
+ if (!host || !lay) {
+ delete guest.latch
+ return false
+ }
+ guest.latch = host.id
+ guest.x = lay.x
+ guest.y = lay.y
+ for (const w of def.wires) if ((w.from.node === host.id && w.to.node === guest.id) || (w.from.node === guest.id && w.to.node === host.id)) delete w.pts
+ return true
+}
+
+const area = (s: Shape) => s.body.w * s.body.h
+
+/**
+ * The part a part's shared pins already all touch, so it counts as latched.
+ * Of two parts that touch, the smaller one latches onto the larger; as large
+ * as each other, the one that is fed latches onto the one feeding it.
+ */
+function touchingHost(def: ComponentDef, guest: CircuitNode, get: DefLookup): string | null {
+ const host = latchTarget(def, guest, get)
+ const lay = host && latchLayout(def, guest, host, get)
+ if (!host || !lay || lay.x !== guest.x || lay.y !== guest.y) return null
+ const a = area(shapeOf(guest, get))
+ const b = area(shapeOf(host, get))
+ if (a > b || (a === b && !lay.right)) return null
+ return host.id
+}
+
+/** Keeps every latched part on its host's pins; parts that newly touch latch, ones that no longer fit let go. */
+export function syncLatches(project: Project) {
+ const get = lookup(project)
+ for (const def of project.components) {
+ if (def.nodes.length < 2) continue
+ for (const n of def.nodes) {
+ if (!canLatch(n)) {
+ delete n.latch
+ continue
+ }
+ const id = n.latch ?? touchingHost(def, n, get)
+ if (id) latchInto(def, n, id, get)
+ }
+ }
+}
+
+/** Parts latched onto any of `ids`. */
+export function latchedTo(def: ComponentDef, ids: Set): CircuitNode[] {
+ return def.nodes.filter(n => n.latch && ids.has(n.latch))
+}
+
+/** Where a latched part touches its host, relative to the part: the column of its pins and their top and bottom rows. */
+export function latchSeam(def: ComponentDef, guest: CircuitNode, get: DefLookup): { x: number; y0: number; y1: number } | null {
+ const host = guest.latch ? def.nodes.find(n => n.id === guest.latch) : undefined
+ if (!host) return null
+ const pairs = pairsOf(def, guest, host, shapeOf(guest, get), shapeOf(host, get))
+ if (!pairs) return null
+ const ys = pairs.list.map(p => p.g.dy)
+ return { x: pairs.list[0]!.g.dx, y0: Math.min(...ys), y1: Math.max(...ys) }
+}
diff --git a/app/lib/logic/ops.ts b/app/lib/logic/ops.ts
index 4e4b0d0..288ce03 100644
--- a/app/lib/logic/ops.ts
+++ b/app/lib/logic/ops.ts
@@ -250,15 +250,18 @@ export function pasteClip(def: ComponentDef, clip: Clip, dx: number, dy: number)
}
/**
- * Copied panels dock to the copy of their component, and copied cable ends
- * plug into the copy of their part, or to nothing when it was not copied along.
+ * 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) {
for (const n of nodes) {
- if (n.plug) {
- const to = ids.get(n.plug)
- if (to) n.plug = to
- else delete n.plug
+ 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)
diff --git a/app/lib/logic/project.ts b/app/lib/logic/project.ts
index 5024268..734befc 100644
--- a/app/lib/logic/project.ts
+++ b/app/lib/logic/project.ts
@@ -36,6 +36,7 @@ function cleanNode(n: CircuitNode) {
else n.rows = n.rows.filter(cleanRow).slice(0, MAX_ROWS)
}
if (n.plug !== undefined && typeof n.plug !== 'string') delete n.plug
+ if (n.latch !== undefined && typeof n.latch !== 'string') delete n.latch
if (n.pitch !== undefined && !(Number.isInteger(n.pitch) && n.pitch >= 1 && n.pitch <= 8)) delete n.pitch
if (n.offsets !== undefined && !(Array.isArray(n.offsets) && n.offsets.every(v => Number.isInteger(v) && v >= 0 && v <= 10_000))) delete n.offsets
for (const k of ['names', 'invert'] as const) {
diff --git a/app/lib/logic/routing.ts b/app/lib/logic/routing.ts
index 1ee5856..5d4e181 100644
--- a/app/lib/logic/routing.ts
+++ b/app/lib/logic/routing.ts
@@ -287,8 +287,8 @@ const CROSS = 1.5
const ALONG = 60
const PIN = 300
/** Most points one search looks at before it gives up, and all searches of one routing together. */
-const MAX_VISITS = 8_000
-const ALL_VISITS = 200_000
+const MAX_VISITS = 6_000
+const ALL_VISITS = 120_000
/** A tiny binary heap of (cost, state). */
class Heap {
diff --git a/app/lib/logic/types.ts b/app/lib/logic/types.ts
index 1a7bdb8..49c9547 100644
--- a/app/lib/logic/types.ts
+++ b/app/lib/logic/types.ts
@@ -60,6 +60,8 @@ export interface CircuitNode {
skip?: string[]
/** Cable end plugged straight into a part: the id of that part. It sits on the part's pins and moves with it. */
plug?: string
+ /** Part latched straight onto another: the id of that part. Its shared pins touch, and it moves with it. */
+ latch?: string
/** Grid rows from one wire of a cable end to the next. Empty: 1. */
pitch?: number
/** Cable end plugged into pins that are not evenly spaced: each wire's row below the first. */
diff --git a/tests/latch.test.ts b/tests/latch.test.ts
new file mode 100644
index 0000000..7417693
--- /dev/null
+++ b/tests/latch.test.ts
@@ -0,0 +1,85 @@
+import { describe, expect, it } from 'vitest'
+import { shapeOf } from '../app/lib/logic/geometry'
+import { latchedTo, latchInto, latchLayout, latchTarget, syncLatches } from '../app/lib/logic/latch'
+import { createProject, lookup } from '../app/lib/logic/ops'
+import type { ComponentDef, Project } from '../app/lib/logic/types'
+
+/** A 4-bit counter's outputs (the example component) feeding a hex display placed further right. */
+function setup(order = [0, 1, 2, 3]): { p: Project; def: ComponentDef } {
+ const p = createProject({ examples: true })
+ const counter = p.components.find(d => d.id === 'ex-counter4') ?? p.components.find(d => /counter/i.test(d.name))!
+ const def: ComponentDef = { id: 'root', name: 'Root', symbol: 'box', nodes: [{ id: 'c', kind: 'chip', chip: counter.id, x: 0, y: 0 }, { id: 'h', kind: 'hex', x: 20, y: 3 }], wires: [] }
+ const outs = shapeOf(def.nodes[0]!, lookup(p)).outputs.slice(0, 4)
+ outs.forEach((o, i) => def.wires.push({ id: `w${i}`, from: { node: 'c', pin: o.key }, to: { node: 'h', pin: `b${order[i]}` } }))
+ p.components.push(def)
+ return { p, def }
+}
+
+describe('latching a part onto another', () => {
+ it('a display wired to four outputs in order latches onto them: its inputs on their pins', () => {
+ const { p, def } = setup()
+ const get = lookup(p)
+ const hex = def.nodes[1]!
+ expect(latchTarget(def, hex, get)?.id).toBe('c')
+ expect(latchInto(def, hex, 'c', get)).toBe(true)
+ expect(hex.latch).toBe('c')
+ const chip = def.nodes[0]!
+ const outs = shapeOf(chip, get).outputs.slice(0, 4)
+ const ins = shapeOf(hex, get).inputs
+ outs.forEach((o, i) => {
+ expect(hex.x + ins[i]!.dx).toBe(chip.x + o.dx)
+ expect(hex.y + ins[i]!.dy).toBe(chip.y + o.dy)
+ })
+ })
+
+ it('wired in another order it does not fit, so it does not latch', () => {
+ const { p, def } = setup([1, 0, 2, 3])
+ expect(latchTarget(def, def.nodes[1]!, lookup(p))).toBeUndefined()
+ })
+
+ it('a pin that would land on a pin it is not wired to keeps it from latching', () => {
+ const { p, def } = setup()
+ // Only three of the four outputs are wired: the fourth input would sit on an output without a wire.
+ def.wires = def.wires.filter(w => w.id !== 'w3')
+ const get = lookup(p)
+ expect(latchLayout(def, def.nodes[1]!, def.nodes[0]!, get)).toBeNull()
+ })
+
+ it('parts whose shared pins already touch latch by themselves, the smaller onto the larger', () => {
+ const { p, def } = setup()
+ const get = lookup(p)
+ const hex = def.nodes[1]!
+ const lay = latchLayout(def, hex, def.nodes[0]!, get)!
+ hex.x = lay.x
+ hex.y = lay.y
+ syncLatches(p)
+ expect(hex.latch).toBe('c')
+ expect(def.nodes[0]!.latch).toBeUndefined()
+ expect(latchedTo(def, new Set(['c'])).map(n => n.id)).toEqual(['h'])
+ })
+
+ it('a latched part stays on its part\'s pins when that part moves', () => {
+ const { p, def } = setup()
+ const get = lookup(p)
+ const hex = def.nodes[1]!
+ latchInto(def, hex, 'c', get)
+ const dx = hex.x - def.nodes[0]!.x
+ def.nodes[0]!.x += 7
+ syncLatches(p)
+ expect(hex.x - def.nodes[0]!.x).toBe(dx)
+ })
+
+ it('a switch feeding a component input from the left latches onto it', () => {
+ const { p, def } = setup()
+ const get = lookup(p)
+ const chip = def.nodes[0]!
+ const pin = shapeOf(chip, get).inputs[0]!
+ def.nodes.push({ id: 's', kind: 'input', x: -10, y: 5 })
+ def.wires.push({ id: 'ws', from: { node: 's', pin: 'q' }, to: { node: 'c', pin: pin.key } })
+ const sw = def.nodes[2]!
+ expect(latchTarget(def, sw, get)?.id).toBe('c')
+ latchInto(def, sw, 'c', get)
+ const out = shapeOf(sw, get).outputs[0]!
+ expect([sw.x + out.dx, sw.y + out.dy]).toEqual([chip.x + pin.dx, chip.y + pin.dy])
+ })
+})