A transistor counts and records, cables, pixels and screens
- Every component shows its transistors (CMOS, 4 per NAND, at every depth) in the palette, its settings and the stats. Challenges keep the fewest transistors of a passing solution and announce new records. - Cables: bundle and split parts carry 2 to 32 wires as one thick cable with a width mark; "Bundle into cable" builds one from selected wires, "Remove cable" takes it apart. Cable ends only join cable ends. - Pixel part; pixels inside a component show on its box as one screen without gaps. New examples: Screen 4x4 and Demo: Screen. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
861b161c8b
commit
9754ecc0b4
|
|
@ -6,7 +6,10 @@ Nuxt 4 (client-only editor, `ssr: false`), Tailwind CSS v4, Lucide icons via `@n
|
||||||
|
|
||||||
## What it does
|
## What it does
|
||||||
|
|
||||||
- Parts: NAND, input switch, output pin, lamp, push button, clock, constant 1, ground, hex display, input panel, note.
|
- Parts: NAND, input switch, output pin, lamp, push button, clock, constant 1, ground, hex display, pixel, cable bundle and split, input panel, note.
|
||||||
|
- 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.
|
||||||
|
- 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.
|
- 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.
|
||||||
- Every circuit is a component. Its input and output nodes become its pins, ordered top to bottom. Double-click a component to open it.
|
- Every circuit is a component. Its input and output nodes become its pins, ordered top to bottom. Double-click a component to open it.
|
||||||
|
|
@ -23,7 +26,7 @@ Nuxt 4 (client-only editor, `ssr: false`), Tailwind CSS v4, Lucide icons via `@n
|
||||||
- Share links: `/p/<id>`. The creator's changes save to the link automatically. Anyone else who opens it gets their own copy; their first edit detaches it from the link.
|
- Share links: `/p/<id>`. The creator's changes save to the link automatically. Anyone else who opens it gets their own copy; their first edit detaches it from the link.
|
||||||
- Truth table, NAND count, gate delay, and loop detection for the open circuit. The table can go full screen, be downloaded as CSV or copied as a Markdown table; the row the switches are set to is highlighted.
|
- Truth table, NAND count, gate delay, and loop detection for the open circuit. The table can go full screen, be downloaded as CSV or copied as a Markdown table; the row the switches are set to is highlighted.
|
||||||
- 17 challenges (NOT up to a D flip-flop) checked against a truth table or a step sequence.
|
- 17 challenges (NOT up to a D flip-flop) checked against a truth table or a step sequence.
|
||||||
- Example library, all built from NAND: NOT, AND, OR, NOR, XOR, XNOR, Mux, Half/Full Adder, SR Latch, D Latch, D Flip-Flop, Register 4, Increment 4, Adder 4, Counter 4, and a counter demo with a hex display.
|
- Example library, all built from NAND: NOT, AND, OR, NOR, XOR, XNOR, Mux, Half/Full Adder, SR Latch, D Latch, D Flip-Flop, Register 4, Increment 4, Adder 4, Counter 4, a counter demo with a hex display, and a 4×4 pixel screen with a demo.
|
||||||
|
|
||||||
## How the simulation works
|
## How the simulation works
|
||||||
|
|
||||||
|
|
@ -35,6 +38,7 @@ All in [app/lib/logic/](app/lib/logic/), plain TypeScript with no Vue dependency
|
||||||
- `analyze.ts` builds truth tables, counts NANDs, computes the longest gate path, and runs challenge tests.
|
- `analyze.ts` builds truth tables, counts NANDs, computes the longest gate path, and runs challenge tests.
|
||||||
- `examples.ts` builds the example library with a small builder; `ops.ts` holds project edits (package selection, copy/paste, prune dangling wires, recursion check).
|
- `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).
|
- `routing.ts` lays out all wires of a circuit (free lanes, detours, separation, crossings, and the tidy layout).
|
||||||
|
- `cables.ts` bundles wires into cables and takes them apart again.
|
||||||
- `panels.ts` docks input panels to components and keeps them in step; `labels.ts` does series names and names taken from pins.
|
- `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.
|
- `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.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -369,6 +369,23 @@ kbd {
|
||||||
color: var(--accent);
|
color: var(--accent);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Transistor count next to a component in the palette. */
|
||||||
|
.tcount {
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
font-size: 10px;
|
||||||
|
color: var(--muted);
|
||||||
|
opacity: 0.8;
|
||||||
|
}
|
||||||
|
|
||||||
|
.comp-row:hover .tcount {
|
||||||
|
visibility: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.challenges .best,
|
||||||
|
.challenge .best {
|
||||||
|
color: var(--on);
|
||||||
|
}
|
||||||
|
|
||||||
.nand-badge {
|
.nand-badge {
|
||||||
display: inline-grid;
|
display: inline-grid;
|
||||||
place-items: center;
|
place-items: center;
|
||||||
|
|
@ -731,6 +748,79 @@ kbd {
|
||||||
stroke-width: 3;
|
stroke-width: 3;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* A cable: several wires in one thick sleeve. */
|
||||||
|
.wire.cable .wire-line {
|
||||||
|
stroke-width: 6;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wire.cable.hover .wire-line {
|
||||||
|
stroke-width: 7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wire.cable .wire-halo {
|
||||||
|
stroke-width: 13;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cable-mark {
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cable-mark path {
|
||||||
|
stroke: var(--text);
|
||||||
|
stroke-width: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cable-mark text {
|
||||||
|
fill: var(--text);
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
font-size: 9px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Bundle and split: the ends of a cable. */
|
||||||
|
.node .body.cable-end {
|
||||||
|
fill: #2a3240;
|
||||||
|
stroke: #7d8aa0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.node .cable-fan {
|
||||||
|
fill: none;
|
||||||
|
stroke: #7d8aa0;
|
||||||
|
stroke-width: 1.2;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Pixel and pixel screens. */
|
||||||
|
.node .pixel {
|
||||||
|
fill: #141a22;
|
||||||
|
stroke: #303a48;
|
||||||
|
stroke-width: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.node .pixel.on {
|
||||||
|
fill: var(--px, #e8f0f8);
|
||||||
|
stroke: var(--px, #e8f0f8);
|
||||||
|
}
|
||||||
|
|
||||||
|
.screen-bg {
|
||||||
|
fill: #07090c;
|
||||||
|
stroke: #303a48;
|
||||||
|
stroke-width: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.screen-px {
|
||||||
|
fill: #11161d;
|
||||||
|
}
|
||||||
|
|
||||||
|
.screen-px.on {
|
||||||
|
fill: var(--px, #e8f0f8);
|
||||||
|
}
|
||||||
|
|
||||||
|
.px-yellow { --px: #ffd34d; }
|
||||||
|
.px-red { --px: #ff5a4f; }
|
||||||
|
.px-green { --px: #3ddc84; }
|
||||||
|
.px-blue { --px: #4dabff; }
|
||||||
|
.px-white { --px: #e8f0f8; }
|
||||||
|
|
||||||
.wire-halo {
|
.wire-halo {
|
||||||
fill: none;
|
fill: none;
|
||||||
stroke: var(--accent);
|
stroke: var(--accent);
|
||||||
|
|
@ -1609,3 +1699,16 @@ kbd {
|
||||||
.panel-rows input.hz {
|
.panel-rows input.hz {
|
||||||
flex: 0 0 56px;
|
flex: 0 0 56px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.challenge .score {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
margin-top: 8px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.challenge .score strong {
|
||||||
|
color: var(--on);
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { GRID as G, pinPos, routeWire, type Pt, type Shape } from '~/lib/logic/geometry'
|
import { cableKeys } from '~/lib/logic/compile'
|
||||||
|
import { cableBits, GRID as G, pinPos, routeWire, type Pt, type Shape } from '~/lib/logic/geometry'
|
||||||
import type { CircuitNode, PanelRow, PinRef, Wire } from '~/lib/logic/types'
|
import type { CircuitNode, PanelRow, PinRef, Wire } from '~/lib/logic/types'
|
||||||
import { branchCorners, branchTo, moveCorner, moveSegment, segmentDrag, splitDrag } from '~/lib/logic/wires'
|
import { branchCorners, branchTo, moveCorner, moveSegment, segmentDrag, splitDrag } from '~/lib/logic/wires'
|
||||||
import { circuitRoutes, findCrossings } from '~/lib/logic/routing'
|
import { circuitRoutes, findCrossings } from '~/lib/logic/routing'
|
||||||
|
|
@ -26,6 +27,10 @@ interface Route {
|
||||||
draw: Pt[]
|
draw: Pt[]
|
||||||
d: string
|
d: string
|
||||||
src: string
|
src: string
|
||||||
|
/** Wires in it when this is a cable (it leaves a bundle). */
|
||||||
|
bits?: number
|
||||||
|
/** Where the cable's width mark goes. */
|
||||||
|
mark?: Pt
|
||||||
}
|
}
|
||||||
|
|
||||||
const toPath = (pts: Pt[]) => pts.map(([x, y], i) => `${i ? 'L' : 'M'}${x * G} ${y * G}`).join('')
|
const toPath = (pts: Pt[]) => pts.map(([x, y], i) => `${i ? 'L' : 'M'}${x * G} ${y * G}`).join('')
|
||||||
|
|
@ -39,7 +44,26 @@ const routes = computed<Route[]>(() => {
|
||||||
}
|
}
|
||||||
const style = ed.project.value.settings.crossing ?? 'bow'
|
const style = ed.project.value.settings.crossing ?? 'bow'
|
||||||
const byId = new Map(def.value.wires.map(w => [w.id, w]))
|
const byId = new Map(def.value.wires.map(w => [w.id, w]))
|
||||||
return routed.map((r, k) => ({ wire: byId.get(r.id)!, pts: r.grid, draw: r.draw, d: wirePath(r.draw, hops.get(k), style), src: r.net }))
|
return routed.map((r, k) => {
|
||||||
|
const wire = byId.get(r.id)!
|
||||||
|
const from = nodeMap.value.get(wire.from.node)
|
||||||
|
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)
|
||||||
|
// 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++) {
|
||||||
|
const [ax, ay] = r.draw[i]!
|
||||||
|
const [bx, by] = r.draw[i + 1]!
|
||||||
|
const len = Math.abs(bx - ax) + Math.abs(by - ay)
|
||||||
|
if (len > best) {
|
||||||
|
best = len
|
||||||
|
route.mark = [(ax + bx) / 2, (ay + by) / 2]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return route
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
const routeOf = (wire: Wire) => routes.value.find(r => r.wire === wire)
|
const routeOf = (wire: Wire) => routes.value.find(r => r.wire === wire)
|
||||||
|
|
@ -82,6 +106,9 @@ const junctions = computed(() => {
|
||||||
|
|
||||||
const srcVal = (src: string) => {
|
const srcVal = (src: string) => {
|
||||||
const [node, pin] = src.split(':')
|
const [node, pin] = src.split(':')
|
||||||
|
const n = nodeMap.value.get(node!)
|
||||||
|
// A cable is lit while any of its wires carries a 1.
|
||||||
|
if (n?.kind === 'bundle') return cableKeys(n).some(k => ed.val(n.id, k) === 1) ? 1 : 0
|
||||||
return ed.val(node!, pin!)
|
return ed.val(node!, pin!)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -236,7 +263,7 @@ function onPointerDown(e: PointerEvent) {
|
||||||
const end = link?.queue[link.at]
|
const end = link?.queue[link.at]
|
||||||
if (end) {
|
if (end) {
|
||||||
// Connecting: a click on a pin or a part wires the current pin there.
|
// Connecting: a click on a pin or a part wires the current pin there.
|
||||||
const target = targetAt(w, end.dir === 'out' ? 'in' : 'out')
|
const target = targetAt(w, end.dir === 'out' ? 'in' : 'out', ed.isBus(end.node, end.pin, end.dir))
|
||||||
if (target) return ed.linkTo(target)
|
if (target) return ed.linkTo(target)
|
||||||
const pinEl = (e.target as Element).closest('[data-pin]')
|
const pinEl = (e.target as Element).closest('[data-pin]')
|
||||||
if (pinEl && link.queue.length === 1) {
|
if (pinEl && link.queue.length === 1) {
|
||||||
|
|
@ -462,12 +489,13 @@ function nodeAt(at: Pt): CircuitNode | undefined {
|
||||||
* else, over a part, that part's first free pin (or its nearest one when
|
* else, over a part, that part's first free pin (or its nearest one when
|
||||||
* all are taken). So dropping a wire anywhere on a component works.
|
* all are taken). So dropping a wire anywhere on a component works.
|
||||||
*/
|
*/
|
||||||
function targetAt(at: Pt, dir: 'in' | 'out'): PinRef | null {
|
function targetAt(at: Pt, dir: 'in' | 'out', bus = false): PinRef | null {
|
||||||
let best: PinRef | null = null
|
let best: PinRef | null = null
|
||||||
let bestD = 1.1 * 1.1
|
let bestD = 1.1 * 1.1
|
||||||
for (const n of def.value.nodes) {
|
for (const n of def.value.nodes) {
|
||||||
const s = shapes.value.get(n.id)!
|
const s = shapes.value.get(n.id)!
|
||||||
for (const p of dir === 'in' ? s.inputs : s.outputs) {
|
for (const p of dir === 'in' ? s.inputs : s.outputs) {
|
||||||
|
if (!!p.bus !== bus) continue
|
||||||
const dx = n.x + p.dx - at[0]
|
const dx = n.x + p.dx - at[0]
|
||||||
const dy = n.y + p.dy - at[1]
|
const dy = n.y + p.dy - at[1]
|
||||||
const dd = dx * dx + dy * dy
|
const dd = dx * dx + dy * dy
|
||||||
|
|
@ -480,7 +508,7 @@ function targetAt(at: Pt, dir: 'in' | 'out'): PinRef | null {
|
||||||
if (best) return best
|
if (best) return best
|
||||||
const n = nodeAt(at)
|
const n = nodeAt(at)
|
||||||
if (!n) return null
|
if (!n) return null
|
||||||
const pins = dir === 'in' ? shapes.value.get(n.id)!.inputs : shapes.value.get(n.id)!.outputs
|
const pins = (dir === 'in' ? shapes.value.get(n.id)!.inputs : shapes.value.get(n.id)!.outputs).filter(p => !!p.bus === bus)
|
||||||
if (!pins.length) return null
|
if (!pins.length) return null
|
||||||
const taken = linked.value[dir]
|
const taken = linked.value[dir]
|
||||||
const free = pins.find(p => !taken.has(`${n.id}:${p.key}`))
|
const free = pins.find(p => !taken.has(`${n.id}:${p.key}`))
|
||||||
|
|
@ -508,7 +536,7 @@ function onPointerUp() {
|
||||||
ed.linking.value = { queue: [{ ...here, dir: d.dir, label: '' }], at: 0 }
|
ed.linking.value = { queue: [{ ...here, dir: d.dir, label: '' }], at: 0 }
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
const target = targetAt(d.cur, d.dir === 'out' ? 'in' : 'out')
|
const target = targetAt(d.cur, d.dir === 'out' ? 'in' : 'out', ed.isBus(d.node, d.pin, d.dir))
|
||||||
if (!target) break
|
if (!target) break
|
||||||
if (d.dir === 'in') {
|
if (d.dir === 'in') {
|
||||||
ed.connect(target, here)
|
ed.connect(target, here)
|
||||||
|
|
@ -547,7 +575,7 @@ function onWheel(e: WheelEvent) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Keyboard ────────────────────────────────────────────────────────
|
// ── Keyboard ────────────────────────────────────────────────────────
|
||||||
const QUICK: Record<string, CircuitNode['kind']> = { n: 'nand', i: 'input', o: 'output', l: 'lamp', c: 'clock', b: 'button', h: 'hex', t: 'note', p: 'panel' }
|
const QUICK: Record<string, CircuitNode['kind']> = { n: 'nand', i: 'input', o: 'output', l: 'lamp', c: 'clock', b: 'button', h: 'hex', t: 'note', p: 'panel', x: 'pixel' }
|
||||||
const ARROWS: Record<string, Pt> = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }
|
const ARROWS: Record<string, Pt> = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }
|
||||||
|
|
||||||
/** Arrow keys: move the selected parts and wires one grid step (four with Shift). */
|
/** Arrow keys: move the selected parts and wires one grid step (four with Shift). */
|
||||||
|
|
@ -655,7 +683,7 @@ 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)
|
const target = targetAt(d.cur, want, ed.isBus(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])]
|
||||||
if (target) {
|
if (target) {
|
||||||
const tn = nodeMap.value.get(target.node)!
|
const tn = nodeMap.value.get(target.node)!
|
||||||
|
|
@ -674,11 +702,13 @@ const targets = computed(() => {
|
||||||
const d = pending.value
|
const d = pending.value
|
||||||
if (!d) return []
|
if (!d) return []
|
||||||
const want = d.dir === 'out' ? 'in' : 'out'
|
const want = d.dir === 'out' ? 'in' : 'out'
|
||||||
|
const bus = ed.isBus(d.node, d.pin, d.dir)
|
||||||
const taken = linked.value[want]
|
const taken = linked.value[want]
|
||||||
const out: { x: number; y: number; free: boolean }[] = []
|
const out: { x: number; y: number; free: boolean }[] = []
|
||||||
for (const n of def.value.nodes) {
|
for (const n of def.value.nodes) {
|
||||||
const s = shapes.value.get(n.id)!
|
const s = shapes.value.get(n.id)!
|
||||||
for (const p of want === 'in' ? s.inputs : s.outputs) {
|
for (const p of want === 'in' ? s.inputs : s.outputs) {
|
||||||
|
if (!!p.bus !== bus) continue
|
||||||
// An output can always take one more wire; an input only has room for one.
|
// An output can always take one more wire; an input only has room for one.
|
||||||
out.push({ x: n.x + p.dx, y: n.y + p.dy, free: want === 'out' || !taken.has(`${n.id}:${p.key}`) })
|
out.push({ x: n.x + p.dx, y: n.y + p.dy, free: want === 'out' || !taken.has(`${n.id}:${p.key}`) })
|
||||||
}
|
}
|
||||||
|
|
@ -764,7 +794,7 @@ defineExpose({ fit, zoomAt })
|
||||||
class="wire"
|
class="wire"
|
||||||
:class="[
|
:class="[
|
||||||
r.wire.color ? `c-${r.wire.color}` : '',
|
r.wire.color ? `c-${r.wire.color}` : '',
|
||||||
{ on: srcVal(r.src) === 1, selected: wireSelected.has(r.wire.id), hover: hoverSrc === r.src },
|
{ 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 v-if="wireSelected.has(r.wire.id)" :d="r.d" class="wire-halo" />
|
||||||
|
|
@ -781,6 +811,10 @@ defineExpose({ fit, zoomAt })
|
||||||
@pointerenter="hoverSrc = r.src"
|
@pointerenter="hoverSrc = r.src"
|
||||||
@pointerleave="hoverSrc = null"
|
@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>
|
||||||
|
</g>
|
||||||
</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 }]">
|
<g v-for="(j, i) in junctions" :key="`j${i}`" class="wire" :class="[j.color ? `c-${j.color}` : '', { on: srcVal(j.src) === 1 }]">
|
||||||
<circle :cx="j.x * G" :cy="j.y * G" r="3.2" class="junction" :data-junction="j.src" />
|
<circle :cx="j.x * G" :cy="j.y * G" r="3.2" class="junction" :data-junction="j.src" />
|
||||||
|
|
|
||||||
|
|
@ -17,7 +17,8 @@ const SHORTCUTS: [string, string][] = [
|
||||||
['Drag on empty space', 'Select several parts'],
|
['Drag on empty space', 'Select several parts'],
|
||||||
['Right or middle drag, Space + drag', 'Move the view'],
|
['Right or middle drag, Space + drag', 'Move the view'],
|
||||||
['Mouse wheel', 'Zoom'],
|
['Mouse wheel', 'Zoom'],
|
||||||
['N, I, O, L, B, C, H, T, P', 'Place NAND, input, output, lamp, button, clock, hex display, note, input panel'],
|
['N, I, O, L, B, C, H, T, P, X', 'Place NAND, input, output, lamp, button, clock, hex display, note, input panel, pixel'],
|
||||||
|
['Select wires, Bundle into cable', 'Run several wires as one thick cable; Remove cable undoes it'],
|
||||||
['Shift + click on canvas', 'Keep placing the same part'],
|
['Shift + click on canvas', 'Keep placing the same part'],
|
||||||
['Ctrl+C, Ctrl+V, Ctrl+D', 'Copy, paste, duplicate; names continue their series (D0 → D1)'],
|
['Ctrl+C, Ctrl+V, Ctrl+D', 'Copy, paste, duplicate; names continue their series (D0 → D1)'],
|
||||||
['Delete', 'Remove the selection'],
|
['Delete', 'Remove the selection'],
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,7 @@
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { tableMarkdown, type TestResult, type TruthTable } from '~/lib/logic/analyze'
|
import type { ChallengeCheck } from '~/composables/useEditor'
|
||||||
|
import { tableMarkdown, type TruthTable } from '~/lib/logic/analyze'
|
||||||
|
import { cableOf } from '~/lib/logic/cables'
|
||||||
import { CHALLENGES } from '~/lib/logic/challenges'
|
import { CHALLENGES } from '~/lib/logic/challenges'
|
||||||
import { chipPins } from '~/lib/logic/geometry'
|
import { chipPins } from '~/lib/logic/geometry'
|
||||||
import { usages } from '~/lib/logic/ops'
|
import { usages } from '~/lib/logic/ops'
|
||||||
|
|
@ -28,7 +30,7 @@ const wireColor = computed(() => {
|
||||||
const colors = new Set(wires.value.map(w => w.color ?? ''))
|
const colors = new Set(wires.value.map(w => w.color ?? ''))
|
||||||
return colors.size === 1 ? [...colors][0] : null
|
return colors.size === 1 ? [...colors][0] : null
|
||||||
})
|
})
|
||||||
const hasFace = computed(() => def.value.nodes.some(n => n.kind === 'lamp' || n.kind === 'hex'))
|
const hasFace = computed(() => def.value.nodes.some(n => n.kind === 'lamp' || n.kind === 'hex' || n.kind === 'pixel'))
|
||||||
const nameInput = ref<HTMLInputElement>()
|
const nameInput = ref<HTMLInputElement>()
|
||||||
watch(
|
watch(
|
||||||
() => ed.labelFocus.value,
|
() => ed.labelFocus.value,
|
||||||
|
|
@ -72,7 +74,9 @@ function refreshTable() {
|
||||||
}
|
}
|
||||||
watch([showTable, () => ed.sim.value, () => def.value.id], refreshTable)
|
watch([showTable, () => ed.sim.value, () => def.value.id], refreshTable)
|
||||||
|
|
||||||
const check = ref<TestResult | null>(null)
|
const check = ref<ChallengeCheck | null>(null)
|
||||||
|
const bestHere = computed(() => (challenge.value ? ed.project.value.best?.[challenge.value.id] : undefined))
|
||||||
|
const cable = computed(() => (wires.value.length === 1 ? cableOf(def.value, wires.value[0]!) : undefined))
|
||||||
watch(() => def.value.id, () => (check.value = null))
|
watch(() => def.value.id, () => (check.value = null))
|
||||||
watch(() => ed.sim.value, () => (check.value = null))
|
watch(() => ed.sim.value, () => (check.value = null))
|
||||||
function runCheck() {
|
function runCheck() {
|
||||||
|
|
@ -141,6 +145,17 @@ watch(() => def.value.id, () => (confirmDelete.value = false))
|
||||||
<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 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>
|
<button class="btn" :disabled="!wires.some(w => w.pts)" @click="ed.autoRoute()"><Icon name="lucide:wand-sparkles" class="size-4" /> Auto route</button>
|
||||||
</div>
|
</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>
|
||||||
|
<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>
|
||||||
<button class="btn btn-ghost mt-2 w-full" @click="ed.deleteSelected()"><Icon name="lucide:trash-2" class="size-4" /> Delete</button>
|
<button class="btn btn-ghost mt-2 w-full" @click="ed.deleteSelected()"><Icon name="lucide:trash-2" class="size-4" /> Delete</button>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
|
@ -157,6 +172,16 @@ watch(() => def.value.id, () => (confirmDelete.value = false))
|
||||||
<Icon :name="check.pass ? 'lucide:circle-check' : 'lucide:circle-x'" class="size-4 shrink-0" />
|
<Icon :name="check.pass ? 'lucide:circle-check' : 'lucide:circle-x'" class="size-4 shrink-0" />
|
||||||
{{ check.message }}
|
{{ check.message }}
|
||||||
</p>
|
</p>
|
||||||
|
<p class="score">
|
||||||
|
<Icon name="lucide:cpu" class="size-4 shrink-0" />
|
||||||
|
<span>
|
||||||
|
{{ ed.transistors(def.id).toLocaleString() }} transistors now<template v-if="bestHere !== undefined">, best <strong>{{ bestHere.toLocaleString() }}</strong></template>
|
||||||
|
</span>
|
||||||
|
</p>
|
||||||
|
<p v-if="check?.pass && check.record !== undefined" class="result pass">
|
||||||
|
<Icon name="lucide:trophy" class="size-4 shrink-0" /> New record! {{ check.record - check.transistors }} fewer than before ({{ check.record }}).
|
||||||
|
</p>
|
||||||
|
<p v-else-if="check?.pass && check.best === check.transistors" class="hint">Fewer transistors is better: 4 per NAND gate. Can you make it smaller?</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- Circuit -->
|
<!-- Circuit -->
|
||||||
|
|
@ -194,6 +219,8 @@ watch(() => def.value.id, () => (confirmDelete.value = false))
|
||||||
<dd>{{ pins.inputs.length }} in, {{ pins.outputs.length }} out</dd>
|
<dd>{{ pins.inputs.length }} in, {{ pins.outputs.length }} out</dd>
|
||||||
<dt>NAND gates</dt>
|
<dt>NAND gates</dt>
|
||||||
<dd>{{ ed.circuitStats.value.nands.toLocaleString() }}</dd>
|
<dd>{{ ed.circuitStats.value.nands.toLocaleString() }}</dd>
|
||||||
|
<dt title="CMOS: 4 transistors per NAND gate">Transistors</dt>
|
||||||
|
<dd>{{ ed.transistors(def.id).toLocaleString() }}</dd>
|
||||||
<dt>{{ ed.circuitStats.value.sequential ? 'Memory' : 'Delay' }}</dt>
|
<dt>{{ ed.circuitStats.value.sequential ? 'Memory' : 'Delay' }}</dt>
|
||||||
<dd>{{ ed.circuitStats.value.sequential ? 'yes (feedback loops)' : `${ed.circuitStats.value.delay} gates` }}</dd>
|
<dd>{{ ed.circuitStats.value.sequential ? 'yes (feedback loops)' : `${ed.circuitStats.value.delay} gates` }}</dd>
|
||||||
</dl>
|
</dl>
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,8 @@
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { stats } from '~/lib/logic/analyze'
|
import { stats } from '~/lib/logic/analyze'
|
||||||
import { compile } from '~/lib/logic/compile'
|
import { compile } from '~/lib/logic/compile'
|
||||||
import { chipPins, rowLabel } from '~/lib/logic/geometry'
|
import { cableOf } from '~/lib/logic/cables'
|
||||||
|
import { cableBits, chipPins, MAX_BITS, rowLabel } from '~/lib/logic/geometry'
|
||||||
import { SINK_KINDS, SOURCE_KINDS } from '~/lib/logic/ops'
|
import { SINK_KINDS, SOURCE_KINDS } from '~/lib/logic/ops'
|
||||||
import { LAMP_COLORS, type CircuitNode, type NodeKind, type PanelControl, type PanelRow } from '~/lib/logic/types'
|
import { LAMP_COLORS, type CircuitNode, type NodeKind, type PanelControl, type PanelRow } from '~/lib/logic/types'
|
||||||
|
|
||||||
|
|
@ -20,6 +21,9 @@ const KIND_NAMES: Record<string, string> = {
|
||||||
hex: 'Hex display',
|
hex: 'Hex display',
|
||||||
note: 'Note',
|
note: 'Note',
|
||||||
panel: 'Input panel',
|
panel: 'Input panel',
|
||||||
|
bundle: 'Cable bundle',
|
||||||
|
split: 'Cable split',
|
||||||
|
pixel: 'Pixel',
|
||||||
}
|
}
|
||||||
|
|
||||||
const CONTROLS: { value: PanelControl; label: string }[] = [
|
const CONTROLS: { value: PanelControl; label: string }[] = [
|
||||||
|
|
@ -37,6 +41,9 @@ const HINTS: Record<string, string> = {
|
||||||
button: 'Gives 1 while held down with the mouse or its key.',
|
button: 'Gives 1 while held down with the mouse or its key.',
|
||||||
lamp: 'Lights up at 1. Inside a component it also shows on the component box.',
|
lamp: 'Lights up at 1. Inside a component it also shows on the component box.',
|
||||||
hex: 'Shows inputs 1, 2, 4, 8 as one hex digit. Inside a component it also shows on the component box.',
|
hex: 'Shows inputs 1, 2, 4, 8 as one hex digit. Inside a component it also shows on the component box.',
|
||||||
|
bundle: 'Wire 0 (top) to the last on the left go into the cable on the right. Run the cable to a split, which gives them back in the same order.',
|
||||||
|
split: 'Takes a cable from a bundle and gives its wires back in the same order, top to bottom.',
|
||||||
|
pixel: 'Lights at 1. Inside a component, all its pixels show on the component box as one screen, without gaps: space them out inside to wire them, every column and row they sit on becomes a column and row of the screen.',
|
||||||
panel: 'Click a row on the canvas to flip its switch or hold its button. Rows without a name take the name of the pin they are wired to.',
|
panel: 'Click a row on the canvas to flip its switch or hold its button. Rows without a name take the name of the pin they are wired to.',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -78,7 +85,7 @@ watch(
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
const hasLabel = computed(() => n.value.kind !== 'high' && n.value.kind !== 'low' && n.value.kind !== 'nand')
|
const hasLabel = computed(() => !['high', 'low', 'nand', 'bundle', 'split', 'pixel'].includes(n.value.kind))
|
||||||
|
|
||||||
function setHz(e: Event) {
|
function setHz(e: Event) {
|
||||||
const v = Number((e.target as HTMLInputElement).value)
|
const v = Number((e.target as HTMLInputElement).value)
|
||||||
|
|
@ -139,6 +146,14 @@ const dock = computed(() => {
|
||||||
return chip ? chip.label?.trim() || (chip.chip ? ed.getDef.value(chip.chip)?.name : undefined) || 'component' : null
|
return chip ? chip.label?.trim() || (chip.chip ? ed.getDef.value(chip.chip)?.name : undefined) || 'component' : null
|
||||||
})
|
})
|
||||||
|
|
||||||
|
/** The bundle of the cable this bundle or split belongs to. */
|
||||||
|
const cableBundle = computed(() => {
|
||||||
|
if (n.value.kind === 'bundle') return n.value
|
||||||
|
if (n.value.kind !== 'split') return undefined
|
||||||
|
const feed = ed.def.value.wires.find(w => w.to.node === n.value.id)
|
||||||
|
return feed ? cableOf(ed.def.value, feed) : undefined
|
||||||
|
})
|
||||||
|
|
||||||
const chipInputs = computed(() => (chipDef.value ? chipPins(chipDef.value).inputs.length : 0))
|
const chipInputs = computed(() => (chipDef.value ? chipPins(chipDef.value).inputs.length : 0))
|
||||||
const chipOutputs = computed(() => (chipDef.value ? chipPins(chipDef.value).outputs.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))
|
const hasPanel = computed(() => ed.def.value.nodes.some(x => x.kind === 'panel' && x.attach === n.value.id))
|
||||||
|
|
@ -260,7 +275,7 @@ function setRowHz(row: PanelRow, e: Event) {
|
||||||
</label>
|
</label>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<div v-if="n.kind === 'lamp' || n.kind === 'hex'" class="field">
|
<div v-if="n.kind === 'lamp' || n.kind === 'hex' || n.kind === 'pixel'" class="field">
|
||||||
<span>Colour</span>
|
<span>Colour</span>
|
||||||
<div class="swatches">
|
<div class="swatches">
|
||||||
<button class="swatch lamp-swatch default" :class="{ active: !n.color, hex: n.kind === 'hex' }" title="Default" @click="setColor(undefined)" />
|
<button class="swatch lamp-swatch default" :class="{ active: !n.color, hex: n.kind === 'hex' }" title="Default" @click="setColor(undefined)" />
|
||||||
|
|
@ -284,6 +299,16 @@ function setRowHz(row: PanelRow, e: Event) {
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<template v-if="n.kind === 'bundle' || n.kind === 'split'">
|
||||||
|
<label class="field">
|
||||||
|
<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>
|
||||||
|
<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>
|
||||||
|
</template>
|
||||||
|
|
||||||
<p v-if="HINTS[n.kind]" class="hint">{{ HINTS[n.kind] }}</p>
|
<p v-if="HINTS[n.kind]" class="hint">{{ HINTS[n.kind] }}</p>
|
||||||
|
|
||||||
<template v-if="n.kind === 'chip' && chipDef">
|
<template v-if="n.kind === 'chip' && chipDef">
|
||||||
|
|
@ -291,6 +316,8 @@ function setRowHz(row: PanelRow, e: Event) {
|
||||||
<dl v-if="chipStats" class="stats">
|
<dl v-if="chipStats" class="stats">
|
||||||
<dt>NAND gates</dt>
|
<dt>NAND gates</dt>
|
||||||
<dd>{{ chipStats.nands.toLocaleString() }}</dd>
|
<dd>{{ chipStats.nands.toLocaleString() }}</dd>
|
||||||
|
<dt title="CMOS: 4 transistors per NAND gate">Transistors</dt>
|
||||||
|
<dd>{{ ed.transistors(chipDef.id).toLocaleString() }}</dd>
|
||||||
<dt>{{ chipStats.sequential ? 'Memory' : 'Delay' }}</dt>
|
<dt>{{ chipStats.sequential ? 'Memory' : 'Delay' }}</dt>
|
||||||
<dd>{{ chipStats.sequential ? 'yes (feedback)' : `${chipStats.delay} gates` }}</dd>
|
<dd>{{ chipStats.sequential ? 'yes (feedback)' : `${chipStats.delay} gates` }}</dd>
|
||||||
</dl>
|
</dl>
|
||||||
|
|
|
||||||
|
|
@ -18,6 +18,16 @@ const chipDef = computed(() => (props.node.chip ? ed.getDef.value(props.node.chi
|
||||||
const b = computed(() => props.shape.body)
|
const b = computed(() => props.shape.body)
|
||||||
const rows = computed(() => props.node.rows ?? [])
|
const rows = computed(() => props.node.rows ?? [])
|
||||||
|
|
||||||
|
/** Lines inside a bundle or split from each single wire to the cable pin. */
|
||||||
|
const cableFan = computed(() => {
|
||||||
|
const s = props.shape
|
||||||
|
const cable = [...s.inputs, ...s.outputs].find(p => p.bus)
|
||||||
|
const singles = [...s.inputs, ...s.outputs].filter(p => !p.bus)
|
||||||
|
if (!cable) return ''
|
||||||
|
const cx = props.node.kind === 'bundle' ? 0.75 * G : 0.25 * G
|
||||||
|
return singles.map(p => `M${p.dx * G} ${p.dy * G}L${cx} ${cable.dy * G}`).join('') + `M${cx} ${cable.dy * G}L${cable.dx * G} ${cable.dy * G}`
|
||||||
|
})
|
||||||
|
|
||||||
const v = (pin: string) => (props.ghost ? 0 : ed.val(props.node.id, pin))
|
const v = (pin: string) => (props.ghost ? 0 : ed.val(props.node.id, pin))
|
||||||
/** Value inside this chip, for its lamps and displays. */
|
/** Value inside this chip, for its lamps and displays. */
|
||||||
const fv = (inner: string, pin: string) => (props.ghost ? 0 : ed.faceVal(props.node.id, inner, pin))
|
const fv = (inner: string, pin: string) => (props.ghost ? 0 : ed.faceVal(props.node.id, inner, pin))
|
||||||
|
|
@ -56,7 +66,20 @@ const title = computed(() => {
|
||||||
<rect :x="0" :y="b.y * G" :width="b.w * G" :height="b.h * G" rx="3" class="body chip" :class="{ missing: !chipDef }" />
|
<rect :x="0" :y="b.y * G" :width="b.w * G" :height="b.h * G" rx="3" class="body chip" :class="{ missing: !chipDef }" />
|
||||||
<text :x="(b.w * G) / 2" :y="(shape.nameY ?? b.y + b.h / 2) * G + 4" text-anchor="middle" class="chip-name">{{ chipDef?.name ?? 'Missing' }}</text>
|
<text :x="(b.w * G) / 2" :y="(shape.nameY ?? b.y + b.h / 2) * G + 4" text-anchor="middle" class="chip-name">{{ chipDef?.name ?? 'Missing' }}</text>
|
||||||
<template v-for="f in shape.face" :key="f.id">
|
<template v-for="f in shape.face" :key="f.id">
|
||||||
<template v-if="f.kind === 'lamp'">
|
<template v-if="f.kind === 'screen'">
|
||||||
|
<rect :x="f.x * G - 2" :y="f.y * G - 2" :width="f.w * G + 4" :height="f.h * G + 4" rx="2" class="screen-bg" />
|
||||||
|
<rect
|
||||||
|
v-for="p in f.pixels"
|
||||||
|
:key="p.id"
|
||||||
|
:x="(f.x + p.col * f.px!) * G"
|
||||||
|
:y="(f.y + p.row * f.px!) * G"
|
||||||
|
:width="f.px! * G - 0.5"
|
||||||
|
:height="f.px! * G - 0.5"
|
||||||
|
class="screen-px"
|
||||||
|
:class="[p.color ? `px-${p.color}` : '', { on: fv(p.id, 'a') === 1 }]"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
<template v-else-if="f.kind === 'lamp'">
|
||||||
<circle :cx="(f.x + f.w / 2) * G" :cy="(f.y + 0.6) * G" :r="0.42 * G" class="lamp" :class="[f.color ? `l-${f.color}` : '', { on: fv(f.id, 'a') === 1 }]" />
|
<circle :cx="(f.x + f.w / 2) * G" :cy="(f.y + 0.6) * G" :r="0.42 * G" class="lamp" :class="[f.color ? `l-${f.color}` : '', { on: fv(f.id, 'a') === 1 }]" />
|
||||||
</template>
|
</template>
|
||||||
<template v-else>
|
<template v-else>
|
||||||
|
|
@ -134,6 +157,17 @@ const title = computed(() => {
|
||||||
<text v-if="node.label" :x="(b.w * G) / 2" :y="(b.y + b.h) * G + 12" text-anchor="middle" class="face-label">{{ node.label }}</text>
|
<text v-if="node.label" :x="(b.w * G) / 2" :y="(b.y + b.h) * G + 12" text-anchor="middle" class="face-label">{{ node.label }}</text>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<!-- Cable ends: a bundle gathers wires into one cable, a split fans it out -->
|
||||||
|
<template v-else-if="node.kind === 'bundle' || node.kind === 'split'">
|
||||||
|
<rect :x="0" :y="b.y * G" :width="b.w * G" :height="b.h * G" rx="2" class="body cable-end" />
|
||||||
|
<path :d="cableFan" class="cable-fan" />
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- Pixel: one square of a screen -->
|
||||||
|
<template v-else-if="node.kind === 'pixel'">
|
||||||
|
<rect x="1" :y="b.y * G + 1" :width="G - 2" :height="G - 2" rx="1" class="pixel" :class="[node.color ? `px-${node.color}` : '', { on: v('a') === 1 }]" />
|
||||||
|
</template>
|
||||||
|
|
||||||
<!-- Input panel: a switch, button or clock per row -->
|
<!-- Input panel: a switch, button or clock per row -->
|
||||||
<template v-else-if="node.kind === 'panel'">
|
<template v-else-if="node.kind === 'panel'">
|
||||||
<text v-if="node.label" :x="(b.w * G) / 2" :y="b.y * G - 5" text-anchor="middle" class="instance-label">{{ node.label }}</text>
|
<text v-if="node.label" :x="(b.w * G) / 2" :y="b.y * G - 5" text-anchor="middle" class="instance-label">{{ node.label }}</text>
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
|
import { shortCount } from '~/lib/logic/analyze'
|
||||||
import { CHALLENGES } from '~/lib/logic/challenges'
|
import { CHALLENGES } from '~/lib/logic/challenges'
|
||||||
import type { ComponentDef, NodeKind } from '~/lib/logic/types'
|
import type { ComponentDef, NodeKind } from '~/lib/logic/types'
|
||||||
|
|
||||||
|
|
@ -17,10 +18,13 @@ const BASICS: { kind: NodeKind; name: string; icon: string; key?: string; hint:
|
||||||
{ kind: 'high', name: 'Constant 1', icon: 'lucide:plus', hint: 'Always 1, like the supply rail.' },
|
{ kind: 'high', name: 'Constant 1', icon: 'lucide:plus', hint: 'Always 1, like the supply rail.' },
|
||||||
{ kind: 'low', name: 'Ground (0)', icon: 'lucide:arrow-down-to-line', hint: 'Always 0.' },
|
{ kind: 'low', name: 'Ground (0)', icon: 'lucide:arrow-down-to-line', hint: 'Always 0.' },
|
||||||
{ kind: 'hex', name: 'Hex display', icon: 'lucide:binary', key: 'H', hint: 'Shows 4 bits as 0–F.' },
|
{ kind: 'hex', name: 'Hex display', icon: 'lucide:binary', key: 'H', hint: 'Shows 4 bits as 0–F.' },
|
||||||
|
{ kind: 'pixel', name: 'Pixel', icon: 'lucide:square', key: 'X', hint: 'One square of a screen, lit at 1. Pixels inside a component show on its box as one screen: build your own LCD.' },
|
||||||
|
{ kind: 'bundle', name: 'Cable bundle', icon: 'lucide:merge', hint: 'Gathers several wires into one cable. Or select wires and press "Bundle into cable".' },
|
||||||
|
{ kind: 'split', name: 'Cable split', icon: 'lucide:split', hint: 'Fans a cable out into its wires again.' },
|
||||||
{ kind: 'note', name: 'Note', icon: 'lucide:sticky-note', key: 'T', hint: 'Text label for your drawing.' },
|
{ kind: 'note', name: 'Note', icon: 'lucide:sticky-note', key: 'T', hint: 'Text label for your drawing.' },
|
||||||
]
|
]
|
||||||
|
|
||||||
const GROUP_ORDER = ['', 'Gates', 'Routing', 'Arithmetic', 'Memory', 'Demos']
|
const GROUP_ORDER = ['', 'Gates', 'Routing', 'Arithmetic', 'Memory', 'Displays', 'Demos']
|
||||||
|
|
||||||
const groups = computed(() => {
|
const groups = computed(() => {
|
||||||
const q = query.value.trim().toLowerCase()
|
const q = query.value.trim().toLowerCase()
|
||||||
|
|
@ -52,6 +56,7 @@ function onDragStart(e: DragEvent, kind: NodeKind, chip?: string) {
|
||||||
}
|
}
|
||||||
|
|
||||||
const solved = computed(() => new Set(ed.project.value.solved))
|
const solved = computed(() => new Set(ed.project.value.solved))
|
||||||
|
const best = computed(() => ed.project.value.best ?? {})
|
||||||
const started = computed(() => new Map(ed.project.value.components.filter(d => d.challenge).map(d => [d.challenge!, d])))
|
const started = computed(() => new Map(ed.project.value.components.filter(d => d.challenge).map(d => [d.challenge!, d])))
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
|
@ -105,6 +110,7 @@ const started = computed(() => new Map(ed.project.value.components.filter(d => d
|
||||||
<Icon :name="d.challenge && solved.has(d.challenge) ? 'lucide:badge-check' : 'lucide:box'" class="size-4 shrink-0" :class="d.challenge && solved.has(d.challenge) ? 'text-(--on)' : 'text-(--muted)'" />
|
<Icon :name="d.challenge && solved.has(d.challenge) ? 'lucide:badge-check' : 'lucide:box'" class="size-4 shrink-0" :class="d.challenge && solved.has(d.challenge) ? 'text-(--on)' : 'text-(--muted)'" />
|
||||||
<span class="grow truncate">{{ d.name }}</span>
|
<span class="grow truncate">{{ d.name }}</span>
|
||||||
<span v-if="d.id === ed.def.value.id" class="editing">editing</span>
|
<span v-if="d.id === ed.def.value.id" class="editing">editing</span>
|
||||||
|
<span v-else-if="ed.transistors(d.id)" class="tcount" :title="`${ed.transistors(d.id).toLocaleString()} transistors`">{{ shortCount(ed.transistors(d.id)) }}T</span>
|
||||||
</button>
|
</button>
|
||||||
<button v-if="d.id !== ed.def.value.id" class="open" title="Open and edit" @click="ed.open(d.id)">
|
<button v-if="d.id !== ed.def.value.id" class="open" title="Open and edit" @click="ed.open(d.id)">
|
||||||
<Icon name="lucide:pencil" class="size-3.5" />
|
<Icon name="lucide:pencil" class="size-3.5" />
|
||||||
|
|
@ -136,7 +142,12 @@ const started = computed(() => new Map(ed.project.value.components.filter(d => d
|
||||||
<button class="btn-sm" @click="ed.beginChallenge(c)">{{ started.has(c.id) ? 'Open' : 'Start' }}</button>
|
<button class="btn-sm" @click="ed.beginChallenge(c)">{{ started.has(c.id) ? 'Open' : 'Start' }}</button>
|
||||||
</div>
|
</div>
|
||||||
<p>{{ c.goal }}</p>
|
<p>{{ c.goal }}</p>
|
||||||
<p class="pins">{{ c.inputs.join(', ') }} → {{ c.outputs.join(', ') }}</p>
|
<p class="pins">
|
||||||
|
{{ c.inputs.join(', ') }} → {{ c.outputs.join(', ') }}
|
||||||
|
<span v-if="best[c.id] !== undefined" class="best" title="Fewest transistors in a passing solution so far">
|
||||||
|
· best {{ best[c.id]!.toLocaleString() }} transistors
|
||||||
|
</span>
|
||||||
|
</p>
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -2,10 +2,11 @@
|
||||||
// history, share links and the running simulation of the open circuit.
|
// history, share links and the running simulation of the open circuit.
|
||||||
// One shared instance for the whole page.
|
// One shared instance for the whole page.
|
||||||
|
|
||||||
import { runSteps, stats, tableCsv, truthTable, type Stats, type TestResult, type TruthTable } from '~/lib/logic/analyze'
|
import { nandCounts, runSteps, stats, tableCsv, TRANSISTORS_PER_NAND, truthTable, type Stats, type TestResult, type TruthTable } from '~/lib/logic/analyze'
|
||||||
|
import { bundleWires, dissolveCable } from '~/lib/logic/cables'
|
||||||
import { CHALLENGES, challengeSteps, type Challenge } from '~/lib/logic/challenges'
|
import { CHALLENGES, challengeSteps, type Challenge } from '~/lib/logic/challenges'
|
||||||
import { compile, rowSource } from '~/lib/logic/compile'
|
import { compile, rowSource } from '~/lib/logic/compile'
|
||||||
import { shapeOf, type Pt } from '~/lib/logic/geometry'
|
import { MAX_BITS, shapeOf, type Pt } from '~/lib/logic/geometry'
|
||||||
import { adoptName, continueSeries, newPinLabel } from '~/lib/logic/labels'
|
import { adoptName, continueSeries, newPinLabel } from '~/lib/logic/labels'
|
||||||
import { attachPanel, detachPanel, dockedPanels, newPanelRows, removeRow, syncPanels } from '~/lib/logic/panels'
|
import { attachPanel, detachPanel, dockedPanels, newPanelRows, removeRow, syncPanels } from '~/lib/logic/panels'
|
||||||
import {
|
import {
|
||||||
|
|
@ -51,6 +52,15 @@ import {
|
||||||
} from '~/lib/logic/storage'
|
} from '~/lib/logic/storage'
|
||||||
import type { CircuitNode, NodeKind, PanelControl, PanelRow, PinRef, Project, WireColor } from '~/lib/logic/types'
|
import type { CircuitNode, NodeKind, PanelControl, PanelRow, PinRef, Project, WireColor } from '~/lib/logic/types'
|
||||||
|
|
||||||
|
/** A challenge check plus how many transistors the solution uses. */
|
||||||
|
export interface ChallengeCheck extends TestResult {
|
||||||
|
transistors: number
|
||||||
|
/** Fewest transistors of any passing solution so far, this one included. */
|
||||||
|
best?: number
|
||||||
|
/** Set when this one beat an earlier record: that record. */
|
||||||
|
record?: number
|
||||||
|
}
|
||||||
|
|
||||||
/** One pin waiting to be wired in "connect one by one". */
|
/** One pin waiting to be wired in "connect one by one". */
|
||||||
export interface LinkEnd {
|
export interface LinkEnd {
|
||||||
node: string
|
node: string
|
||||||
|
|
@ -377,6 +387,7 @@ function create() {
|
||||||
}
|
}
|
||||||
if (p.kind === 'note') node.label = 'Note'
|
if (p.kind === 'note') node.label = 'Note'
|
||||||
if (p.kind === 'panel') node.rows = newPanelRows()
|
if (p.kind === 'panel') node.rows = newPanelRows()
|
||||||
|
if (p.kind === 'bundle' || p.kind === 'split') node.bits = 4
|
||||||
def.value.nodes.push(node)
|
def.value.nodes.push(node)
|
||||||
selection.value = [node.id]
|
selection.value = [node.id]
|
||||||
wireSel.value = []
|
wireSel.value = []
|
||||||
|
|
@ -388,8 +399,19 @@ function create() {
|
||||||
return !containsDef(project.value, chipId, def.value.id)
|
return !containsDef(project.value, chipId, def.value.id)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** True when the pin is a cable end (bundle output, split input). */
|
||||||
|
function isBus(nodeId: string, pin: string, dir: 'in' | 'out'): boolean {
|
||||||
|
const n = def.value.nodes.find(x => x.id === nodeId)
|
||||||
|
if (!n) return false
|
||||||
|
const s = shapeOf(n, getDef.value)
|
||||||
|
return !!(dir === 'in' ? s.inputs : s.outputs).find(p => p.key === pin)?.bus
|
||||||
|
}
|
||||||
|
|
||||||
function connect(from: PinRef, to: PinRef, pts?: Pt[]) {
|
function connect(from: PinRef, to: PinRef, pts?: Pt[]) {
|
||||||
const d = def.value
|
const d = def.value
|
||||||
|
if (isBus(from.node, from.pin, 'out') !== isBus(to.node, to.pin, 'in')) {
|
||||||
|
return notify('A cable runs from a bundle to a split; single wires go to the bundle’s and split’s side pins', 'error')
|
||||||
|
}
|
||||||
const old = d.wires.find(w => w.to.node === to.node && w.to.pin === to.pin)
|
const old = d.wires.find(w => w.to.node === to.node && w.to.pin === to.pin)
|
||||||
d.wires = d.wires.filter(w => w !== old)
|
d.wires = d.wires.filter(w => w !== old)
|
||||||
const wire: (typeof d.wires)[number] = { id: uid('w'), from, to }
|
const wire: (typeof d.wires)[number] = { id: uid('w'), from, to }
|
||||||
|
|
@ -678,15 +700,58 @@ function create() {
|
||||||
open(d.id)
|
open(d.id)
|
||||||
}
|
}
|
||||||
|
|
||||||
function checkChallenge(): TestResult | null {
|
function checkChallenge(): ChallengeCheck | null {
|
||||||
const c = CHALLENGES.find(c => c.id === def.value.challenge)
|
const c = CHALLENGES.find(c => c.id === def.value.challenge)
|
||||||
if (!c) return null
|
if (!c) return null
|
||||||
const res = runSteps(getDef.value, def.value.id, challengeSteps(c))
|
const res = runSteps(getDef.value, def.value.id, challengeSteps(c))
|
||||||
if (res.pass && !project.value.solved.includes(c.id)) {
|
const used = transistors(def.value.id)
|
||||||
|
const before = project.value.best?.[c.id]
|
||||||
|
if (!res.pass) return { ...res, transistors: used, best: before }
|
||||||
|
let changed = false
|
||||||
|
if (!project.value.solved.includes(c.id)) {
|
||||||
project.value.solved.push(c.id)
|
project.value.solved.push(c.id)
|
||||||
commit(false)
|
changed = true
|
||||||
}
|
}
|
||||||
return res
|
const record = before === undefined || used < before
|
||||||
|
if (record) {
|
||||||
|
project.value.best = { ...project.value.best, [c.id]: used }
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
if (changed) {
|
||||||
|
commit(false)
|
||||||
|
persist()
|
||||||
|
}
|
||||||
|
return { ...res, transistors: used, best: record ? used : before, record: record && before !== undefined ? before : undefined }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Transistors ───────────────────────────────────────────────────
|
||||||
|
const nands = computed(() => nandCounts(project.value.components))
|
||||||
|
|
||||||
|
/** Transistors in a component at every depth, 4 per NAND gate. */
|
||||||
|
function transistors(defId: string): number {
|
||||||
|
return (nands.value.get(defId) ?? 0) * TRANSISTORS_PER_NAND
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Cables ────────────────────────────────────────────────────────
|
||||||
|
function bundleSelected() {
|
||||||
|
const res = bundleWires(def.value, wireSel.value, getDef.value)
|
||||||
|
if (!res.ok) return notify(res.error, 'error')
|
||||||
|
selection.value = [res.bundle.id, res.split.id]
|
||||||
|
wireSel.value = []
|
||||||
|
commit()
|
||||||
|
notify(`${res.bundle.bits} wires bundled into one cable`)
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeCable(bundleId: string) {
|
||||||
|
const n = dissolveCable(def.value, bundleId)
|
||||||
|
clearSelection()
|
||||||
|
commit()
|
||||||
|
notify(n ? `Cable removed; ${n} wire${n === 1 ? '' : 's'} run on their own again` : 'Cable removed')
|
||||||
|
}
|
||||||
|
|
||||||
|
function setBits(node: CircuitNode, bits: number) {
|
||||||
|
node.bits = Math.min(MAX_BITS, Math.max(2, Math.round(bits) || 2))
|
||||||
|
commit()
|
||||||
}
|
}
|
||||||
|
|
||||||
function table(): TruthTable | { error: string } {
|
function table(): TruthTable | { error: string } {
|
||||||
|
|
@ -1301,6 +1366,11 @@ function create() {
|
||||||
setTidy,
|
setTidy,
|
||||||
tidyAll,
|
tidyAll,
|
||||||
exportTable,
|
exportTable,
|
||||||
|
transistors,
|
||||||
|
isBus,
|
||||||
|
bundleSelected,
|
||||||
|
removeCable,
|
||||||
|
setBits,
|
||||||
swap,
|
swap,
|
||||||
unlink,
|
unlink,
|
||||||
unpack,
|
unpack,
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@
|
||||||
import { compile, type Netlist } from './compile'
|
import { compile, type Netlist } from './compile'
|
||||||
import { chipPins, type DefLookup } from './geometry'
|
import { chipPins, type DefLookup } from './geometry'
|
||||||
import { Simulator } from './sim'
|
import { Simulator } from './sim'
|
||||||
|
import type { ComponentDef } from './types'
|
||||||
|
|
||||||
const SETTLE_BUDGET = 2_000_000
|
const SETTLE_BUDGET = 2_000_000
|
||||||
|
|
||||||
|
|
@ -60,6 +61,44 @@ export function tableMarkdown(t: TruthTable): string {
|
||||||
return `${lines.join('\n')}\n`
|
return `${lines.join('\n')}\n`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A CMOS NAND gate with two inputs: two transistors in parallel to the supply, two in series to ground. */
|
||||||
|
export const TRANSISTORS_PER_NAND = 4
|
||||||
|
|
||||||
|
/**
|
||||||
|
* NAND gates per component, counting everything inside it at every depth.
|
||||||
|
* Switches, lamps, displays and cables need no gates. Shared work is cached,
|
||||||
|
* so a whole library costs one pass; a component that contains itself counts 0.
|
||||||
|
*/
|
||||||
|
export function nandCounts(components: ComponentDef[]): Map<string, number> {
|
||||||
|
const byId = new Map(components.map(d => [d.id, d]))
|
||||||
|
const memo = new Map<string, number>()
|
||||||
|
const busy = new Set<string>()
|
||||||
|
const count = (id: string): number => {
|
||||||
|
const known = memo.get(id)
|
||||||
|
if (known !== undefined) return known
|
||||||
|
const def = byId.get(id)
|
||||||
|
if (!def || busy.has(id)) return 0
|
||||||
|
busy.add(id)
|
||||||
|
let n = 0
|
||||||
|
for (const node of def.nodes) {
|
||||||
|
if (node.kind === 'nand') n++
|
||||||
|
else if (node.kind === 'chip' && node.chip) n += count(node.chip)
|
||||||
|
}
|
||||||
|
busy.delete(id)
|
||||||
|
memo.set(id, n)
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
for (const d of components) count(d.id)
|
||||||
|
return memo
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "1,234 transistors" in short form for tight spots: 1.2k. */
|
||||||
|
export function shortCount(n: number): string {
|
||||||
|
if (n < 1000) return String(n)
|
||||||
|
if (n < 1_000_000) return `${(n / 1000).toFixed(n < 10_000 ? 1 : 0).replace(/\.0$/, '')}k`
|
||||||
|
return `${(n / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`
|
||||||
|
}
|
||||||
|
|
||||||
export interface Stats {
|
export interface Stats {
|
||||||
nands: number
|
nands: number
|
||||||
/** Has feedback loops, so it can store state (latch, flip-flop, counter). */
|
/** Has feedback loops, so it can store state (latch, flip-flop, counter). */
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,91 @@
|
||||||
|
// Cables: several wires bundled into one. A bundle part gathers the wires,
|
||||||
|
// 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 { uid } from './ops'
|
||||||
|
import type { CircuitNode, ComponentDef, Wire } from './types'
|
||||||
|
|
||||||
|
const isCable = (def: ComponentDef, w: Wire) => def.nodes.find(n => n.id === w.from.node)?.kind === 'bundle'
|
||||||
|
|
||||||
|
/** The bundle a wire belongs to: the wire is the cable itself, or runs into or out of its ends. */
|
||||||
|
export function cableOf(def: ComponentDef, wire: Wire): CircuitNode | undefined {
|
||||||
|
const nodes = new Map(def.nodes.map(n => [n.id, n]))
|
||||||
|
const from = nodes.get(wire.from.node)
|
||||||
|
if (from?.kind === 'bundle') return from
|
||||||
|
const to = nodes.get(wire.to.node)
|
||||||
|
if (to?.kind === 'bundle') return to
|
||||||
|
if (from?.kind === 'split') {
|
||||||
|
const feed = def.wires.find(w => w.to.node === from.id)
|
||||||
|
const b = feed && nodes.get(feed.from.node)
|
||||||
|
if (b?.kind === 'bundle') return b
|
||||||
|
}
|
||||||
|
return 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.
|
||||||
|
*/
|
||||||
|
export function bundleWires(def: ComponentDef, wireIds: string[], get: DefLookup): { 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))
|
||||||
|
if (wires.length < 2) return { ok: false, error: 'Select at least two wires' }
|
||||||
|
if (wires.length > MAX_BITS) return { ok: false, error: `A cable holds at most ${MAX_BITS} wires` }
|
||||||
|
if (wires.some(w => isCable(def, w))) return { ok: false, error: 'A cable cannot go into another cable' }
|
||||||
|
const ends = wires.map(w => {
|
||||||
|
const fn = nodes.get(w.from.node)!
|
||||||
|
const tn = nodes.get(w.to.node)!
|
||||||
|
return { w, a: pinPos(fn, shapeOf(fn, get), w.from.pin, 'out')!, b: pinPos(tn, shapeOf(tn, get), w.to.pin, 'in')! }
|
||||||
|
})
|
||||||
|
if (ends.some(e => !e.a || !e.b)) return { ok: false, error: 'Some wires have no pins' }
|
||||||
|
ends.sort((p, q) => p.b.y - q.b.y || p.a.y - q.a.y)
|
||||||
|
|
||||||
|
const n = ends.length
|
||||||
|
const mid = Math.floor((n - 1) / 2)
|
||||||
|
const mean = (v: number[]) => Math.round(v.reduce((s, x) => s + x, 0) / v.length)
|
||||||
|
const right = Math.max(...ends.map(e => e.a.x))
|
||||||
|
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 }
|
||||||
|
def.nodes.push(bundle, split)
|
||||||
|
def.wires = def.wires.filter(w => !ids.has(w.id))
|
||||||
|
ends.forEach((e, i) => {
|
||||||
|
const pin = `b${i}`
|
||||||
|
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 } : {}) })
|
||||||
|
return { ok: true, bundle, split }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Takes a cable apart again: its bundle and splits go, and each source is
|
||||||
|
* wired straight to the targets its wire reached. Returns how many wires
|
||||||
|
* now run on their own.
|
||||||
|
*/
|
||||||
|
export function dissolveCable(def: ComponentDef, bundleId: string): number {
|
||||||
|
const bundle = def.nodes.find(n => n.id === bundleId && n.kind === 'bundle')
|
||||||
|
if (!bundle) return 0
|
||||||
|
const splits = new Set(def.wires.filter(w => w.from.node === bundle.id).map(w => w.to.node))
|
||||||
|
for (const id of [...splits]) if (def.nodes.find(n => n.id === id)?.kind !== 'split') splits.delete(id)
|
||||||
|
const added: Wire[] = []
|
||||||
|
for (let i = 0; i < cableBits(bundle); i++) {
|
||||||
|
const pin = `b${i}`
|
||||||
|
const feed = def.wires.find(w => w.to.node === bundle.id && w.to.pin === pin)
|
||||||
|
if (!feed) continue
|
||||||
|
for (const w of def.wires) {
|
||||||
|
if (!splits.has(w.from.node) || w.from.pin !== pin) continue
|
||||||
|
added.push({ id: uid('w'), from: feed.from, to: w.to, ...(w.color ? { color: w.color } : {}) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const gone = new Set([bundle.id, ...splits])
|
||||||
|
def.nodes = def.nodes.filter(n => !gone.has(n.id))
|
||||||
|
def.wires = [...def.wires.filter(w => !gone.has(w.from.node) && !gone.has(w.to.node)), ...added]
|
||||||
|
return added.length
|
||||||
|
}
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
// nets. Chip boundaries and input/output pins disappear: they are aliases,
|
// nets. Chip boundaries and input/output pins disappear: they are aliases,
|
||||||
// merged with union-find. Net 0 is constant LOW, net 1 constant HIGH.
|
// merged with union-find. Net 0 is constant LOW, net 1 constant HIGH.
|
||||||
|
|
||||||
import { chipPins, type ChipPins, type DefLookup } from './geometry'
|
import { cableBits, chipPins, type ChipPins, type DefLookup } from './geometry'
|
||||||
import type { CircuitNode, ComponentDef, Wire } from './types'
|
import type { CircuitNode, ComponentDef, Wire } from './types'
|
||||||
|
|
||||||
export const LOW = 0
|
export const LOW = 0
|
||||||
|
|
@ -40,9 +40,13 @@ export function inputKeys(node: CircuitNode, pins?: ChipPins): string[] {
|
||||||
return ['a', 'b']
|
return ['a', 'b']
|
||||||
case 'output':
|
case 'output':
|
||||||
case 'lamp':
|
case 'lamp':
|
||||||
|
case 'pixel':
|
||||||
|
case 'split':
|
||||||
return ['a']
|
return ['a']
|
||||||
case 'hex':
|
case 'hex':
|
||||||
return ['b0', 'b1', 'b2', 'b3']
|
return ['b0', 'b1', 'b2', 'b3']
|
||||||
|
case 'bundle':
|
||||||
|
return cableKeys(node)
|
||||||
case 'chip':
|
case 'chip':
|
||||||
return pins ? pins.inputs.map(p => p.key) : []
|
return pins ? pins.inputs.map(p => p.key) : []
|
||||||
default:
|
default:
|
||||||
|
|
@ -63,11 +67,20 @@ export function outputKeys(node: CircuitNode, pins?: ChipPins): string[] {
|
||||||
return pins ? pins.outputs.map(p => p.key) : []
|
return pins ? pins.outputs.map(p => p.key) : []
|
||||||
case 'panel':
|
case 'panel':
|
||||||
return (node.rows ?? []).map(r => r.id)
|
return (node.rows ?? []).map(r => r.id)
|
||||||
|
case 'bundle':
|
||||||
|
return ['q']
|
||||||
|
case 'split':
|
||||||
|
return cableKeys(node)
|
||||||
default:
|
default:
|
||||||
return []
|
return []
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Pin keys of the single wires on a bundle or split: b0, b1, … */
|
||||||
|
export function cableKeys(node: CircuitNode): string[] {
|
||||||
|
return Array.from({ length: cableBits(node) }, (_, i) => `b${i}`)
|
||||||
|
}
|
||||||
|
|
||||||
/** Key of a panel row in the simulator's sources, like a switch's node id. */
|
/** Key of a panel row in the simulator's sources, like a switch's node id. */
|
||||||
export const rowSource = (nodeId: string, rowId: string) => `${nodeId}:${rowId}`
|
export const rowSource = (nodeId: string, rowId: string) => `${nodeId}:${rowId}`
|
||||||
|
|
||||||
|
|
@ -133,6 +146,7 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
|
||||||
|
|
||||||
const wiresTo = new Map<string, Wire>()
|
const wiresTo = new Map<string, Wire>()
|
||||||
for (const w of def.wires) wiresTo.set(`${w.to.node}:${w.to.pin}`, w)
|
for (const w of def.wires) wiresTo.set(`${w.to.node}:${w.to.pin}`, w)
|
||||||
|
const nodeById = new Map(def.nodes.map(n => [n.id, n]))
|
||||||
|
|
||||||
const outNet = new Map<string, number>()
|
const outNet = new Map<string, number>()
|
||||||
for (const n of def.nodes) {
|
for (const n of def.nodes) {
|
||||||
|
|
@ -168,6 +182,15 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
|
||||||
case 'clock':
|
case 'clock':
|
||||||
clocks.push({ net: q, hz: n.hz ?? 0, key: path + n.id })
|
clocks.push({ net: q, hz: n.hz ?? 0, key: path + n.id })
|
||||||
break
|
break
|
||||||
|
case 'split': {
|
||||||
|
// Wire i of the cable is whatever drives input i of the bundle at its other end.
|
||||||
|
const w = wiresTo.get(`${n.id}:a`)
|
||||||
|
const src = w && nodeById.get(w.from.node)
|
||||||
|
if (src?.kind !== 'bundle') break
|
||||||
|
const count = Math.min(cableBits(n), cableBits(src))
|
||||||
|
for (let i = 0; i < count; i++) union(outNet.get(`${n.id}:b${i}`)!, inNet(src.id, `b${i}`))
|
||||||
|
break
|
||||||
|
}
|
||||||
case 'panel':
|
case 'panel':
|
||||||
// In the open circuit the rows are switches and buttons you use;
|
// In the open circuit the rows are switches and buttons you use;
|
||||||
// inside a component a switch row keeps its position, a button is 0.
|
// inside a component a switch row keeps its position, a button is 0.
|
||||||
|
|
@ -199,7 +222,7 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
|
||||||
|
|
||||||
if (stack.length === 1) {
|
if (stack.length === 1) {
|
||||||
for (const n of def.nodes) {
|
for (const n of def.nodes) {
|
||||||
if (n.kind === 'lamp' || n.kind === 'hex') for (const k of inputKeys(n)) rawFace.set(`${path}${n.id}:${k}`, inNet(n.id, k))
|
if (n.kind === 'lamp' || n.kind === 'hex' || n.kind === 'pixel') for (const k of inputKeys(n)) rawFace.set(`${path}${n.id}:${k}`, inNet(n.id, k))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -81,6 +81,20 @@ export class Builder {
|
||||||
note(x: number, y: number, text: string) {
|
note(x: number, y: number, text: string) {
|
||||||
this.add({ kind: 'note', x, y, label: text })
|
this.add({ kind: 'note', x, y, label: text })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pixel(x: number, y: number, src: Src) {
|
||||||
|
const id = this.add({ kind: 'pixel', x, y })
|
||||||
|
this.link(src, { node: id, pin: 'a' })
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An input panel docked to a placed part, a switch per input, set to `on`. */
|
||||||
|
panel(chip: Src, on: boolean[]) {
|
||||||
|
const node = this.def.nodes.find(n => n.id === chip.node)!
|
||||||
|
const pins = chipPins(this.lib.get(node.chip!)!).inputs
|
||||||
|
const rows = pins.map((p, i) => ({ id: p.key, type: 'switch' as const, name: p.label, dy: i, ...(on[i] ? { on: true } : {}) }))
|
||||||
|
const id = this.add({ kind: 'panel', x: node.x - 8, y: node.y, attach: node.id, rows })
|
||||||
|
for (const p of pins) this.link({ node: id, pin: p.key }, { node: node.id, pin: p.key })
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function exampleLibrary(): ComponentDef[] {
|
export function exampleLibrary(): ComponentDef[] {
|
||||||
|
|
@ -263,6 +277,29 @@ export function exampleLibrary(): ComponentDef[] {
|
||||||
b.hex(24, 2, Q)
|
b.hex(24, 2, Q)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
make(
|
||||||
|
{
|
||||||
|
id: 'ex-screen4',
|
||||||
|
name: 'Screen 4×4',
|
||||||
|
group: 'Displays',
|
||||||
|
description: 'An LCD made of 16 pixels: P0 is the top left, P3 the top right, P15 the bottom right. Its box shows them as one screen.',
|
||||||
|
},
|
||||||
|
b => {
|
||||||
|
b.note(0, -4, 'Pixels are spaced out here so they can be wired.\nOn the component box they sit side by side as one screen.')
|
||||||
|
for (let r = 0; r < 4; r++) {
|
||||||
|
for (let c = 0; c < 4; c++) b.pixel(10 + 3 * c, 5 * r + 1, b.input(`P${4 * r + c}`, 0, 5 * r + c))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
make({ id: 'ex-demo-screen', name: 'Demo: Screen', group: 'Demos', description: 'An input panel drives the 4×4 screen. Flip its switches to draw.' }, b => {
|
||||||
|
b.note(0, -3, 'Flip the switches on the panel to draw on the screen.')
|
||||||
|
b.chip('ex-screen4', 12, 0)
|
||||||
|
const screen = b.def.nodes.at(-1)!
|
||||||
|
// Smiley: eyes, then the mouth.
|
||||||
|
b.panel({ node: screen.id, pin: '' }, [1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0].map(Boolean))
|
||||||
|
})
|
||||||
|
|
||||||
return [...lib.values()]
|
return [...lib.values()]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,8 @@ export interface PinInfo {
|
||||||
label: string
|
label: string
|
||||||
dx: number
|
dx: number
|
||||||
dy: number
|
dy: number
|
||||||
|
/** A cable pin: only joins another cable pin. */
|
||||||
|
bus?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Shape {
|
export interface Shape {
|
||||||
|
|
@ -24,10 +26,21 @@ export interface Shape {
|
||||||
face?: FaceItem[]
|
face?: FaceItem[]
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface FaceItem {
|
export interface ScreenPixel {
|
||||||
/** Node id inside the component. */
|
/** Pixel node id inside the component. */
|
||||||
id: string
|
id: string
|
||||||
kind: 'lamp' | 'hex'
|
col: number
|
||||||
|
row: number
|
||||||
|
color?: LampColor
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FaceItem {
|
||||||
|
/** Node id inside the component; for a screen, the first pixel's. */
|
||||||
|
id: string
|
||||||
|
kind: 'lamp' | 'hex' | 'screen'
|
||||||
|
/** Screen only: its pixels and the size of one, in grid units. */
|
||||||
|
pixels?: ScreenPixel[]
|
||||||
|
px?: number
|
||||||
label: string
|
label: string
|
||||||
color?: LampColor
|
color?: LampColor
|
||||||
/** Top-left corner and size in grid units, relative to the chip node. */
|
/** Top-left corner and size in grid units, relative to the chip node. */
|
||||||
|
|
@ -67,7 +80,6 @@ export function faceLayout(def: ComponentDef): { items: FaceItem[]; w: number; h
|
||||||
const empty = { items: [], w: 0, h: 0 }
|
const empty = { items: [], w: 0, h: 0 }
|
||||||
if (def.face === false) return empty
|
if (def.face === false) return empty
|
||||||
const nodes = def.nodes.filter(n => n.kind === 'lamp' || n.kind === 'hex').sort((a, b) => a.y - b.y || a.x - b.x)
|
const nodes = def.nodes.filter(n => n.kind === 'lamp' || n.kind === 'hex').sort((a, b) => a.y - b.y || a.x - b.x)
|
||||||
if (!nodes.length) return empty
|
|
||||||
const rows: CircuitNode[][] = []
|
const rows: CircuitNode[][] = []
|
||||||
for (const n of nodes) {
|
for (const n of nodes) {
|
||||||
const row = rows[rows.length - 1]
|
const row = rows[rows.length - 1]
|
||||||
|
|
@ -92,9 +104,43 @@ export function faceLayout(def: ComponentDef): { items: FaceItem[]; w: number; h
|
||||||
w = Math.max(w, x - 0.3)
|
w = Math.max(w, x - 0.3)
|
||||||
y += h + 0.3
|
y += h + 0.3
|
||||||
}
|
}
|
||||||
|
const screen = screenLayout(def)
|
||||||
|
if (screen) {
|
||||||
|
w = Math.max(w, screen.w)
|
||||||
|
items.push({ ...screen, x: (w - screen.w) / 2, y })
|
||||||
|
y += screen.h + 0.3
|
||||||
|
}
|
||||||
|
if (!items.length) return empty
|
||||||
return { items, w, h: y - 0.3 }
|
return { items, w, h: y - 0.3 }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pixels inside a component, drawn as one screen without gaps: every
|
||||||
|
* distinct column and row they sit on becomes a column and row of the
|
||||||
|
* screen, so they can be spaced out inside for wiring.
|
||||||
|
*/
|
||||||
|
export function screenLayout(def: ComponentDef): FaceItem | null {
|
||||||
|
const pixels = def.nodes.filter(n => n.kind === 'pixel')
|
||||||
|
if (!pixels.length) return null
|
||||||
|
const xs = [...new Set(pixels.map(n => n.x))].sort((a, b) => a - b)
|
||||||
|
const ys = [...new Set(pixels.map(n => n.y))].sort((a, b) => a - b)
|
||||||
|
const col = new Map(xs.map((x, i) => [x, i]))
|
||||||
|
const row = new Map(ys.map((y, i) => [y, i]))
|
||||||
|
const size = Math.max(xs.length, ys.length)
|
||||||
|
const px = size <= 8 ? 1 : size <= 32 ? 0.5 : 0.25
|
||||||
|
return {
|
||||||
|
id: pixels[0]!.id,
|
||||||
|
kind: 'screen',
|
||||||
|
label: '',
|
||||||
|
x: 0,
|
||||||
|
y: 0,
|
||||||
|
w: xs.length * px,
|
||||||
|
h: ys.length * px,
|
||||||
|
px,
|
||||||
|
pixels: pixels.map(n => ({ id: n.id, col: col.get(n.x)!, row: row.get(n.y)!, color: n.color })),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function gateShape(symbol: SymbolKind, inputs: { key: string; label: string }[], output: { key: string; label: string }): Shape {
|
function gateShape(symbol: SymbolKind, inputs: { key: string; label: string }[], output: { key: string; label: string }): Shape {
|
||||||
const n = inputs.length
|
const n = inputs.length
|
||||||
if (n === 1) {
|
if (n === 1) {
|
||||||
|
|
@ -174,6 +220,32 @@ const CLOCK_SHAPE: Shape = {
|
||||||
|
|
||||||
const MISSING_SHAPE: Shape = { body: { x: 0, y: -1, w: 4, h: 2 }, inputs: [], outputs: [] }
|
const MISSING_SHAPE: Shape = { body: { x: 0, y: -1, w: 4, h: 2 }, inputs: [], outputs: [] }
|
||||||
|
|
||||||
|
export const MAX_BITS = 32
|
||||||
|
|
||||||
|
/** Wires in a cable, within range. */
|
||||||
|
export function cableBits(node: CircuitNode): number {
|
||||||
|
const n = node.bits ?? 4
|
||||||
|
return Math.min(MAX_BITS, Math.max(2, Math.round(n)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Bundle: one input per wire on the left, the cable leaves on the right. Split: the mirror image. */
|
||||||
|
function cableShape(node: CircuitNode): Shape {
|
||||||
|
const n = cableBits(node)
|
||||||
|
const wires = Array.from({ length: n }, (_, i) => ({ key: `b${i}`, label: String(i), dy: i }))
|
||||||
|
const mid = Math.floor((n - 1) / 2)
|
||||||
|
const body = { x: 0, y: -0.5, w: 1, h: n }
|
||||||
|
if (node.kind === 'bundle') {
|
||||||
|
return { body, inputs: wires.map(p => ({ ...p, dx: 0 })), outputs: [{ key: 'q', label: '', dx: 1, dy: mid, bus: true }] }
|
||||||
|
}
|
||||||
|
return { body, inputs: [{ key: 'a', label: '', dx: 0, dy: mid, bus: true }], outputs: wires.map(p => ({ ...p, dx: 1 })) }
|
||||||
|
}
|
||||||
|
|
||||||
|
const PIXEL_SHAPE: Shape = {
|
||||||
|
body: { x: 0, y: -0.5, w: 1, h: 1 },
|
||||||
|
inputs: [{ key: 'a', label: '', dx: 0, dy: 0 }],
|
||||||
|
outputs: [],
|
||||||
|
}
|
||||||
|
|
||||||
/** Grid offset of every panel row below the first one. */
|
/** Grid offset of every panel row below the first one. */
|
||||||
export function panelOffsets(rows: PanelRow[]): number[] {
|
export function panelOffsets(rows: PanelRow[]): number[] {
|
||||||
const out: number[] = []
|
const out: number[] = []
|
||||||
|
|
@ -231,6 +303,11 @@ export function shapeOf(node: CircuitNode, getDef: DefLookup): Shape {
|
||||||
return HEX_SHAPE
|
return HEX_SHAPE
|
||||||
case 'panel':
|
case 'panel':
|
||||||
return panelShape(node)
|
return panelShape(node)
|
||||||
|
case 'bundle':
|
||||||
|
case 'split':
|
||||||
|
return cableShape(node)
|
||||||
|
case 'pixel':
|
||||||
|
return PIXEL_SHAPE
|
||||||
case 'note': {
|
case 'note': {
|
||||||
const lines = noteLines(node)
|
const lines = noteLines(node)
|
||||||
const k = noteScale(node)
|
const k = noteScale(node)
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,7 @@ function cleanNode(n: CircuitNode) {
|
||||||
if (n.key !== undefined && !(typeof n.key === 'string' && n.key.length === 1)) delete n.key
|
if (n.key !== undefined && !(typeof n.key === 'string' && n.key.length === 1)) delete n.key
|
||||||
if (n.size !== undefined && !['sm', 'md', 'lg'].includes(n.size)) delete n.size
|
if (n.size !== undefined && !['sm', 'md', 'lg'].includes(n.size)) delete n.size
|
||||||
if (n.autoLabel !== undefined && n.autoLabel !== true) delete n.autoLabel
|
if (n.autoLabel !== undefined && n.autoLabel !== true) delete n.autoLabel
|
||||||
|
if (n.bits !== undefined && !(Number.isInteger(n.bits) && n.bits >= 2 && n.bits <= 32)) delete n.bits
|
||||||
if (n.attach !== undefined && typeof n.attach !== 'string') delete n.attach
|
if (n.attach !== undefined && typeof n.attach !== 'string') delete n.attach
|
||||||
if (n.skip !== undefined) {
|
if (n.skip !== undefined) {
|
||||||
if (Array.isArray(n.skip)) n.skip = n.skip.filter(k => typeof k === 'string').slice(0, MAX_ROWS)
|
if (Array.isArray(n.skip)) n.skip = n.skip.filter(k => typeof k === 'string').slice(0, MAX_ROWS)
|
||||||
|
|
@ -66,9 +67,18 @@ export function toProject(data: unknown): Project {
|
||||||
...(p.settings?.tidy === true ? { tidy: true } : {}),
|
...(p.settings?.tidy === true ? { tidy: true } : {}),
|
||||||
},
|
},
|
||||||
solved: Array.isArray(p.solved) ? p.solved.filter(s => typeof s === 'string') : [],
|
solved: Array.isArray(p.solved) ? p.solved.filter(s => typeof s === 'string') : [],
|
||||||
|
...(bestOf(p.best) ? { best: bestOf(p.best)! } : {}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Challenge records: challenge id → fewest transistors, whole non-negative numbers only. */
|
||||||
|
function bestOf(raw: unknown): Record<string, number> | null {
|
||||||
|
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null
|
||||||
|
const out: Record<string, number> = {}
|
||||||
|
for (const [k, v] of Object.entries(raw)) if (typeof v === 'number' && Number.isInteger(v) && v >= 0 && k.length <= 64) out[k] = v
|
||||||
|
return Object.keys(out).length ? out : null
|
||||||
|
}
|
||||||
|
|
||||||
export function parseProject(json: string): Project {
|
export function parseProject(json: string): Project {
|
||||||
if (json.length > LIMITS.bytes) throw new Error('File too large')
|
if (json.length > LIMITS.bytes) throw new Error('File too large')
|
||||||
let data: unknown
|
let data: unknown
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,9 @@ export type BuiltinKind =
|
||||||
| 'hex' // 4-bit hex display
|
| 'hex' // 4-bit hex display
|
||||||
| 'note' // text annotation, no pins
|
| 'note' // text annotation, no pins
|
||||||
| 'panel' // column of switches, buttons and clocks, one output per row
|
| 'panel' // column of switches, buttons and clocks, one output per row
|
||||||
|
| 'bundle' // gathers several wires into one cable
|
||||||
|
| 'split' // fans a cable out into its wires again
|
||||||
|
| 'pixel' // one square of a screen; inside a component, pixels form a screen on its box
|
||||||
|
|
||||||
export type NodeKind = BuiltinKind | 'chip'
|
export type NodeKind = BuiltinKind | 'chip'
|
||||||
|
|
||||||
|
|
@ -40,6 +43,8 @@ export interface CircuitNode {
|
||||||
size?: NoteSize
|
size?: NoteSize
|
||||||
/** Set while the label was given automatically, so a new connection may rename it. */
|
/** Set while the label was given automatically, so a new connection may rename it. */
|
||||||
autoLabel?: boolean
|
autoLabel?: boolean
|
||||||
|
/** Number of wires in the cable of a bundle or split. */
|
||||||
|
bits?: number
|
||||||
/** Rows of a panel, top to bottom. */
|
/** Rows of a panel, top to bottom. */
|
||||||
rows?: PanelRow[]
|
rows?: PanelRow[]
|
||||||
/** Panel docked to a component: the id of that chip node. Its rows follow the chip's input pins. */
|
/** Panel docked to a component: the id of that chip node. Its rows follow the chip's input pins. */
|
||||||
|
|
@ -128,4 +133,6 @@ export interface Project {
|
||||||
settings: Settings
|
settings: Settings
|
||||||
/** Challenge ids the user has passed. */
|
/** Challenge ids the user has passed. */
|
||||||
solved: string[]
|
solved: string[]
|
||||||
|
/** Fewest transistors a passing solution used, per challenge id. */
|
||||||
|
best?: Record<string, number>
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,178 @@
|
||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import { nandCounts, shortCount, stats, TRANSISTORS_PER_NAND } from '../app/lib/logic/analyze'
|
||||||
|
import { bundleWires, cableOf, dissolveCable } from '../app/lib/logic/cables'
|
||||||
|
import { compile } from '../app/lib/logic/compile'
|
||||||
|
import { faceLayout, screenLayout, shapeOf } from '../app/lib/logic/geometry'
|
||||||
|
import { createProject, lookup, pruneWires } from '../app/lib/logic/ops'
|
||||||
|
import { toProject } from '../app/lib/logic/project'
|
||||||
|
import { Simulator } from '../app/lib/logic/sim'
|
||||||
|
import type { ComponentDef, Project } from '../app/lib/logic/types'
|
||||||
|
|
||||||
|
/** Four switches wired straight to four lamps. */
|
||||||
|
function lamps(): { p: Project; def: ComponentDef } {
|
||||||
|
const p = createProject({ examples: false })
|
||||||
|
const def: ComponentDef = {
|
||||||
|
id: 'root',
|
||||||
|
name: 'Root',
|
||||||
|
symbol: 'box',
|
||||||
|
nodes: [
|
||||||
|
...[0, 1, 2, 3].map(i => ({ id: `s${i}`, kind: 'input' as const, x: 0, y: i * 2, label: `S${i}` })),
|
||||||
|
...[0, 1, 2, 3].map(i => ({ id: `l${i}`, kind: 'lamp' as const, x: 30, y: 10 + i * 2 })),
|
||||||
|
],
|
||||||
|
wires: [0, 1, 2, 3].map(i => ({ id: `w${i}`, from: { node: `s${i}`, pin: 'q' }, to: { node: `l${i}`, pin: 'a' }, ...(i === 0 ? { color: 'blue' as const } : {}) })),
|
||||||
|
}
|
||||||
|
p.components.push(def)
|
||||||
|
return { p, def }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lamp values for every switch pattern, as strings like "1010". */
|
||||||
|
function behaviour(p: Project, def: ComponentDef): string[] {
|
||||||
|
const out: string[] = []
|
||||||
|
for (let m = 0; m < 16; m++) {
|
||||||
|
const s = new Simulator(compile(lookup(p), def.id))
|
||||||
|
for (let i = 0; i < 4; i++) s.setSource(`s${i}`, ((m >> i) & 1) === 1)
|
||||||
|
s.run()
|
||||||
|
out.push([0, 1, 2, 3].map(i => s.pin(`l${i}`, 'a')).join(''))
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('cables', () => {
|
||||||
|
it('bundling wires into a cable keeps every signal on its own wire', () => {
|
||||||
|
const { p, def } = lamps()
|
||||||
|
const before = behaviour(p, def)
|
||||||
|
const res = bundleWires(def, ['w0', 'w1', 'w2', 'w3'], lookup(p))
|
||||||
|
if (!res.ok) throw new Error(res.error)
|
||||||
|
expect(res.bundle.bits).toBe(4)
|
||||||
|
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')
|
||||||
|
// Both ends sit between sources and targets.
|
||||||
|
expect(res.bundle.x).toBeGreaterThan(2)
|
||||||
|
expect(res.split.x).toBeLessThan(30)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('takes a cable apart again into the same connections', () => {
|
||||||
|
const { p, def } = lamps()
|
||||||
|
const res = bundleWires(def, ['w0', 'w1', 'w2', 'w3'], lookup(p))
|
||||||
|
if (!res.ok) throw new Error(res.error)
|
||||||
|
const cable = def.wires.find(w => w.from.node === res.bundle.id)!
|
||||||
|
expect(cableOf(def, cable)?.id).toBe(res.bundle.id)
|
||||||
|
expect(dissolveCable(def, res.bundle.id)).toBe(4)
|
||||||
|
expect(def.nodes.some(n => n.kind === 'bundle' || n.kind === 'split')).toBe(false)
|
||||||
|
expect(def.wires.map(w => `${w.from.node}>${w.to.node}`).sort()).toEqual(['s0>l0', 's1>l1', 's2>l2', 's3>l3'])
|
||||||
|
expect(behaviour(p, def)).toEqual(behaviourOfFresh())
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a cable can fan out to two splits, and a narrower split takes the first wires', () => {
|
||||||
|
const { p, def } = lamps()
|
||||||
|
const res = bundleWires(def, ['w0', 'w1', 'w2', 'w3'], lookup(p))
|
||||||
|
if (!res.ok) throw new Error(res.error)
|
||||||
|
def.nodes.push({ id: 'sp2', kind: 'split', bits: 2, x: 20, y: 30 }, { id: 'x0', kind: 'lamp', x: 30, y: 30 }, { id: 'x1', kind: 'lamp', x: 30, y: 31 })
|
||||||
|
def.wires.push(
|
||||||
|
{ id: 'c2', from: { node: res.bundle.id, pin: 'q' }, to: { node: 'sp2', pin: 'a' } },
|
||||||
|
{ id: 'o0', from: { node: 'sp2', pin: 'b0' }, to: { node: 'x0', pin: 'a' } },
|
||||||
|
{ id: 'o1', from: { node: 'sp2', pin: 'b1' }, to: { node: 'x1', pin: 'a' } },
|
||||||
|
)
|
||||||
|
const s = new Simulator(compile(lookup(p), def.id))
|
||||||
|
s.setSource('s1', true)
|
||||||
|
s.run()
|
||||||
|
expect([s.pin('x0', 'a'), s.pin('x1', 'a')]).toEqual([0, 1])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('refuses one wire, and cables inside cables', () => {
|
||||||
|
const { p, def } = lamps()
|
||||||
|
expect(bundleWires(def, ['w0'], lookup(p)).ok).toBe(false)
|
||||||
|
const res = bundleWires(def, ['w0', 'w1'], lookup(p))
|
||||||
|
if (!res.ok) throw new Error(res.error)
|
||||||
|
const cable = def.wires.find(w => w.from.node === res.bundle.id)!
|
||||||
|
expect(bundleWires(def, [cable.id, 'w2'], lookup(p)).ok).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('narrowing a cable end drops the wires on pins that are gone', () => {
|
||||||
|
const { p, def } = lamps()
|
||||||
|
const res = bundleWires(def, ['w0', 'w1', 'w2', 'w3'], lookup(p))
|
||||||
|
if (!res.ok) throw new Error(res.error)
|
||||||
|
res.split.bits = 2
|
||||||
|
pruneWires(p)
|
||||||
|
expect(def.wires.filter(w => w.from.node === res.split.id).map(w => w.from.pin).sort()).toEqual(['b0', 'b1'])
|
||||||
|
expect(shapeOf(res.split, lookup(p)).outputs).toHaveLength(2)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
function behaviourOfFresh() {
|
||||||
|
const { p, def } = lamps()
|
||||||
|
return behaviour(p, def)
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('transistors', () => {
|
||||||
|
it('counts 4 per NAND through every level, the same as the compiled circuit', () => {
|
||||||
|
const p = createProject({ examples: true })
|
||||||
|
const counts = nandCounts(p.components)
|
||||||
|
for (const d of p.components) expect(counts.get(d.id), d.name).toBe(stats(compile(lookup(p), d.id)).nands)
|
||||||
|
expect(counts.get('ex-not')! * TRANSISTORS_PER_NAND).toBe(4)
|
||||||
|
expect(counts.get('ex-xor')! * TRANSISTORS_PER_NAND).toBe(16)
|
||||||
|
expect(counts.get('ex-fa')).toBeGreaterThan(counts.get('ex-ha')!)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not hang on a component that contains itself', () => {
|
||||||
|
const loop: ComponentDef = { id: 'a', name: 'A', symbol: 'box', nodes: [{ id: 'x', kind: 'chip', chip: 'a', x: 0, y: 0 }, { id: 'n', kind: 'nand', x: 0, y: 0 }], wires: [] }
|
||||||
|
expect(nandCounts([loop]).get('a')).toBe(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('shortens big numbers', () => {
|
||||||
|
expect(shortCount(36)).toBe('36')
|
||||||
|
expect(shortCount(1234)).toBe('1.2k')
|
||||||
|
expect(shortCount(56_000)).toBe('56k')
|
||||||
|
expect(shortCount(2_500_000)).toBe('2.5M')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps challenge records through validation and drops nonsense', () => {
|
||||||
|
const p = createProject({ examples: false })
|
||||||
|
const data = JSON.parse(JSON.stringify({ ...p, best: { xor: 16, and: -2, or: 'x', nor: 3.5 } }))
|
||||||
|
expect(toProject(data).best).toEqual({ xor: 16 })
|
||||||
|
expect(toProject(JSON.parse(JSON.stringify(p))).best).toBeUndefined()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('pixel screens', () => {
|
||||||
|
it('packs spaced-out pixels into one screen without gaps', () => {
|
||||||
|
const def: ComponentDef = {
|
||||||
|
id: 's',
|
||||||
|
name: 'S',
|
||||||
|
symbol: 'box',
|
||||||
|
nodes: [
|
||||||
|
{ id: 'a', kind: 'pixel', x: 10, y: 1 },
|
||||||
|
{ id: 'b', kind: 'pixel', x: 13, y: 1 },
|
||||||
|
{ id: 'c', kind: 'pixel', x: 10, y: 6, color: 'green' },
|
||||||
|
],
|
||||||
|
wires: [],
|
||||||
|
}
|
||||||
|
const screen = screenLayout(def)!
|
||||||
|
expect(screen.pixels).toEqual([
|
||||||
|
{ id: 'a', col: 0, row: 0, color: undefined },
|
||||||
|
{ id: 'b', col: 1, row: 0, color: undefined },
|
||||||
|
{ id: 'c', col: 0, row: 1, color: 'green' },
|
||||||
|
])
|
||||||
|
expect([screen.w, screen.h]).toEqual([2, 2])
|
||||||
|
expect(faceLayout(def).items.map(i => i.kind)).toEqual(['screen'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('the example screen shows what its inputs say, on the chip box', () => {
|
||||||
|
const p = createProject({ examples: true })
|
||||||
|
const get = lookup(p)
|
||||||
|
const demo = get('ex-demo-screen')!
|
||||||
|
const chip = demo.nodes.find(n => n.kind === 'chip')!
|
||||||
|
const shape = shapeOf(chip, get)
|
||||||
|
const face = shape.face!.find(f => f.kind === 'screen')!
|
||||||
|
expect(face.pixels).toHaveLength(16)
|
||||||
|
const s = new Simulator(compile(get, demo.id))
|
||||||
|
const panel = demo.nodes.find(n => n.kind === 'panel')!
|
||||||
|
for (const r of panel.rows!) s.setSource(`${panel.id}:${r.id}`, !!r.on)
|
||||||
|
s.run()
|
||||||
|
const lit = face.pixels!.map(px => s.face(chip.id, px.id, 'a'))
|
||||||
|
expect(lit.join('')).toBe('1001000010010110')
|
||||||
|
})
|
||||||
|
})
|
||||||
Loading…
Reference in New Issue