A cables you place yourself, drawn as coloured ribbons

- Select wires (or a box of parts and wires), "Bundle into cable…" or
  Ctrl+G, then click where the cable starts and where it ends, with a
  preview; "place it for me" keeps the automatic placement.
- Up to 16 wires, a cable is a ribbon: one thin line per wire inside the
  sleeve, in that wire's colour, lit on its own.
- The sleeve starts neutral (no longer takes the first wire's colour) and
  has its own colour in the cable and bundle/split settings. Wide cables
  are clickable across their width; the width mark sits above the ribbon.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-21 10:39:54 +02:00
parent 183edc784f
commit 29c32026d7
11 changed files with 291 additions and 33 deletions

View File

@ -13,7 +13,7 @@ Nuxt 4 (client-only editor, `ssr: false`), Tailwind CSS v4, Lucide icons via `@n
- Puzzles: "Publish as puzzle" (This circuit) turns a circuit into a link `/puzzle/<id>`. Only its behaviour is published, as a truth table, or for circuits with memory as a run of input changes from power-on; the circuit stays private. Whoever opens the link gets the puzzle in their project, sees the target and the author's transistor count, and after a pass their solution goes to the server, which re-runs the checks and counts the transistors itself (with a fixed work budget) and keeps each player's best. The board shows everyone's transistor counts and your place. The puzzle of the week is generated from the ISO week, the same for everyone: three or four inputs, one or two outputs, each depending on every input. Players are anonymous ids per browser.
- 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.
- Cables: a bundle gathers 2 to 32 wires into one thick cable, a split fans it out again in the same order; one bundle can feed several splits. Select some wires and press "Bundle into cable" to have both ends placed for you (the cable takes the wires' colour); "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 (or parts and wires with a box) and press "Bundle into cable…" or Ctrl+G, then click where the cable starts and where it ends (a preview follows the mouse; Esc cancels); "place it for me" puts the ends next to the sources and targets. 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.
- 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.
- 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.
@ -49,7 +49,7 @@ All in [app/lib/logic/](app/lib/logic/), plain TypeScript with no Vue dependency
- `examples.ts` builds the example library with a small builder; `ops.ts` holds project edits (package selection, copy/paste, prune dangling wires, recursion check).
- `routing.ts` lays out all wires of a circuit (free lanes, detours, separation, crossings, and the tidy layout).
- `progress.ts` holds the campaign rules; `puzzles.ts` makes, checks and scores puzzles and generates the weekly one (shared with the server, [server/api/puzzles/](server/api/puzzles/), storage in `data/puzzles`).
- `cables.ts` bundles wires into cables and takes them apart again.
- `cables.ts` bundles wires into cables (ends where you click, or next to sources and targets), takes them apart again, and lays out the ribbon lines (`offsetPath`, `ribbon`).
- `panels.ts` docks input panels to components and keeps them in step; `labels.ts` does series names and names taken from pins.
- `wires.ts` edits wire routes (segment and corner drags, splits, branches); `project.ts` validates project data for both the browser and the server; `storage.ts` is the browser's project library.

View File

@ -2212,3 +2212,43 @@ kbd {
padding: 0;
border-bottom: 2px solid transparent;
}
/* Ribbon cable: sleeve, dark core, one thin line per wire in its own colour. */
.cable-sleeve {
fill: none;
stroke: var(--w-off);
stroke-linejoin: round;
stroke-linecap: butt;
}
.wire.on .cable-sleeve {
stroke: color-mix(in srgb, var(--w-on) 55%, var(--w-off));
}
.cable-core {
fill: none;
stroke: #10151c;
stroke-linejoin: round;
stroke-linecap: butt;
}
.lane {
--w-on: var(--on);
--w-off: #3b4554;
fill: none;
stroke: var(--w-off);
stroke-width: 1.3;
stroke-linejoin: round;
pointer-events: none;
}
.lane.on {
stroke: var(--w-on);
}
.lane.c-red { --w-on: #ff5c5c; --w-off: #6b3337; }
.lane.c-orange { --w-on: #ff9f43; --w-off: #6b4a2b; }
.lane.c-yellow { --w-on: #ffd93d; --w-off: #625a2e; }
.lane.c-blue { --w-on: #4dabff; --w-off: #2b4a6b; }
.lane.c-purple { --w-on: #b388ff; --w-off: #463768; }
.lane.c-pink { --w-on: #ff7ac6; --w-off: #673657; }

View File

@ -32,7 +32,11 @@ onMounted(() => {
<Transition name="fade">
<div v-if="ed.notice.value" class="toast" :class="ed.notice.value.kind">{{ ed.notice.value.text }}</div>
</Transition>
<div v-if="ed.placing.value" class="placing-hint">
<div v-if="ed.cabling.value" class="placing-hint">
<strong>Cable with {{ ed.cabling.value.wires.length }} wires:</strong>
{{ ed.cabling.value.start ? 'click where it ends (its split).' : 'click where it starts (its bundle).' }} <kbd>Esc</kbd> cancels.
</div>
<div v-else-if="ed.placing.value" class="placing-hint">
Click on the canvas to place. <kbd>Shift</kbd> places several, <kbd>Esc</kbd> stops.
</div>
<div v-else-if="link" class="placing-hint">

View File

@ -215,6 +215,13 @@ function pack() {
</div>
</section>
<section v-if="wires.length >= 2">
<h3>Cable</h3>
<button class="btn w-full" title="Then click where the cable starts and where it ends (Ctrl+G)" @click="ed.startCable(wires.map(w => w.id))">
<Icon name="lucide:merge" class="size-4" /> Bundle the {{ wires.length }} wires into a cable…
</button>
</section>
<section>
<h3>Arrange</h3>
<div class="arrange">

View File

@ -5,6 +5,7 @@ import type { CircuitNode, PanelRow, PinRef, Wire } from '~/lib/logic/types'
import { branchCorners, branchTo, moveCorner, moveSegment, segmentDrag, splitDrag } from '~/lib/logic/wires'
import { circuitRoutes, findCrossings } from '~/lib/logic/routing'
import { seriesLinks } from '~/lib/logic/bulk'
import { LANE, ribbon } from '~/lib/logic/cables'
import { wirePath } from '~/lib/draw'
import { pinName } from '~/lib/logic/labels'
@ -33,8 +34,15 @@ interface Route {
bits?: number
/** Where the cable's width mark goes. */
mark?: Pt
/** A cable drawn as a ribbon: one line per wire, coloured like that wire. */
lanes?: { i: number; d: string; color?: string }[]
/** Width of the cable's sleeve in pixels. */
sleeve?: number
}
/** Cables with up to this many wires show each wire as its own line. */
const RIBBON_MAX = 16
const toPath = (pts: Pt[]) => pts.map(([x, y], i) => `${i ? 'L' : 'M'}${x * G} ${y * G}`).join('')
const routes = computed<Route[]>(() => {
@ -52,6 +60,13 @@ const routes = computed<Route[]>(() => {
const route: Route = { wire, pts: r.grid, draw: r.draw, d: wirePath(r.draw, hops.get(k), style), src: r.net }
if (from?.kind === 'bundle') {
route.bits = cableBits(from)
if (route.bits <= RIBBON_MAX) {
// Each wire keeps the colour of the wire that runs into the bundle.
const feed = new Map(def.value.wires.filter(w => w.to.node === from.id).map(w => [w.to.pin, w.color]))
route.d = toPath(r.draw)
route.lanes = ribbon(r.draw, route.bits).map((lane, i) => ({ i, d: toPath(lane), color: feed.get(`b${i}`) }))
route.sleeve = route.bits * LANE * G + 3
}
// The width mark sits on the middle of the longest straight run.
let best = 0
for (let i = 0; i < r.draw.length - 1; i++) {
@ -306,6 +321,11 @@ function onPointerDown(e: PointerEvent) {
return ed.stopLinking()
}
if (ed.cabling.value) {
ed.placeCable([Math.round(w[0]), Math.round(w[1])])
return
}
const placing = ed.placing.value
if (placing) {
if (placing.chip && !ed.canPlace(placing.chip)) {
@ -692,6 +712,9 @@ function onKey(e: KeyboardEvent) {
else if (mod && key === 'd') {
e.preventDefault()
ed.duplicate()
} else if (mod && key === 'g') {
e.preventDefault()
ed.startCable()
} else if (mod && key === 'a') {
e.preventDefault()
ed.selectAll()
@ -699,6 +722,10 @@ function onKey(e: KeyboardEvent) {
e.preventDefault()
ed.deleteSelected()
} else if (e.key === 'Escape') {
if (ed.cabling.value) {
ed.cabling.value = null
return
}
if (ed.linking.value) return ed.stopLinking()
ed.placing.value = null
ed.clearSelection()
@ -810,11 +837,23 @@ const handles = computed(() =>
const gridSize = computed(() => G * view.value.zoom)
const flow = computed(() => ed.project.value.settings.flow)
/** Preview while placing a cable: its start (where you clicked or the mouse) and its end. */
const cableGhost = computed(() => {
const c = ed.cabling.value
if (!c || !cursor.value) return null
const at: Pt = [Math.round(cursor.value[0]), Math.round(cursor.value[1])]
const bits = c.wires.length
const mid = Math.floor((bits - 1) / 2)
const end = (kind: 'bundle' | 'split', p: Pt): CircuitNode => ({ id: `ghost-${kind}`, kind, bits, x: p[0], y: p[1] - mid })
if (!c.start) return { nodes: [end('bundle', at)], line: '' }
return { nodes: [end('bundle', c.start), end('split', at)], line: toPath(routeWire(c.start, at)) }
})
const cursorStyle = computed(() => {
if (drag.value?.kind === 'pan') return 'grabbing'
if (spaceDown.value) return 'grab'
if (ed.placing.value) return 'copy'
if (ed.linking.value) return 'crosshair'
if (ed.linking.value || ed.cabling.value) return 'crosshair'
return 'default'
})
@ -859,23 +898,38 @@ defineExpose({ fit, zoomAt })
{ on: srcVal(r.src) === 1, selected: wireSelected.has(r.wire.id), hover: hoverSrc === r.src, cable: !!r.bits },
]"
>
<path v-if="wireSelected.has(r.wire.id)" :d="r.d" class="wire-halo" />
<path :d="r.d" class="wire-line" />
<path v-if="flow && srcVal(r.src) === 1" :d="r.d" class="wire-flow" />
<path v-if="wireSelected.has(r.wire.id)" :d="r.d" class="wire-halo" :style="r.sleeve ? { strokeWidth: `${r.sleeve + 9}px` } : undefined" />
<template v-if="r.lanes">
<!-- Ribbon cable: a sleeve in the cable's colour, one line per wire inside -->
<path :d="r.d" class="cable-sleeve" :style="{ strokeWidth: `${r.sleeve! + 3}px` }" />
<path :d="r.d" class="cable-core" :style="{ strokeWidth: `${r.sleeve}px` }" />
<path
v-for="l in r.lanes"
:key="l.i"
:d="l.d"
class="lane"
:class="[l.color ? `c-${l.color}` : '', { on: ed.val(r.wire.from.node, `b${l.i}`) === 1 }]"
/>
</template>
<template v-else>
<path :d="r.d" class="wire-line" />
<path v-if="flow && srcVal(r.src) === 1" :d="r.d" class="wire-flow" />
</template>
<path
v-for="(p, i) in r.pts.slice(0, -1)"
:key="i"
:d="`M${p[0] * G} ${p[1] * G}L${r.pts[i + 1]![0] * G} ${r.pts[i + 1]![1] * G}`"
class="wire-hit"
:class="{ vertical: p[0] === r.pts[i + 1]![0] }"
:style="r.sleeve ? { strokeWidth: `${Math.max(10, r.sleeve + 4)}px` } : undefined"
:data-wire="r.wire.id"
:data-seg="i"
@pointerenter="hoverSrc = r.src"
@pointerleave="hoverSrc = null"
/>
<g v-if="r.bits && r.mark" class="cable-mark" :transform="`translate(${r.mark[0] * G} ${r.mark[1] * G})`">
<path d="M-4 6L4 -6" />
<text x="6" y="-6">{{ r.bits }}</text>
<path :d="r.sleeve ? `M-4 ${r.sleeve / 2 + 3}L4 ${-r.sleeve / 2 - 3}` : 'M-4 6L4 -6'" />
<text x="6" :y="r.sleeve ? -r.sleeve / 2 - 4 : -6">{{ r.bits }}</text>
</g>
</g>
<g v-for="(j, i) in junctions" :key="`j${i}`" class="wire" :class="[j.color ? `c-${j.color}` : '', { on: srcVal(j.src) === 1 }]">
@ -916,6 +970,10 @@ defineExpose({ fit, zoomAt })
<text :x="b.x * G" :y="b.y * G + 3.5" text-anchor="middle">{{ b.n }}</text>
</g>
<EditorNodeView v-if="ghost" :node="ghost" :shape="ed.shape(ghost)" :selected="false" ghost />
<template v-if="cableGhost">
<path v-if="cableGhost.line" :d="cableGhost.line" class="temp-wire" />
<EditorNodeView v-for="g in cableGhost.nodes" :key="g.id" :node="g" :shape="ed.shape(g)" :selected="false" ghost />
</template>
<rect v-if="boxRect" v-bind="boxRect" class="box-select" />
</g>
</svg>

View File

@ -6,7 +6,7 @@ import { cableBits, chipPins, MAX_BITS, rowLabel } from '~/lib/logic/geometry'
import { SINK_KINDS, SOURCE_KINDS } from '~/lib/logic/ops'
import { KIND_NAMES } from '~/lib/logic/progress'
import { baseOf, gateFamily, inputCount, MAX_GATE_INPUTS } from '~/lib/logic/wide'
import { LAMP_COLORS, type CircuitNode, type NodeKind, type PanelControl, type PanelRow } from '~/lib/logic/types'
import { LAMP_COLORS, WIRE_COLORS, type CircuitNode, type NodeKind, type PanelControl, type PanelRow } from '~/lib/logic/types'
const props = defineProps<{ node: CircuitNode }>()
const ed = useEditor()
@ -146,6 +146,8 @@ const cableBundle = computed(() => {
return feed ? cableOf(ed.def.value, feed) : undefined
})
const sleeveColor = computed(() => (cableBundle.value ? ed.def.value.wires.find(w => w.from.node === cableBundle.value!.id)?.color : undefined))
const chipInputs = computed(() => (chipDef.value ? chipPins(chipDef.value).inputs.length : 0))
const chipOutputs = computed(() => (chipDef.value ? chipPins(chipDef.value).outputs.length : 0))
const hasPanel = computed(() => ed.def.value.nodes.some(x => x.kind === 'panel' && x.attach === n.value.id))
@ -317,6 +319,21 @@ function setRowHz(row: PanelRow, e: Event) {
<span>Wires in the cable</span>
<input type="number" min="2" :max="MAX_BITS" step="1" :value="cableBits(n)" @change="ed.setBits(n, Number(($event.target as HTMLInputElement).value))" />
</label>
<div v-if="cableBundle" class="field">
<span>Sleeve colour (the wires inside keep theirs)</span>
<div class="swatches">
<button class="swatch none" :class="{ active: !sleeveColor }" title="Default" @click="ed.setCableColor(cableBundle.id, undefined)" />
<button
v-for="c in WIRE_COLORS"
:key="c"
class="swatch"
:class="[`c-${c}`, { active: sleeveColor === c }]"
:title="c"
@click="ed.setCableColor(cableBundle.id, c)"
/>
</div>
</div>
<p class="hint">Drag the bundle and the split to decide where the cable starts and ends.</p>
<button v-if="cableBundle" class="btn mb-2 w-full" title="Take the cable apart again into single wires" @click="ed.removeCable(cableBundle.id)">
<Icon name="lucide:split" class="size-4" /> Remove cable
</button>

View File

@ -9,13 +9,16 @@ const wireColor = computed(() => {
return colors.size === 1 ? [...colors][0] : null
})
const cable = computed(() => (wires.value.length === 1 ? cableOf(ed.def.value, wires.value[0]!) : undefined))
/** The selected wire is the cable itself (it leaves a bundle). */
const isCable = computed(() => wires.value.length === 1 && cable.value?.id === wires.value[0]!.from.node)
</script>
<template>
<section>
<h3>{{ wires.length === 1 ? 'Wire' : `${wires.length} wires` }}</h3>
<h3>{{ isCable ? 'Cable' : wires.length === 1 ? 'Wire' : `${wires.length} wires` }}</h3>
<p v-if="isCable" class="hint">The colour is the cable's sleeve; each wire inside keeps its own colour. Drag its bundle and split to move where it starts and ends.</p>
<div class="field">
<span>Colour</span>
<span>{{ isCable ? 'Sleeve colour' : 'Colour' }}</span>
<div class="swatches">
<button class="swatch none" :class="{ active: wireColor === '' }" title="Default" @click="ed.setWireColor(undefined)" />
<button
@ -32,14 +35,14 @@ const cable = computed(() => (wires.value.length === 1 ? cableOf(ed.def.value, w
<button v-if="wires.length === 1" class="btn" @click="ed.selectNet(wires[0]!.id)"><Icon name="lucide:git-fork" class="size-4" /> Whole signal</button>
<button class="btn" :disabled="!wires.some(w => w.pts)" @click="ed.autoRoute()"><Icon name="lucide:wand-sparkles" class="size-4" /> Auto route</button>
</div>
<button
v-if="wires.length >= 2"
class="btn mt-2 w-full"
title="Replace these wires with one cable: a bundle after their sources, a split before their targets"
@click="ed.bundleSelected()"
>
<Icon name="lucide:merge" class="size-4" /> Bundle into cable
</button>
<template v-if="wires.length >= 2">
<button class="btn btn-primary mt-2 w-full" title="Then click where the cable starts and where it ends (Ctrl+G)" @click="ed.startCable()">
<Icon name="lucide:merge" class="size-4" /> Bundle into cable…
</button>
<button class="btn btn-ghost mt-1 w-full" title="Start just after the sources, end just before the targets" @click="ed.bundleSelected()">
Bundle, place it for me
</button>
</template>
<button v-if="cable" class="btn mt-2 w-full" title="Take the cable apart again into single wires" @click="ed.removeCable(cable.id)">
<Icon name="lucide:split" class="size-4" /> Remove cable
</button>

View File

@ -1024,8 +1024,39 @@ function create() {
}
// ── Cables ────────────────────────────────────────────────────────
function bundleSelected() {
const res = bundleWires(def.value, wireSel.value, getDef.value)
/** Bundling with a chosen route: the next click places the start of the cable, the one after its end. */
const cabling = ref<{ wires: string[]; start?: Pt } | null>(null)
function startCable(wires = wireSel.value) {
if (wires.length < 2) return notify('Select at least two wires to bundle (Shift + click or drag a box)', 'error')
placing.value = null
linking.value = null
cabling.value = { wires: [...wires] }
}
function placeCable(at: Pt) {
const c = cabling.value
if (!c) return
if (!c.start) {
c.start = at
return
}
cabling.value = null
bundleSelected(c.wires, { start: c.start, end: at })
}
/** Colour of a cable's sleeve (every cable leaving that bundle); undefined for the default. */
function setCableColor(bundleId: string, color: WireColor | undefined) {
for (const w of def.value.wires) {
if (w.from.node !== bundleId) continue
if (color) w.color = color
else delete w.color
}
commit(false)
}
function bundleSelected(wires = wireSel.value, at?: { start: Pt; end: Pt }) {
const res = bundleWires(def.value, wires, getDef.value, at)
if (!res.ok) return notify(res.error, 'error')
selection.value = [res.bundle.id, res.split.id]
wireSel.value = []
@ -1688,6 +1719,10 @@ function create() {
publishPuzzle,
isBus,
bundleSelected,
cabling,
startCable,
placeCable,
setCableColor,
removeCable,
setBits,
swap,

View File

@ -2,7 +2,7 @@
// one cable runs to a split part (or several), which fans them out again.
// Wire i of the cable is input i of the bundle and output i of the split.
import { cableBits, MAX_BITS, pinPos, shapeOf, type DefLookup } from './geometry'
import { cableBits, MAX_BITS, pinPos, shapeOf, type DefLookup, type Pt } from './geometry'
import { uid } from './ops'
import type { CircuitNode, ComponentDef, Wire } from './types'
@ -24,11 +24,17 @@ export function cableOf(def: ComponentDef, wire: Wire): CircuitNode | undefined
}
/**
* Replaces the given wires with a cable: a bundle just after their sources,
* a split just before their targets, wires in the order of the targets top
* to bottom. Returns the new parts, or a reason it can't.
* Replaces the given wires with a cable, wires in the order of the targets
* top to bottom. The cable runs from `at.start` to `at.end` (where the
* bundle and the split are centred) when given, else from just after the
* sources to just before the targets. Returns the new parts, or a reason it can't.
*/
export function bundleWires(def: ComponentDef, wireIds: string[], get: DefLookup): { ok: true; bundle: CircuitNode; split: CircuitNode } | { ok: false; error: string } {
export function bundleWires(
def: ComponentDef,
wireIds: string[],
get: DefLookup,
at?: { start: Pt; end: Pt },
): { ok: true; bundle: CircuitNode; split: CircuitNode } | { ok: false; error: string } {
const nodes = new Map(def.nodes.map(n => [n.id, n]))
const ids = new Set(wireIds)
const wires = def.wires.filter(w => ids.has(w.id))
@ -50,9 +56,12 @@ export function bundleWires(def: ComponentDef, wireIds: string[], get: DefLookup
const left = Math.min(...ends.map(e => e.b.x))
const bx = right + 2
const sx = Math.max(bx + 4, left - 3)
const color = wires.find(w => w.color)?.color
const bundle: CircuitNode = { id: uid('n'), kind: 'bundle', bits: n, x: bx, y: mean(ends.map(e => e.a.y)) - mid }
const split: CircuitNode = { id: uid('n'), kind: 'split', bits: n, x: sx, y: mean(ends.map(e => e.b.y)) - mid }
const bundle: CircuitNode = at
? { id: uid('n'), kind: 'bundle', bits: n, x: Math.round(at.start[0]), y: Math.round(at.start[1]) - mid }
: { id: uid('n'), kind: 'bundle', bits: n, x: bx, y: mean(ends.map(e => e.a.y)) - mid }
const split: CircuitNode = at
? { id: uid('n'), kind: 'split', bits: n, x: Math.round(at.end[0]), y: Math.round(at.end[1]) - mid }
: { id: uid('n'), kind: 'split', bits: n, x: sx, y: mean(ends.map(e => e.b.y)) - mid }
def.nodes.push(bundle, split)
def.wires = def.wires.filter(w => !ids.has(w.id))
ends.forEach((e, i) => {
@ -60,7 +69,8 @@ export function bundleWires(def: ComponentDef, wireIds: string[], get: DefLookup
def.wires.push({ id: uid('w'), from: e.w.from, to: { node: bundle.id, pin }, ...(e.w.color ? { color: e.w.color } : {}) })
def.wires.push({ id: uid('w'), from: { node: split.id, pin }, to: e.w.to, ...(e.w.color ? { color: e.w.color } : {}) })
})
def.wires.push({ id: uid('w'), from: { node: bundle.id, pin: 'q' }, to: { node: split.id, pin: 'a' }, ...(color ? { color } : {}) })
// The sleeve starts neutral: the wires inside show their own colours.
def.wires.push({ id: uid('w'), from: { node: bundle.id, pin: 'q' }, to: { node: split.id, pin: 'a' } })
return { ok: true, bundle, split }
}
@ -89,3 +99,31 @@ export function dissolveCable(def: ComponentDef, bundleId: string): number {
def.wires = [...def.wires.filter(w => !gone.has(w.from.node) && !gone.has(w.to.node)), ...added]
return added.length
}
/**
* The same path moved sideways by `d` (grid units): to the right of the
* direction of travel for positive `d`, corners kept square. Used to draw
* each wire of a cable as its own line inside the sleeve.
*/
export function offsetPath(pts: Pt[], d: number): Pt[] {
const normals: Pt[] = []
for (let i = 0; i < pts.length - 1; i++) {
const dx = Math.sign(pts[i + 1]![0] - pts[i]![0])
const dy = Math.sign(pts[i + 1]![1] - pts[i]![1])
normals.push([-dy, dx])
}
return pts.map((p, i) => {
const a = normals[i - 1]
const b = normals[i]
const n: Pt = !a ? b! : !b ? a : a[0] === b[0] && a[1] === b[1] ? a : a[0] === -b[0] && a[1] === -b[1] ? a : [a[0] + b[0], a[1] + b[1]]
return [p[0] + d * n[0], p[1] + d * n[1]]
})
}
/** Space between the lines of a ribbon cable, in grid units. */
export const LANE = 0.14
/** One line per wire of a cable, wire 0 on top (on the left of the direction of travel). */
export function ribbon(pts: Pt[], bits: number): Pt[][] {
return Array.from({ length: bits }, (_, i) => offsetPath(pts, (i - (bits - 1) / 2) * LANE))
}

View File

@ -0,0 +1,55 @@
import { describe, expect, it } from 'vitest'
import { bundleWires, offsetPath, ribbon } from '../app/lib/logic/cables'
import { compile } from '../app/lib/logic/compile'
import { lookup, createProject } from '../app/lib/logic/ops'
import { Simulator } from '../app/lib/logic/sim'
import type { ComponentDef } from '../app/lib/logic/types'
describe('ribbon cables', () => {
it('moves a square path sideways and keeps the corners square', () => {
// Right, then down, then right again.
const p = offsetPath([[0, 0], [4, 0], [4, 3], [8, 3]], 0.5)
expect(p).toEqual([[0, 0.5], [3.5, 0.5], [3.5, 3.5], [8, 3.5]])
})
it('draws wire 0 on top when the cable runs to the right', () => {
const lanes = ribbon([[0, 0], [10, 0]], 4)
expect(lanes.map(l => l[0]![1])).toEqual([...lanes.map(l => l[0]![1])].sort((a, b) => a - b))
expect(lanes[0]![0]![1]).toBeLessThan(0)
})
})
describe('placing a cable', () => {
const def = (): ComponentDef => ({
id: 'c',
name: 'C',
symbol: 'box',
nodes: [
...[0, 1, 2].map(i => ({ id: `s${i}`, kind: 'input' as const, x: 0, y: i * 2, on: i !== 1 })),
...[0, 1, 2].map(i => ({ id: `l${i}`, kind: 'lamp' as const, x: 30, y: 10 + i * 2 })),
],
wires: [0, 1, 2].map(i => ({ id: `w${i}`, from: { node: `s${i}`, pin: 'q' }, to: { node: `l${i}`, pin: 'a' }, ...(i === 0 ? { color: 'red' as const } : {}) })),
})
it('puts the start and end where you click, centred on the cable', () => {
const d = def()
const res = bundleWires(d, ['w0', 'w1', 'w2'], lookup(createProject({ examples: false })), { start: [8, 4], end: [22, 12] })
if (!res.ok) throw new Error(res.error)
expect([res.bundle.x, res.bundle.y]).toEqual([8, 3])
expect([res.split.x, res.split.y]).toEqual([22, 11])
// Each wire keeps its colour on both sides of the cable; the sleeve starts neutral.
expect(d.wires.filter(w => w.color === 'red')).toHaveLength(2)
expect(d.wires.find(w => w.from.node === res.bundle.id)!.color).toBeUndefined()
})
it('still carries every signal to its lamp', () => {
const p = createProject({ examples: false })
const d = def()
p.components.push(d)
bundleWires(d, ['w0', 'w1', 'w2'], lookup(p), { start: [8, 4], end: [22, 12] })
const sim = new Simulator(compile(lookup(p), 'c'))
for (const n of d.nodes) if (n.kind === 'input') sim.setSource(n.id, !!n.on)
sim.run()
expect([0, 1, 2].map(i => sim.pin(`l${i}`, 'a'))).toEqual([1, 0, 1])
})
})

View File

@ -47,8 +47,9 @@ describe('cables', () => {
expect(def.wires.filter(w => w.from.node === res.bundle.id)).toHaveLength(1)
expect(def.wires).toHaveLength(9)
expect(behaviour(p, def)).toEqual(before)
// The cable takes the colour of the wires.
expect(def.wires.find(w => w.from.node === res.bundle.id)!.color).toBe('blue')
// The sleeve starts neutral; the coloured wire keeps its colour into the bundle and out of the split.
expect(def.wires.find(w => w.from.node === res.bundle.id)!.color).toBeUndefined()
expect(def.wires.filter(w => w.color === 'blue').map(w => (w.to.node === res.bundle.id ? 'in' : 'out'))).toEqual(['in', 'out'])
// Both ends sit between sources and targets.
expect(res.bundle.x).toBeGreaterThan(2)
expect(res.split.x).toBeLessThan(30)