logigate/app/lib/logic/examples.ts

314 lines
13 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Example library: every part below is built from NAND gates only, then
// reused as a chip by the next one (NOT → AND → … → 4-bit counter).
// Coordinates are grid units, hand-placed so the wiring reads cleanly.
import { chipPins } from './geometry'
import type { CircuitNode, ComponentDef, PinRef, SymbolKind } from './types'
type Pt = [number, number]
export type Src = PinRef & { pts?: Pt[] }
/** Route a wire through corner points. */
export const via = (src: Src, ...pts: Pt[]): Src => ({ ...src, pts })
export class Builder {
readonly def: ComponentDef
private seq = 0
constructor(
private lib: Map<string, ComponentDef>,
init: { id: string; name: string; symbol?: SymbolKind; group?: string; description?: string },
) {
this.def = { symbol: 'box', ...init, nodes: [], wires: [] }
}
private add(node: Omit<CircuitNode, 'id'>): string {
const id = `n${++this.seq}`
this.def.nodes.push({ id, ...node })
return id
}
link(from: Src, to: PinRef) {
const wire: ComponentDef['wires'][number] = { id: `w${++this.seq}`, from: { node: from.node, pin: from.pin }, to }
if (from.pts) wire.pts = from.pts
this.def.wires.push(wire)
}
input(label: string, x: number, y: number): Src {
return { node: this.add({ kind: 'input', x, y, label }), pin: 'q' }
}
output(label: string, x: number, y: number, src?: Src) {
const id = this.add({ kind: 'output', x, y, label })
if (src) this.link(src, { node: id, pin: 'a' })
return id
}
nand(x: number, y: number, a?: Src, b?: Src): Src {
const id = this.add({ kind: 'nand', x, y })
if (a) this.link(a, { node: id, pin: 'a' })
if (b) this.link(b, { node: id, pin: 'b' })
return { node: id, pin: 'q' }
}
/** Place a library part; inputs and returned outputs follow its pin order. */
chip(chipId: string, x: number, y: number, ...ins: (Src | undefined)[]): Src[] {
const def = this.lib.get(chipId)
if (!def) throw new Error(`Unknown part ${chipId}`)
const pins = chipPins(def)
const id = this.add({ kind: 'chip', chip: chipId, x, y })
ins.forEach((src, i) => {
const pin = pins.inputs[i]
if (src && pin) this.link(src, { node: id, pin: pin.key })
})
return pins.outputs.map(p => ({ node: id, pin: p.key }))
}
source(kind: 'high' | 'low' | 'clock' | 'button', x: number, y: number, label?: string): Src {
return { node: this.add({ kind, x, y, label }), pin: 'q' }
}
hex(x: number, y: number, bits: Src[], label?: string) {
const id = this.add({ kind: 'hex', x, y, label })
bits.forEach((src, i) => this.link(src, { node: id, pin: `b${i}` }))
}
lamp(x: number, y: number, src: Src, label?: string) {
const id = this.add({ kind: 'lamp', x, y, label })
this.link(src, { node: id, pin: 'a' })
}
note(x: number, y: number, text: string) {
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[] {
const lib = new Map<string, ComponentDef>()
const make = (init: ConstructorParameters<typeof Builder>[1], build: (b: Builder) => void) => {
const b = new Builder(lib, init)
build(b)
lib.set(b.def.id, b.def)
}
make({ id: 'ex-not', name: 'NOT', symbol: 'not', group: 'Gates', description: 'Inverter: a NAND with both inputs tied together.' }, b => {
const A = b.input('A', 0, 1)
b.output('Q', 11, 1, b.nand(5, 0, A, A))
})
make({ id: 'ex-and', name: 'AND', symbol: 'and', group: 'Gates', description: 'NAND followed by NOT.' }, b => {
const A = b.input('A', 0, 0)
const B = b.input('B', 0, 2)
const [q] = b.chip('ex-not', 11, 1, b.nand(5, 0, A, B))
b.output('Q', 16, 1, q)
})
make({ id: 'ex-or', name: 'OR', symbol: 'or', group: 'Gates', description: 'De Morgan: NAND of the inverted inputs.' }, b => {
const A = b.input('A', 0, 0)
const B = b.input('B', 0, 4)
const [na] = b.chip('ex-not', 5, 0, A)
const [nb] = b.chip('ex-not', 5, 4, B)
b.output('Q', 17, 2, b.nand(11, 1, na, nb))
})
make({ id: 'ex-nor', name: 'NOR', symbol: 'nor', group: 'Gates', description: 'OR followed by NOT.' }, b => {
const A = b.input('A', 0, 0)
const B = b.input('B', 0, 2)
const [o] = b.chip('ex-or', 5, 0, A, B)
const [q] = b.chip('ex-not', 11, 1, o)
b.output('Q', 16, 1, q)
})
make({ id: 'ex-xor', name: 'XOR', symbol: 'xor', group: 'Gates', description: 'Exclusive OR from four NANDs: 1 when exactly one input is 1.' }, b => {
const A = b.input('A', 0, 1)
const B = b.input('B', 0, 7)
const n1 = b.nand(5, 3, A, B)
const n2 = b.nand(12, 1, A, n1)
const n3 = b.nand(12, 5, n1, B)
b.output('Q', 25, 4, b.nand(19, 3, n2, n3))
})
make({ id: 'ex-xnor', name: 'XNOR', symbol: 'xnor', group: 'Gates', description: 'XOR followed by NOT: 1 when both inputs are equal.' }, b => {
const A = b.input('A', 0, 0)
const B = b.input('B', 0, 2)
const [x] = b.chip('ex-xor', 5, 0, A, B)
const [q] = b.chip('ex-not', 11, 1, x)
b.output('Q', 16, 1, q)
})
make({ id: 'ex-mux', name: 'Mux', group: 'Routing', description: 'Selector: Q = A when S is 0, Q = B when S is 1.' }, b => {
const A = b.input('A', 0, 0)
const B = b.input('B', 0, 4)
const S = b.input('S', 0, 8)
const [ns] = b.chip('ex-not', 4, 8, S)
const n1 = b.nand(10, 0, A, ns)
const n2 = b.nand(10, 4, B, via(S, [3, 8], [3, 6]))
b.output('Q', 23, 3, b.nand(17, 2, n1, n2))
})
make({ id: 'ex-ha', name: 'Half Adder', group: 'Arithmetic', description: 'Adds two bits: S is the sum bit, C the carry.' }, b => {
const A = b.input('A', 0, 0)
const B = b.input('B', 0, 2)
const [s] = b.chip('ex-xor', 6, 0, A, B)
const [c] = b.chip('ex-and', 6, 5, via(A, [3, 0], [3, 5]), via(B, [4, 2], [4, 7]))
b.output('S', 13, 1, s)
b.output('C', 13, 6, c)
})
make({ id: 'ex-fa', name: 'Full Adder', group: 'Arithmetic', description: 'Adds three bits (A, B and carry in) with two half adders.' }, b => {
const A = b.input('A', 0, 0)
const B = b.input('B', 0, 2)
const Cin = b.input('Cin', 0, 6)
const [s1, c1] = b.chip('ex-ha', 5, 0, A, B)
const [s2, c2] = b.chip('ex-ha', 16, 3, s1, Cin)
const [c] = b.chip('ex-or', 26, 5, via(c1!, [15, 1], [15, 5]), c2)
b.output('S', 33, 3, s2)
b.output('Cout', 33, 6, c)
})
make({ id: 'ex-sr', name: 'SR Latch', group: 'Memory', description: 'Stores one bit. S sets Q to 1, R resets it to 0; with both at 0 it remembers.' }, b => {
const S = b.input('S', 0, 0)
const R = b.input('R', 0, 7)
const [ns] = b.chip('ex-not', 4, 0, S)
const [nr] = b.chip('ex-not', 4, 7, R)
// The Q̄ gate goes first: the simulator settles gates in the order they
// were placed, so the latch (and every memory built on it) starts at 0.
const n2 = b.nand(10, 5)
const n1 = b.nand(10, 0, ns, via(n2, [15, 6], [15, 4], [8, 4], [8, 2]))
b.link(via(n1, [16, 1], [16, 3], [9, 3], [9, 5]), { node: n2.node, pin: 'a' })
b.link(nr!, { node: n2.node, pin: 'b' })
b.output('Q', 19, 1, n1)
b.output('Q̄', 19, 6, n2)
})
make({ id: 'ex-dlatch', name: 'D Latch', group: 'Memory', description: 'While E is 1, Q follows D. When E drops to 0, Q keeps the last value.' }, b => {
const D = b.input('D', 0, 0)
const E = b.input('E', 0, 4)
const [s] = b.chip('ex-and', 8, 0, D, E)
const [nd] = b.chip('ex-not', 4, 8, D)
const [r] = b.chip('ex-and', 8, 6, E, nd)
const [q, nq] = b.chip('ex-sr', 15, 1, s, r)
b.output('Q', 25, 1, q)
b.output('Q̄', 25, 3, nq)
})
make({ id: 'ex-dff', name: 'D Flip-Flop', group: 'Memory', description: 'Takes over D at the rising edge of CLK and holds it until the next rising edge. Two D latches (master, slave).' }, b => {
const D = b.input('D', 0, 0)
const CLK = b.input('CLK', 0, 4)
const [nclk] = b.chip('ex-not', 5, 4, CLK)
const [mq] = b.chip('ex-dlatch', 11, 0, D, nclk)
const [q, nq] = b.chip('ex-dlatch', 21, 0, mq, via(CLK, [3, 6], [19, 6]))
b.output('Q', 30, 0, q)
b.output('Q̄', 30, 2, nq)
})
make({ id: 'ex-reg4', name: 'Register 4', group: 'Memory', description: 'Four D flip-flops on one clock: stores a 4-bit number.' }, b => {
const D = [0, 1, 2, 3].map(i => b.input(`D${i}`, 0, 4 * i))
const CLK = b.input('CLK', 0, 16)
D.forEach((d, i) => {
const [q] = b.chip('ex-dff', 6, 4 * i, d, CLK)
b.output(`Q${i}`, 18, 4 * i, q)
})
})
make({ id: 'ex-inc4', name: 'Increment 4', group: 'Arithmetic', description: 'Adds 1 to a 4-bit number with a chain of half adders.' }, b => {
const A = [0, 1, 2, 3].map(i => b.input(`A${i}`, 0, 4 * i))
let carry = b.source('high', 3, 1)
A.forEach((a, i) => {
const [s, c] = b.chip('ex-ha', 6 + 9 * i, 4 * i, a, carry)
b.output(`S${i}`, 43, 4 * i, s)
carry = c!
})
b.output('Cout', 43, 16, carry)
})
make({ id: 'ex-add4', name: 'Adder 4', group: 'Arithmetic', description: 'Adds two 4-bit numbers with four full adders (ripple carry).' }, b => {
const A = [0, 1, 2, 3].map(i => b.input(`A${i}`, 0, 2 * i))
const B = [0, 1, 2, 3].map(i => b.input(`B${i}`, 0, 8 + 2 * i))
let carry: Src = via(b.input('Cin', 0, 16), [13, 16], [13, 22])
for (let i = 0; i < 4; i++) {
const y = 20 + 4 * i
const [s, c] = b.chip('ex-fa', 14, y, via(A[i]!, [3 + i, 2 * i], [3 + i, y]), via(B[i]!, [8 + i, 8 + 2 * i], [8 + i, y + 1]), carry)
b.output(`S${i}`, 28, y, s)
carry = i < 3 ? via(c!, [24, y + 1], [24, y + 3], [12, y + 3], [12, y + 6]) : c!
}
b.output('Cout', 28, 36, carry)
})
make({ id: 'ex-cnt4', name: 'Counter 4', group: 'Memory', description: 'Counts 0 to 15 on each rising clock edge. RST = 1 sets it back to 0 at the next edge. Its display shows on the box.' }, b => {
const CLK = b.input('CLK', 0, 21)
const RST = b.input('RST', 0, 24)
const inc = b.chip('ex-inc4', 6, 0)
const [nrst] = b.chip('ex-not', 4, 24, RST)
const ands = [0, 1, 2, 3].map(i => {
const [q] = b.chip('ex-and', 22, 5 * i, i === 0 ? inc[0] : via(inc[i]!, [16 + i, i], [16 + i, 5 * i]), via(nrst!, [20, 24], [20, 5 * i + 2]))
return via(q!, [27 + i, 5 * i + 1], [27 + i, i])
})
const Q = b.chip('ex-reg4', 32, 0, ...ands, via(CLK, [31, 21], [31, 4]))
const incNode = inc[0]!.node
const incIns = chipPins(lib.get('ex-inc4')!).inputs
Q.forEach((q, i) => {
b.link(via(q, [41 + i, i], [41 + i, -1 - i], [5 - i, -1 - i], [5 - i, i]), { node: incNode, pin: incIns[i]!.key })
b.output(`Q${i}`, 52, 2 * i, i === 0 ? q : via(q, [50 - i, i], [50 - i, 2 * i]))
})
// Shows on the Counter 4 box wherever the counter is used.
b.hex(47, 8, Q.map((q, i) => via(q, [41 + i, i], [41 + i, 8 + i])), 'count')
})
make({ id: 'ex-demo-counter', name: 'Demo: Counter', group: 'Demos', description: 'A clock drives the 4-bit counter; the hex display shows the count.' }, b => {
b.note(0, -3, 'The clock drives a 4-bit counter.\nHold Reset during a tick to go back to 0.')
const clk = b.source('clock', 0, 2)
const rst = b.source('button', 0, 6, 'Reset')
const Q = b.chip('ex-cnt4', 8, 2, clk, rst)
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()]
}
export function starterCircuit(): ComponentDef {
const b = new Builder(new Map(), { id: 'main', name: 'Main' })
b.note(0, -4, 'Click a switch to flip it. NAND is the only gate:\nbuild the rest from it and save them as components.')
const A = b.input('A', 0, 0)
const B = b.input('B', 0, 2)
b.lamp(12, 1, b.nand(5, 0, A, B))
return b.def
}