BF split ports: no wire against the cable, pins that stay put, lines kept on unpack

A wire dropped on a socket with a cable in it only takes a line coming
out; the lines going in are the cable's, so it no longer drives one
against the cable. Wired by hand anyway, the check calls that an error,
like a signal sent by two parts. A line going in with neither a wire nor
a cable gets the usual "not connected (reads 0)" warning and marker.

While a wire is drawn over a socket it ends on the socket, where it goes
when let go, not on the pin below. Splitting or joining a port no longer
moves the pins on the other side of the box. Pins on their usual edge
come first, so a wire dropped on the box body takes those, and the cable
button only offers pins whose cable end sits outside the box.

Unpacking a component joins wires on its split lines to the parts that
used the line inside; wires that had nowhere to go are counted in a
notice. Docked panels line up with the moved ports when a project is
opened, not at the next edit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-26 18:38:32 +01:00
parent 1be913bd24
commit 049f84eb64
8 changed files with 193 additions and 35 deletions

View File

@ -15,7 +15,7 @@ Nuxt 4 (client-only editor, `ssr: false`), Tailwind CSS v4, Lucide icons via `@n
- Sound (speaker in the top bar; volume and clock ticks in Settings, the gear in the top bar): clicks for placing, wiring, switches and buttons, a tick per clock cycle up to 8 Hz (off by default), and jingles for a solve, a failed check, unlocks and new records. All synthesised with Web Audio, no sound files ([app/lib/audio.ts](app/lib/audio.ts)). - Sound (speaker in the top bar; volume and clock ticks in Settings, the gear in the top bar): clicks for placing, wiring, switches and buttons, a tick per clock cycle up to 8 Hz (off by default), and jingles for a solve, a failed check, unlocks and new records. All synthesised with Web Audio, no sound files ([app/lib/audio.ts](app/lib/audio.ts)).
- Transistors: every component shows how many it takes, counted as a CMOS NAND (4 transistors) per gate at every depth: in the palette, its settings and the circuit stats. Each challenge keeps your record, the fewest transistors of any passing solution, and says so when you beat it. - Transistors: every component shows how many it takes, counted as a CMOS NAND (4 transistors) per gate at every depth: in the palette, its settings and the circuit stats. Each challenge keeps your record, the fewest transistors of any passing solution, and says so when you beat it.
- Cables: a bundle gathers 2 to 32 wires into one cable, a split fans it out again in the same order; one bundle can feed several splits. Select the wires (a box across them, or Shift + click) and press "Bundle into cable" or Ctrl+G: the cable starts right after the sources on their middle row and ends right before the targets on theirs, so the wires keep running as they did (backwards too); an end steps aside when another part is in the way. "Place the ends yourself…" (Ctrl+Shift+G) lets you click where it starts and ends, with a preview; Esc cancels. "Unlink all" on a bundle or split removes only the wires going in or out; the cable stays. Drag the bundle and split later to move the ends. Up to 16 wires, the cable is drawn as a ribbon: each wire is its own thin line inside, in its own colour, lit while it carries a 1. The sleeve starts neutral and gets its own colour (cable or bundle/split settings). "Remove cable" turns it back into single wires. A cable end only joins another cable end, and the cable shows its width. - Cables: a bundle gathers 2 to 32 wires into one cable, a split fans it out again in the same order; one bundle can feed several splits. Select the wires (a box across them, or Shift + click) and press "Bundle into cable" or Ctrl+G: the cable starts right after the sources on their middle row and ends right before the targets on theirs, so the wires keep running as they did (backwards too); an end steps aside when another part is in the way. "Place the ends yourself…" (Ctrl+Shift+G) lets you click where it starts and ends, with a preview; Esc cancels. "Unlink all" on a bundle or split removes only the wires going in or out; the cable stays. Drag the bundle and split later to move the ends. Up to 16 wires, the cable is drawn as a ribbon: each wire is its own thin line inside, in its own colour, lit while it carries a 1. The sleeve starts neutral and gets its own colour (cable or bundle/split settings). "Remove cable" turns it back into single wires. A cable end only joins another cable end, and the cable shows its width.
- Connectors (your own HDMI, RJ45, buses): in the bottom bar's Connectors, "New connector type" makes one: a name, a colour, and lines that each run out → in or back (acknowledge, hot-plug, a receive pair). Each type gives two parts, "<type> out" and "<type> in". Inside a component, a port shows its lines as pins on its inner side (lines coming in are outputs, lines going out inputs) and has a cable pin at the top to hand the whole cable on to a part inside; on the component's box it is one port at the very top of its side, in ports on the left, out ports on the right, drawn as a socket in the type's colour. "Split … into lines" (selection panel or right click on the component) gives that box a pin per line right below the socket, named after the line, to wire lines by hand without an adapter: lines going into the component are inputs, lines coming out outputs, and a cable still plugs into the socket. Dropping a single wire on a socket does the same and takes the first free line. "Join … lines" takes the line pins and their wires away again. One cable joins an out port to an in port of the same type and carries every line, forward and back; it is drawn as a sleeve in the type's colour with its name. Ports of different types never join, and a cable whose ends stop matching (a port changed type) is removed. Editing a type changes every port and cable of it; lines are matched by their place in the list. A type can only be deleted once no port uses it. - Connectors (your own HDMI, RJ45, buses): in the bottom bar's Connectors, "New connector type" makes one: a name, a colour, and lines that each run out → in or back (acknowledge, hot-plug, a receive pair). Each type gives two parts, "<type> out" and "<type> in". Inside a component, a port shows its lines as pins on its inner side (lines coming in are outputs, lines going out inputs) and has a cable pin at the top to hand the whole cable on to a part inside; on the component's box it is one port at the very top of its side, in ports on the left, out ports on the right, drawn as a socket in the type's colour. "Split … into lines" (selection panel or right click on the component) gives that box a pin per line right below the socket, named after the line, to wire lines by hand without an adapter: lines going into the component are inputs, lines coming out outputs, and a cable still plugs into the socket. Dropping a single wire on a socket does the same and takes the first free line (with a cable in the socket, only a line coming out: the cable feeds the others). "Join … lines" takes the line pins and their wires away again. One cable joins an out port to an in port of the same type and carries every line, forward and back; it is drawn as a sleeve in the type's colour with its name. Ports of different types never join, and a cable whose ends stop matching (a port changed type) is removed. Editing a type changes every port and cable of it; lines are matched by their place in the list. A type can only be deleted once no port uses it.
- Pixels and screens: a pixel is a one-grid square that lights at 1, in five colours. Inside a component all pixels show on its box as one screen without gaps (every column and row they sit on becomes one of the screen), so you build your own LCD; see "Screen 4×4" and "Demo: Screen". - Pixels and screens: a pixel is a one-grid square that lights at 1, in five colours. Inside a component all pixels show on its box as one screen without gaps (every column and row they sit on becomes one of the screen), so you build your own LCD; see "Screen 4×4" and "Demo: Screen".
- Input panel: one part with a column of controls; each row is a switch, button or clock. "Attach input panel" on a placed component docks one to its left with a row per free input, lined up with the pins and named after them. A docked panel moves with its component, gets a row when the component gains an input and loses it when the pin goes; inputs that are wired elsewhere, and rows you remove, are left alone. Inside a component a switch row keeps its position and a button row is 0. - Input panel: one part with a column of controls; each row is a switch, button or clock. "Attach input panel" on a placed component docks one to its left with a row per free input, lined up with the pins and named after them. A docked panel moves with its component, gets a row when the component gains an input and loses it when the pin goes; inputs that are wired elsewhere, and rows you remove, are left alone. Inside a component a switch row keeps its position and a button row is 0.
- Automatic names: copies continue a series (D0 copied gives D1, D2; A gives B), and so does placing a new input or output after a numbered one. A switch, button, lamp or output pin without a name of its own (or with an automatic one) takes the name of the component pin it gets wired to, made unique (Cin, Cin2); a name typed by hand is kept. On the canvas, a switch, button, clock, lamp or output pin without a name typed by hand shows the name of the component pin it is wired to, dimmed and in italics (or its automatic name, also dimmed); the name follows the wiring as it changes. - Automatic names: copies continue a series (D0 copied gives D1, D2; A gives B), and so does placing a new input or output after a numbered one. A switch, button, lamp or output pin without a name of its own (or with an automatic one) takes the name of the component pin it gets wired to, made unique (Cin, Cin2); a name typed by hand is kept. On the canvas, a switch, button, clock, lamp or output pin without a name typed by hand shows the name of the component pin it is wired to, dimmed and in italics (or its automatic name, also dimmed); the name follows the wiring as it changes.

View File

@ -845,7 +845,9 @@ const openPins = computed(() => {
const out = new Map<string, Set<string>>() const out = new Map<string, Set<string>>()
for (const n of def.value.nodes) { for (const n of def.value.nodes) {
if (!CHECKED_INPUTS.has(n.kind)) continue if (!CHECKED_INPUTS.has(n.kind)) continue
const open = shapes.value.get(n.id)!.inputs.filter(p => !p.bus && !p.port && !linked.value.in.has(`${n.id}:${p.key}`)).map(p => p.key) // A line of a split port is fed by the cable when one is in its socket.
const cabled = (port: string) => linked.value.in.has(`${n.id}:${port}`) || linked.value.out.has(`${n.id}:${port}`)
const open = shapes.value.get(n.id)!.inputs.filter(p => !p.bus && !(p.port && cabled(p.port)) && !linked.value.in.has(`${n.id}:${p.key}`)).map(p => p.key)
if (open.length) out.set(n.id, new Set(open)) if (open.length) out.set(n.id, new Set(open))
} }
return out return out
@ -912,13 +914,13 @@ function targetAt(at: Pt, dir: 'in' | 'out', bus = ''): PinRef | null {
* for a wire from an output, or a line coming out, for a wire to an input. * for a wire from an output, or a line coming out, for a wire to an input.
*/ */
const openSockets = computed(() => { const openSockets = computed(() => {
const out: Record<'in' | 'out', { node: string; port: string; x: number; y: number }[]> = { in: [], out: [] } const out: Record<'in' | 'out', { node: string; port: string; x: number; y: number; face: 1 | -1 }[]> = { in: [], out: [] }
for (const n of def.value.nodes) { for (const n of def.value.nodes) {
if (n.kind !== 'chip') continue if (n.kind !== 'chip') continue
const s = shapes.value.get(n.id)! const s = shapes.value.get(n.id)!
for (const p of [...s.inputs, ...s.outputs]) { for (const p of [...s.inputs, ...s.outputs]) {
if (!p.conn || n.splitPorts?.includes(p.key)) continue if (!p.conn || n.splitPorts?.includes(p.key)) continue
const at = { node: n.id, port: p.key, x: n.x + p.dx, y: n.y + p.dy } const at = { node: n.id, port: p.key, x: n.x + p.dx, y: n.y + p.dy, face: p.dx > 0 ? (1 as const) : (-1 as const) }
if (lineForWire(ed.project.value, def.value, n.id, p.key, true)) out.in.push(at) if (lineForWire(ed.project.value, def.value, n.id, p.key, true)) out.in.push(at)
if (lineForWire(ed.project.value, def.value, n.id, p.key, false)) out.out.push(at) if (lineForWire(ed.project.value, def.value, n.id, p.key, false)) out.out.push(at)
} }
@ -1205,11 +1207,16 @@ const tempWire = computed(() => {
const p = pinPos(n, shapes.value.get(n.id)!, d.pin, d.dir) const p = pinPos(n, shapes.value.get(n.id)!, d.pin, d.dir)
if (!p) return null if (!p) return null
const want = d.dir === 'out' ? 'in' : 'out' const want = d.dir === 'out' ? 'in' : 'out'
const target = targetAt(d.cur, want, ed.pinKind(d.node, d.pin, d.dir)) // Over a port's socket the wire ends there, as it does when let go (the port splits into its lines).
const socket = drag.value?.kind === 'wire' && drag.value.replace ? undefined : socketAt(d)
const target = socket ? null : targetAt(d.cur, want, ed.pinKind(d.node, d.pin, d.dir))
let end: Pt = [Math.round(d.cur[0]), Math.round(d.cur[1])] let end: Pt = [Math.round(d.cur[0]), Math.round(d.cur[1])]
// The side the far end faces: a snapped pin's own, else the usual one. // The side the far end faces: a snapped pin's own, else the usual one.
let endFace: 1 | -1 = want === 'in' ? -1 : 1 let endFace: 1 | -1 = want === 'in' ? -1 : 1
if (target) { if (socket) {
end = [socket.x, socket.y]
endFace = socket.face
} else if (target) {
const tn = nodeMap.value.get(target.node)! const tn = nodeMap.value.get(target.node)!
const tp = pinPos(tn, shapes.value.get(tn.id)!, target.pin, want)! const tp = pinPos(tn, shapes.value.get(tn.id)!, target.pin, want)!
end = [tp.x, tp.y] end = [tp.x, tp.y]
@ -1219,7 +1226,7 @@ const tempWire = computed(() => {
d.dir === 'out' d.dir === 'out'
? routeWire([p.x, p.y], end, d.branch && branchTo(d.branch, [p.x, p.y], end), p.face, endFace) ? routeWire([p.x, p.y], end, d.branch && branchTo(d.branch, [p.x, p.y], end), p.face, endFace)
: routeWire(end, [p.x, p.y], undefined, endFace, p.face) : routeWire(end, [p.x, p.y], undefined, endFace, p.face)
return { d: toPath(pts), snapped: !!target, end } return { d: toPath(pts), snapped: !!(socket || target), end }
}) })
const isCable = (w: Wire) => nodeMap.value.get(w.from.node)?.kind === 'bundle' const isCable = (w: Wire) => nodeMap.value.get(w.from.node)?.kind === 'bundle'

View File

@ -245,6 +245,9 @@ function create() {
const canRedo = ref(false) const canRedo = ref(false)
function resetHistory() { function resetHistory() {
// Docked panels line up with pins that moved since the project was saved (ports went to the top), now rather than at the next edit.
syncPanels(project.value)
pruneWires(project.value)
syncLatches(project.value) syncLatches(project.value)
syncCables(project.value) syncCables(project.value)
undoStack.length = 0 undoStack.length = 0
@ -757,6 +760,7 @@ function create() {
selection.value = res.nodes selection.value = res.nodes
wireSel.value = [] wireSel.value = []
commit() commit()
if (res.dropped) notify(`Unpacked. ${res.dropped} wire${res.dropped === 1 ? '' : 's'} on split lines had nowhere to go and ${res.dropped === 1 ? 'was' : 'were'} removed.`)
} }
/** Splits a port on a placed component's box into a pin per line, or joins it into its socket again (the wires on its lines go). */ /** Splits a port on a placed component's box into a pin per line, or joins it into its socket again (the wires on its lines go). */
@ -1138,8 +1142,9 @@ function create() {
const cabled = new Set(d.wires.filter(w => w.from.node === n.id && kinds.get(w.to.node)?.plug === n.id).map(w => w.from.pin)) const cabled = new Set(d.wires.filter(w => w.from.node === n.id && kinds.get(w.to.node)?.plug === n.id).map(w => w.from.pin))
// Inputs already fed by a plugged cable are taken; inputs with a plain wire can take a cable (the wire goes into it). // Inputs already fed by a plugged cable are taken; inputs with a plain wire can take a cable (the wire goes into it).
const fed = new Set(d.wires.filter(w => w.to.node === n.id && kinds.get(w.from.node)?.plug === n.id).map(w => w.to.pin)) const fed = new Set(d.wires.filter(w => w.to.node === n.id && kinds.get(w.from.node)?.plug === n.id).map(w => w.to.pin))
const outs = s.outputs.filter(p => !p.bus).sort((a, b) => a.dy - b.dy) // Pins on their usual edge only: a split port's lines that run the other way sit on the far edge, where no cable end fits.
const ins = n.kind === 'panel' ? [] : s.inputs.filter(p => !p.bus).sort((a, b) => a.dy - b.dy) const outs = s.outputs.filter(p => !p.bus && p.face !== -1).sort((a, b) => a.dy - b.dy)
const ins = n.kind === 'panel' ? [] : s.inputs.filter(p => !p.bus && p.face !== 1).sort((a, b) => a.dy - b.dy)
return { out: pinGroups(outs, k => !cabled.has(k)), in: pinGroups(ins, k => !fed.has(k)) } return { out: pinGroups(outs, k => !cabled.has(k)), in: pinGroups(ins, k => !fed.has(k)) }
} }

View File

@ -499,7 +499,8 @@ function clearSpot(def: ComponentDef, get: DefLookup, x: number, y: number, h: n
export function cableFromPins(def: ComponentDef, partId: string, pins: string[], get: DefLookup): { ok: true; bundle: CircuitNode; split: CircuitNode } | { ok: false; error: string } { export function cableFromPins(def: ComponentDef, partId: string, pins: string[], get: DefLookup): { ok: true; bundle: CircuitNode; split: CircuitNode } | { ok: false; error: string } {
const part = def.nodes.find(n => n.id === partId) const part = def.nodes.find(n => n.id === partId)
if (!part) return { ok: false, error: 'Part not found' } if (!part) return { ok: false, error: 'Part not found' }
const outs = shapeOf(part, get).outputs.filter(p => !p.bus && pins.includes(p.key)).sort((a, b) => a.dy - b.dy) // Outputs on the right edge only: a cable end on the left would sit inside the box.
const outs = shapeOf(part, get).outputs.filter(p => !p.bus && p.face !== -1 && pins.includes(p.key)).sort((a, b) => a.dy - b.dy)
if (outs.length < 2) return { ok: false, error: 'A cable needs at least two pins' } if (outs.length < 2) return { ok: false, error: 'A cable needs at least two pins' }
if (outs.length > MAX_BITS) return { ok: false, error: `A cable holds at most ${MAX_BITS} wires` } if (outs.length > MAX_BITS) return { ok: false, error: `A cable holds at most ${MAX_BITS} wires` }
const bundle: CircuitNode = { id: uid('n'), kind: 'bundle', bits: outs.length, x: part.x + outs[0]!.dx, y: part.y + outs[0]!.dy } const bundle: CircuitNode = { id: uid('n'), kind: 'bundle', bits: outs.length, x: part.x + outs[0]!.dx, y: part.y + outs[0]!.dy }
@ -524,7 +525,8 @@ export function cableIntoPins(def: ComponentDef, partId: string, pins: string[],
const part = def.nodes.find(n => n.id === partId) const part = def.nodes.find(n => n.id === partId)
if (!part) return { ok: false, error: 'Part not found' } if (!part) return { ok: false, error: 'Part not found' }
const fed = new Set(def.wires.filter(w => w.to.node === part.id).map(w => w.to.pin)) const fed = new Set(def.wires.filter(w => w.to.node === part.id).map(w => w.to.pin))
const ins = shapeOf(part, get).inputs.filter(p => !p.bus && pins.includes(p.key) && !fed.has(p.key)).sort((a, b) => a.dy - b.dy) // Inputs on the left edge only: a cable end on the right would sit inside the box.
const ins = shapeOf(part, get).inputs.filter(p => !p.bus && p.face !== 1 && pins.includes(p.key) && !fed.has(p.key)).sort((a, b) => a.dy - b.dy)
if (ins.length < 2) return { ok: false, error: 'A cable needs at least two free inputs' } if (ins.length < 2) return { ok: false, error: 'A cable needs at least two free inputs' }
if (ins.length > MAX_BITS) return { ok: false, error: `A cable holds at most ${MAX_BITS} wires` } if (ins.length > MAX_BITS) return { ok: false, error: `A cable holds at most ${MAX_BITS} wires` }
const split: CircuitNode = { id: uid('n'), kind: 'split', bits: ins.length, x: part.x + ins[0]!.dx - 1, y: part.y + ins[0]!.dy } const split: CircuitNode = { id: uid('n'), kind: 'split', bits: ins.length, x: part.x + ins[0]!.dx - 1, y: part.y + ins[0]!.dy }

View File

@ -25,18 +25,21 @@ function partName(n: CircuitNode, get: DefLookup): string {
return own ? `${kind} ${own}` : (n.label?.trim() ? `${kind} ${n.label.trim()}` : kind) return own ? `${kind} ${own}` : (n.label?.trim() ? `${kind} ${n.label.trim()}` : kind)
} }
/** Input pins of a part that have no wire (the lines of a split port may stay open: a cable can feed them). */ /** Pins of a part with a wire or cable, coming in or going out. */
const linkedPins = (def: ComponentDef, n: CircuitNode) => new Set(def.wires.flatMap(w => [w.to.node === n.id ? w.to.pin : '', w.from.node === n.id ? w.from.pin : '']))
/** Input pins of a part that have no wire (a line of a split port is fed by the cable when one is in its socket). */
export function openInputs(def: ComponentDef, n: CircuitNode, get: DefLookup): string[] { export function openInputs(def: ComponentDef, n: CircuitNode, get: DefLookup): string[] {
if (!CHECKED_INPUTS.has(n.kind)) return [] if (!CHECKED_INPUTS.has(n.kind)) return []
const linked = linkedPins(def, n)
const wired = new Set(def.wires.filter(w => w.to.node === n.id).map(w => w.to.pin)) const wired = new Set(def.wires.filter(w => w.to.node === n.id).map(w => w.to.pin))
return shapeOf(n, get).inputs.filter(p => !p.bus && !p.port && !wired.has(p.key)).map(p => p.key) return shapeOf(n, get).inputs.filter(p => !p.bus && !(p.port && linked.has(p.port)) && !wired.has(p.key)).map(p => p.key)
} }
/** Lines of split ports on a component's box that are wired by hand while a cable is plugged into their port. */ /** Lines of split ports on a component's box that are wired by hand while a cable is plugged into their port. */
export function doublyFedLines(def: ComponentDef, n: CircuitNode, get: DefLookup): string[] { export function doublyFedLines(def: ComponentDef, n: CircuitNode, get: DefLookup): string[] {
if (n.kind !== 'chip' || !n.splitPorts?.length) return [] if (n.kind !== 'chip' || !n.splitPorts?.length) return []
// Its pins with a wire or cable, coming in or going out. const linked = linkedPins(def, n)
const linked = new Set(def.wires.flatMap(w => [w.to.node === n.id ? w.to.pin : '', w.from.node === n.id ? w.from.pin : '']))
return shapeOf(n, get).inputs.filter(p => p.port && linked.has(p.key) && linked.has(p.port)).map(p => p.key) return shapeOf(n, get).inputs.filter(p => p.port && linked.has(p.key) && linked.has(p.port)).map(p => p.key)
} }
@ -66,7 +69,7 @@ export function checkCircuit(def: ComponentDef, get: DefLookup): Issue[] {
if (twice.length) { if (twice.length) {
const shape = shapeOf(n, get) const shape = shapeOf(n, get)
const labels = twice.map(k => shape.inputs.find(p => p.key === k)?.label || k) const labels = twice.map(k => shape.inputs.find(p => p.key === k)?.label || k)
issues.push({ level: 'warn', text: `${name(n)}: ${labels.join(', ')} wired and fed by the cable as well: both drive ${twice.length === 1 ? 'it' : 'them'}`, nodes: [n.id] }) issues.push({ level: 'error', text: `${name(n)}: ${labels.join(', ')} wired and fed by the cable as well: they drive ${twice.length === 1 ? 'it' : 'them'} against each other`, nodes: [n.id] })
} }
// Parts that drive nothing. // Parts that drive nothing.
if ((n.kind === 'input' || n.kind === 'button' || n.kind === 'clock' || n.kind === 'nand') && !fed.has(`${n.id}:q`)) { if ((n.kind === 'input' || n.kind === 'button' || n.kind === 'clock' || n.kind === 'nand') && !fed.has(`${n.id}:q`)) {

View File

@ -477,20 +477,24 @@ function boxShape(name: string, plain: ChipPins, face: ReturnType<typeof faceLay
Math.ceil(longest(left) * LABEL_CHAR + longest(right) * LABEL_CHAR + name.length * NAME_CHAR + 1.5), Math.ceil(longest(left) * LABEL_CHAR + longest(right) * LABEL_CHAR + name.length * NAME_CHAR + 1.5),
Math.ceil(face.w + 1.2), Math.ceil(face.w + 1.2),
) )
// An edge with ports starts at the top; one of single pins only is centred. // 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 place = (ps: EdgePin[], dx: number) => {
const off = ps.some(p => p.pin.bus) ? 0 : Math.floor((n - ps.length) / 2) 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 } })) return ps.map((p, i) => ({ dir: p.dir, pin: { ...p.pin, dx, dy: off + i } }))
} }
const pins = [...place(left, 0), ...place(right, w)] // 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 top = n === 1 ? -1 : -0.5
const pinBottom = n === 1 ? 1 : n - 0.5 const pinBottom = n === 1 ? 1 : n - 0.5
const faceTop = pinBottom + 0.2 const faceTop = pinBottom + 0.2
const faceLeft = (w - face.w) / 2 const faceLeft = (w - face.w) / 2
return { return {
body: { x: 0, y: top, w, h: pinBottom - top + (face.items.length ? face.h + 0.6 : 0) }, body: { x: 0, y: top, w, h: pinBottom - top + (face.items.length ? face.h + 0.6 : 0) },
inputs: pins.filter(p => p.dir === 'in').map(p => p.pin), inputs: [...onLeft, ...onRight].filter(p => p.dir === 'in').map(p => p.pin),
outputs: pins.filter(p => p.dir === 'out').map(p => p.pin), outputs: [...onRight, ...onLeft].filter(p => p.dir === 'out').map(p => p.pin),
nameY: (top + pinBottom) / 2, nameY: (top + pinBottom) / 2,
face: face.items.map(it => ({ ...it, x: it.x + faceLeft, y: it.y + faceTop })), face: face.items.map(it => ({ ...it, x: it.x + faceLeft, y: it.y + faceTop })),
} }

View File

@ -4,7 +4,7 @@
import type { Challenge } from './challenges' import type { Challenge } from './challenges'
import { inputKeys, outputKeys } from './compile' import { inputKeys, outputKeys } from './compile'
import { exampleLibrary, starterCircuit } from './examples' import { exampleLibrary, starterCircuit } from './examples'
import { chipPins, shapeOf, splitLines, type DefLookup } from './geometry' import { chipPins, linePin, shapeOf, splitLines, type DefLookup } from './geometry'
import type { CircuitNode, ComponentDef, NodeKind, Project, PuzzleSpec, Wire } from './types' import type { CircuitNode, ComponentDef, NodeKind, Project, PuzzleSpec, Wire } from './types'
export function uid(prefix = ''): string { export function uid(prefix = ''): string {
@ -468,15 +468,20 @@ export function splitPort(project: Project, def: ComponentDef, nodeId: string, p
* The line of a component's port a single wire takes when dropped on its * 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 * 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 * 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. * can feed more wires, an unused one first). Null when no line runs that way,
* and for lines going in while a cable is in the socket: the cable feeds them.
*/ */
export function lineForWire(project: Project, def: ComponentDef, nodeId: string, port: string, enters: boolean): string | null { export function lineForWire(project: Project, def: ComponentDef, nodeId: string, port: string, enters: boolean): string | null {
const get = lookup(project) const get = lookup(project)
const node = def.nodes.find(n => n.id === nodeId) const node = def.nodes.find(n => n.id === nodeId)
const child = node?.kind === 'chip' && node.chip ? get(node.chip) : undefined const child = node?.kind === 'chip' && node.chip ? get(node.chip) : undefined
if (!node || !child) return null if (!node || !child) return null
const into = new Set(def.wires.filter(w => w.to.node === nodeId).map(w => w.to.pin))
const from = new Set(def.wires.filter(w => w.from.node === nodeId).map(w => w.from.pin))
// A wire on a line the cable feeds would drive it against the cable.
if (enters && (into.has(port) || from.has(port))) return null
const lines = splitLines({ ...node, splitPorts: [port] }, chipPins(child), get).filter(l => l.enters === enters) 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)) const used = enters ? into : from
return (lines.find(l => !used.has(l.key)) ?? (enters ? undefined : lines[0]))?.key ?? null return (lines.find(l => !used.has(l.key)) ?? (enters ? undefined : lines[0]))?.key ?? null
} }
@ -496,9 +501,10 @@ export function unlinkWires(def: ComponentDef, ids: Set<string>): number {
/** /**
* Replaces a placed component with the parts inside it (the reverse of * Replaces a placed component with the parts inside it (the reverse of
* "Make component"). Its pins disappear: outside wires are joined straight * "Make component"). Its pins disappear: outside wires are joined straight
* to the parts they reached inside. Returns the ids of the new parts. * to the parts they reached inside, the lines of split ports too. Returns
* the ids of the new parts, and how many wires on lines had nowhere to go.
*/ */
export function unpackChip(project: Project, defId: string, nodeId: string): { ok: true; nodes: string[] } | { ok: false; error: string } { export function unpackChip(project: Project, defId: string, nodeId: string): { ok: true; nodes: string[]; dropped: number } | { ok: false; error: string } {
const get = lookup(project) const get = lookup(project)
const def = get(defId) const def = get(defId)
const chip = def?.nodes.find(n => n.id === nodeId) const chip = def?.nodes.find(n => n.id === nodeId)
@ -522,8 +528,21 @@ export function unpackChip(project: Project, defId: string, nodeId: string): { o
const kindOf = new Map(child.nodes.map(n => [n.id, n.kind])) const kindOf = new Map(child.nodes.map(n => [n.id, n.kind]))
const feed = new Map<string, Wire['from']>() 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) 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 => // Lines of split ports on the box, and those whose wires found a place.
kindOf.get(ref.node) === 'input' ? feed.get(ref.node) : ids.has(ref.node) ? { node: ids.get(ref.node)!, pin: ref.pin } : undefined const lines = new Map(splitLines(chip, chipPins(child), get).map(l => [l.key, l]))
const carried = new Set<string>()
const resolve = (ref: Wire['from']): Wire['from'] | undefined => {
if (kindOf.get(ref.node) === 'input') return feed.get(ref.node)
// A line of a port going in: what was wired into it on the box, if anything.
const port = kindOf.get(ref.node) === 'portin' || kindOf.get(ref.node) === 'portout'
const line = linePin(ref.node, ref.pin)
const hand = port ? feed.get(line) : undefined
if (hand) {
carried.add(line)
return hand
}
return ids.has(ref.node) ? { node: ids.get(ref.node)!, pin: ref.pin } : undefined
}
const added: Wire[] = [] const added: Wire[] = []
for (const w of child.wires) { for (const w of child.wires) {
@ -531,20 +550,25 @@ export function unpackChip(project: Project, defId: string, nodeId: string): { o
const from = resolve(w.from) const from = resolve(w.from)
if (!from) continue if (!from) continue
const wire: Wire = { id: uid('w'), from, to: { node: ids.get(w.to.node)!, pin: w.to.pin } } 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 (from.node === ids.get(w.from.node) && w.pts) wire.pts = w.pts.map(([x, y]) => [x + ox, y + oy])
if (w.color) wire.color = w.color if (w.color) wire.color = w.color
added.push(wire) added.push(wire)
} }
for (const w of def.wires) { for (const w of def.wires) {
if (w.from.node !== chip.id) continue if (w.from.node !== chip.id) continue
const inside = child.wires.find(x => x.to.node === w.from.pin) // An output pin is fed by the wire into its output part; a line coming out, by the wire into that line of its port.
const line = lines.get(w.from.pin)
const inside = line ? child.wires.find(x => x.to.node === line.port && x.to.pin === `l${line.index}`) : child.wires.find(x => x.to.node === w.from.pin)
const from = inside && resolve(inside.from) const from = inside && resolve(inside.from)
if (from) added.push({ id: uid('w'), from, to: w.to }) if (!from) continue
added.push({ id: uid('w'), from, to: w.to })
if (line) carried.add(line.key)
} }
const dropped = def.wires.filter(w => (w.to.node === chip.id && lines.has(w.to.pin) && !carried.has(w.to.pin)) || (w.from.node === chip.id && lines.has(w.from.pin) && !carried.has(w.from.pin))).length
def.nodes = def.nodes.filter(n => n !== chip) 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] def.wires = [...def.wires.filter(w => w.from.node !== chip.id && w.to.node !== chip.id), ...added]
return { ok: true, nodes: [...ids.values()] } return { ok: true, nodes: [...ids.values()], dropped }
} }
/** Points one placed component at its own copy of the definition, so edits to it don't change the others. */ /** Points one placed component at its own copy of the definition, so edits to it don't change the others. */

View File

@ -1,10 +1,11 @@
import { describe, expect, it } from 'vitest' import { describe, expect, it } from 'vitest'
import { cableFromPins, cableIntoPins } from '../app/lib/logic/cables'
import { checkCircuit, doublyFedLines } from '../app/lib/logic/check' import { checkCircuit, doublyFedLines } from '../app/lib/logic/check'
import { compile } from '../app/lib/logic/compile' import { compile } from '../app/lib/logic/compile'
import { pinKindOf, shapeOf } from '../app/lib/logic/geometry' import { pinKindOf, shapeOf } from '../app/lib/logic/geometry'
import { pinName } from '../app/lib/logic/labels' import { pinName } from '../app/lib/logic/labels'
import { createProject, lineForWire, lookup, pruneWires, splitPort } from '../app/lib/logic/ops' import { createProject, lineForWire, lookup, pruneWires, splitPort, unpackChip } from '../app/lib/logic/ops'
import { attachPanel } from '../app/lib/logic/panels' import { attachPanel, syncPanels } from '../app/lib/logic/panels'
import { toProject } from '../app/lib/logic/project' import { toProject } from '../app/lib/logic/project'
import { Simulator } from '../app/lib/logic/sim' import { Simulator } from '../app/lib/logic/sim'
import type { CircuitNode, ComponentDef, Project, Wire } from '../app/lib/logic/types' import type { CircuitNode, ComponentDef, Project, Wire } from '../app/lib/logic/types'
@ -160,7 +161,7 @@ describe('ports on a component box', () => {
// A wire into a line the cable feeds as well: both drive it, and the check says so. // A wire into a line the cable feeds as well: both drive it, and the check says so.
root(p).wires.push(w('d0', ['sb', 'q'], ['snk', 'rx.l0'])) root(p).wires.push(w('d0', ['sb', 'q'], ['snk', 'rx.l0']))
expect(doublyFedLines(root(p), node(p, 'root', 'snk'), lookup(p))).toEqual(['rx.l0']) expect(doublyFedLines(root(p), node(p, 'root', 'snk'), lookup(p))).toEqual(['rx.l0'])
expect(checkCircuit(root(p), lookup(p)).some(i => i.level === 'warn' && i.text.includes('D0'))).toBe(true) expect(checkCircuit(root(p), lookup(p)).some(i => i.level === 'error' && i.text.includes('D0'))).toBe(true)
}) })
it('passes split lines through a component that offers an inner part’s port as its own', () => { it('passes split lines through a component that offers an inner part’s port as its own', () => {
@ -249,4 +250,116 @@ describe('ports on a component box', () => {
const panel = attachPanel(p, root(p), 'snk')! const panel = attachPanel(p, root(p), 'snk')!
expect(panel.rows!.map(r => r.id)).toEqual(['h']) expect(panel.rows!.map(r => r.id)).toEqual(['h'])
}) })
it('with a cable in the socket, a dropped wire takes no line going in: the cable feeds those', () => {
const p = project()
const r = root(p)
r.wires.push(w('cable', ['src', 'tx'], ['snk', 'rx']))
// Into the sink's in port: D0 and D1 come through the cable. HPD can still be read.
expect(lineForWire(p, r, 'snk', 'rx', true)).toBeNull()
expect(lineForWire(p, r, 'snk', 'rx', false)).toBe('rx.l2')
// The source's out port: HPD comes back through the cable, D0 can still be read.
expect(lineForWire(p, r, 'src', 'tx', true)).toBeNull()
expect(lineForWire(p, r, 'src', 'tx', false)).toBe('tx.l0')
})
it('a line going in with neither a wire nor a cable is an open input', () => {
const p = project()
node(p, 'root', 'snk').splitPorts = ['rx']
root(p).wires.push(w('d0', ['sa', 'q'], ['snk', 'rx.l0']))
expect(checkCircuit(root(p), lookup(p)).some(i => i.level === 'warn' && i.text === 'Sink: D1 not connected (reads 0)')).toBe(true)
// A cable in the socket feeds D1.
root(p).wires = root(p).wires.filter(x => x.id !== 'd0')
root(p).wires.push(w('cable', ['src', 'tx'], ['snk', 'rx']))
expect(checkCircuit(root(p), lookup(p)).some(i => i.text.includes('not connected'))).toBe(false)
})
it('splitting or joining a port leaves the pins of the other side where they are', () => {
const p = project()
const get = lookup(p)
for (const design of [undefined, { w: 6, h: 3 }]) {
p.components.find(d => d.id === 'source')!.design = design
const rows = (splitPorts?: string[]) => shapeOf({ id: 'n', kind: 'chip', chip: 'source', x: 0, y: 0, splitPorts }, get).inputs.filter(i => !i.port).map(i => [i.key, i.dy])
expect(rows(['tx'])).toEqual(rows())
}
// A side of single pins only is still centred when nothing is split.
p.components.find(d => d.id === 'source')!.design = undefined
p.components.find(d => d.id === 'source')!.nodes.push({ id: 'z', kind: 'output', x: 10, y: 10, label: 'Z' }, { id: 'z2', kind: 'output', x: 10, y: 12, label: 'Z2' })
expect(shapeOf({ id: 'n', kind: 'chip', chip: 'source', x: 0, y: 0 }, get).inputs.map(i => [i.key, i.dy])).toEqual([['a', 1], ['b', 2]])
})
it('lists the pins of the usual edge first, so a wire dropped on the box takes those', () => {
const p = project()
const get = lookup(p)
const snk = shapeOf({ id: 'n', kind: 'chip', chip: 'sink', x: 0, y: 0, splitPorts: ['rx'] }, get)
expect(snk.outputs.map(o => o.key)).toEqual(['x', 'y', 'rx.l2'])
const src = shapeOf({ id: 'n', kind: 'chip', chip: 'source', x: 0, y: 0, splitPorts: ['tx'] }, get)
expect(src.inputs.map(i => i.key)).toEqual(['a', 'b', 'tx.l2'])
})
it('a cable onto split lines only takes those on their usual edge, so its end never sits in the box', () => {
const p = project()
p.connectors![0]!.lines = [{ name: 'D0' }, { name: 'D1' }, { name: 'RX0', back: true }, { name: 'RX1', back: true }]
const r = root(p)
const get = lookup(p)
node(p, 'root', 'src').splitPorts = ['tx']
node(p, 'root', 'snk').splitPorts = ['rx']
// RX0 and RX1 run back: into the source on its right edge, out of the sink on its left.
expect(cableIntoPins(r, 'src', ['tx.l2', 'tx.l3'], get).ok).toBe(false)
expect(cableFromPins(r, 'snk', ['rx.l2', 'rx.l3'], get).ok).toBe(false)
// D0 and D1 leave the source on the right and enter the sink on the left: there a cable fits.
const src = node(p, 'root', 'src')
const out = cableFromPins(r, 'src', ['tx.l0', 'tx.l1'], get)
expect(out.ok && out.bundle.x).toBe(src.x + shapeOf(src, get).body.w)
const into = cableIntoPins(r, 'snk', ['rx.l0', 'rx.l1'], get)
expect(into.ok && into.split.x).toBe(node(p, 'root', 'snk').x - 1)
})
it('unpacking joins wires on split lines to the parts inside', () => {
const p = project()
const r = root(p)
node(p, 'root', 'snk').splitPorts = ['rx']
r.nodes.push({ id: 'lamp2', kind: 'lamp', x: 50, y: 4 })
r.wires.push(w('d0', ['sa', 'q'], ['snk', 'rx.l0']), w('xl', ['snk', 'x'], ['lamp', 'a']), w('hp', ['snk', 'rx.l2'], ['lamp2', 'a']))
const res = unpackChip(p, 'root', 'snk')
expect(res.ok && res.dropped).toBe(0)
for (const [a, h] of [[0, 1], [1, 0]] as const) {
const s = run(p, { sa: !!a, sh: !!h })
expect([s.pin('lamp', 'q'), s.pin('lamp2', 'q')]).toEqual([a, h])
}
})
it('unpacking says how many wires on lines had nowhere to go', () => {
const p = project()
p.components.push({
id: 'box',
name: 'Box',
symbol: 'box',
nodes: [
{ id: 'inner', kind: 'chip', chip: 'source', x: 6, y: 0 },
{ id: 'p2', kind: 'portout', conn: 'hdmi', x: 30, y: 0 },
],
wires: [w('b2', ['inner', 'tx'], ['p2', 'bus'])],
})
// D0 of the box comes from a part inside through a cable: no single wire inside to join it to.
root(p).nodes.push({ id: 'bx', kind: 'chip', chip: 'box', x: 6, y: 20, splitPorts: ['p2'] })
root(p).wires.push(w('l0', ['bx', 'p2.l0'], ['lamp', 'a']))
const res = unpackChip(p, 'root', 'bx')
expect(res.ok && res.dropped).toBe(1)
})
it('a docked panel made before ports moved to the top loses its row for the socket and lines up again', () => {
const p = project()
const r = root(p)
r.wires = r.wires.filter(x => x.id !== 'r3')
// As docked by earlier releases: a row for H and one for the socket below it, the port at the bottom.
r.nodes.push({ id: 'pan', kind: 'panel', x: 24, y: 0, attach: 'snk', rows: [{ id: 'h', type: 'switch', dy: 0 }, { id: 'rx', type: 'switch', dy: 1 }] })
r.wires.push(w('ph', ['pan', 'h'], ['snk', 'h']))
syncPanels(p)
pruneWires(p)
const pan = node(p, 'root', 'pan')
expect(pan.rows!.map(x => x.id)).toEqual(['h'])
const h = shapeOf(node(p, 'root', 'snk'), lookup(p)).inputs.find(i => i.key === 'h')!
expect(pan.y).toBe(node(p, 'root', 'snk').y + h.dy)
})
}) })