diff --git a/app/assets/css/main.css b/app/assets/css/main.css index ebeb885..d458c91 100644 --- a/app/assets/css/main.css +++ b/app/assets/css/main.css @@ -5689,3 +5689,115 @@ button.tile:hover { .face-thing.nested:not(.sel) { stroke-dasharray: 3 2; } + +/* Logic analyzer: above the bottom bar, as wide as it. */ +.analyzer { + position: absolute; + left: var(--bar-x); + width: var(--bar-w); + bottom: 76px; + z-index: 19; + display: flex; + flex-direction: column; + max-height: 40vh; + background: rgb(19 24 31 / 0.97); + border: 1px solid var(--border); + border-radius: 12px; + box-shadow: 0 10px 30px rgb(0 0 0 / 0.4); + font-size: 12px; +} + +.analyzer-head { + display: flex; + align-items: center; + gap: 8px; + padding: 6px 8px 6px 12px; + border-bottom: 1px solid var(--border); +} + +.analyzer-empty { + padding: 12px; +} + +.analyzer-body { + display: flex; + overflow-y: auto; + min-height: 0; +} + +.analyzer-names { + flex: none; + border-right: 1px solid var(--border); +} + +.analyzer-names li { + display: flex; + align-items: center; + gap: 6px; + padding: 0 4px 0 12px; + border-bottom: 1px solid rgb(37 46 58 / 0.5); +} + +.analyzer-names li > .truncate { + flex: 1; + min-width: 0; +} + +.analyzer-val { + color: var(--on); + font-family: var(--font-mono); + font-size: 11px; +} + +.analyzer-wave { + position: relative; + flex: 1; + min-width: 0; + overflow: hidden; + cursor: crosshair; +} + +.analyzer-wave svg { + display: block; +} + +.analyzer-bit { + fill: none; + stroke: var(--on); + stroke-width: 1.5; +} + +.analyzer-bus { + fill: var(--on-dim); + stroke: var(--on); + stroke-width: 1; +} + +.analyzer-bus-text { + fill: var(--text); + font-family: var(--font-mono); + font-size: 10px; +} + +.analyzer-mark { + stroke: var(--border); + stroke-width: 1; +} + +.analyzer-cursor { + stroke: var(--accent); + stroke-width: 1; +} + +.analyzer-cycle { + position: absolute; + right: 6px; + top: 2px; + color: var(--muted); + font-size: 10px; + pointer-events: none; +} + +.analyzer-head .hint { + margin: 0; +} diff --git a/app/components/editor/Analyzer.vue b/app/components/editor/Analyzer.vue new file mode 100644 index 0000000..0297c8a --- /dev/null +++ b/app/components/editor/Analyzer.vue @@ -0,0 +1,145 @@ + + + diff --git a/app/components/editor/App.vue b/app/components/editor/App.vue index 56a280c..bd6e6d3 100644 --- a/app/components/editor/App.vue +++ b/app/components/editor/App.vue @@ -45,6 +45,7 @@ watch( + diff --git a/app/components/editor/Canvas.vue b/app/components/editor/Canvas.vue index 8c86010..31e79a6 100644 --- a/app/components/editor/Canvas.vue +++ b/app/components/editor/Canvas.vue @@ -10,6 +10,7 @@ import { dropLinks, dropPins, fitStart, type DropPin } from '~/lib/logic/fit' import type { CanvasOps, MenuEntry } from '~/composables/useMenu' import { cableInUse, LANE, plugLayout, ribbon, RIBBON_MAX } from '~/lib/logic/cables' import { latchLayout, latchSeam } from '~/lib/logic/latch' +import { probeAt } from '~/lib/logic/probes' import { moveParts, moveStart, type MoveStart } from '~/lib/logic/move' import { wirePath, type HopSpan } from '~/lib/draw' import { downloadSheet, printSheet, sheetSvg } from '~/lib/sheet' @@ -1670,6 +1671,8 @@ function openMenuAt(target: Element, at: Pt, x: number, y: number) { const pull = endActions(n).find(x => x.key === 'pull') if (pull) here.push({ label: 'Pull the cable out', icon: pull.icon, run: () => pull.run(new PointerEvent('pointerdown')) }) } + const probe = p && !p.port ? probeAt(def.value, n, pin, dir, ed.getDef.value) : null + if (probe) here.push({ label: 'Watch in analyzer', icon: 'lucide:activity', run: () => ed.watchSignal(probe) }) if (dir === 'in' && ed.canInvert(n, pin)) { const on = n.invert?.includes(pin) here.push({ label: on ? 'Take the bubble off this input' : 'Invert this input', icon: 'lucide:circle-dot', keys: 'Alt+click', run: () => ed.toggleInvert(n, pin) }) diff --git a/app/components/editor/Toolbar.vue b/app/components/editor/Toolbar.vue index 212e10b..658f543 100644 --- a/app/components/editor/Toolbar.vue +++ b/app/components/editor/Toolbar.vue @@ -252,6 +252,9 @@ const moreEntries = computed(() => { + {{ ed.cycles.value.toLocaleString() }} ticks {{ statusText }} diff --git a/app/composables/useEditor.ts b/app/composables/useEditor.ts index f632cb7..ea3fc68 100644 --- a/app/composables/useEditor.ts +++ b/app/composables/useEditor.ts @@ -25,6 +25,7 @@ import { challengeName, challengeOpen, defUsable, isCampaign, KIND_NAMES, kindUn import { apiId, makePuzzle, scoreSolution, weekKey, weeklyId } from '~/lib/logic/puzzles' import { baseOf, MAX_GATE_INPUTS, NAND_BASE, wideGate } from '~/lib/logic/wide' import { CHALLENGES, challengeSteps, type Challenge } from '~/lib/logic/challenges' +import { probeValue } from '~/lib/logic/probes' import { latchedTo, latchInto, latchTarget, syncLatches } from '~/lib/logic/latch' import { cleanBundle, importBundle, importProblem, LIBRARY_LIMITS, libraryBundle, ownedEntry, publishProblem, type LibraryBundle, type LibraryMeta } from '~/lib/logic/library' import { compile, INVERTIBLE, invertedPins, rowSource } from '~/lib/logic/compile' @@ -80,7 +81,7 @@ import { type AccountUser, type ProjectMeta, } from '~/lib/logic/storage' -import type { CircuitNode, ComponentDef, ConnectorType, HeldState, LampColor, LibraryOrigin, NodeKind, PanelControl, PanelRow, PinRef, Project, PuzzleSpec, WireColor } from '~/lib/logic/types' +import type { CircuitNode, ComponentDef, ConnectorType, HeldState, LampColor, LibraryOrigin, NodeKind, Probe, PanelControl, PanelRow, PinRef, Project, PuzzleSpec, WireColor } from '~/lib/logic/types' /** A challenge check plus how many transistors the solution uses. */ /** How everyone did on a puzzle, from the server. */ @@ -541,6 +542,62 @@ function create() { } let raf = 0 + // ── Logic analyzer ──────────────────────────────────────────────── + /** The analyzer panel is open. */ + const analyzerOpen = ref(false) + /** What the watched signals were, oldest first: one sample per clock half-step, and on every other change. */ + const trace = shallowRef<{ cycle: number; vals: number[]; edge: boolean }[]>([]) + const traceVersion = ref(0) + const TRACE_MAX = 1000 + let traceKey = '' + + /** Takes a sample of the watched signals; without `edge`, only when one of them changed. */ + function sample(edge = false) { + const s = sim.value + const d = def.value + const ps = d.probes + if (!s || !ps?.length) return + // Other signals (or another circuit): start over. + const key = `${d.id}|${ps.map(p => `${p.node}:${p.pin}`).join(',')}` + if (key !== traceKey) { + traceKey = key + trace.value = [] + } + const vals = ps.map(p => probeValue(d, p, (n, pin) => s.pin(n, pin))) + const list = trace.value + const last = list[list.length - 1] + if (!edge && last && last.vals.every((v, i) => v === vals[i])) return + list.push({ cycle: cycles.value, vals, edge }) + if (list.length > TRACE_MAX) list.splice(0, list.length - TRACE_MAX) + traceVersion.value++ + } + + function clearTrace() { + trace.value = [] + traceVersion.value++ + sample(true) + } + + /** Watches a signal in the analyzer (and opens it). */ + function watchSignal(p: Probe | null) { + if (!p) return + const d = def.value + if (!(d.probes ?? []).some(x => x.node === p.node && x.pin === p.pin)) { + d.probes = [...(d.probes ?? []), { node: p.node, pin: p.pin }] + commit(false) + } + analyzerOpen.value = true + nextTick(() => sample(true)) + } + + function unwatch(i: number) { + const d = def.value + if (!d.probes) return + d.probes = d.probes.filter((_, k) => k !== i) + if (!d.probes.length) delete d.probes + commit(false) + } + function startLoop() { let lastT = performance.now() let acc: number[] = [] @@ -571,6 +628,7 @@ function create() { for (let k = 0; acc[i]! >= half && k < 16; k++) { acc[i]! -= half s.run(BUDGET) + sample(true) if (s.toggleClock(i) && i === counted) rises++ } if (acc[i]! > half) acc[i] = 0 @@ -590,6 +648,7 @@ function create() { status.value = settled ? 'stable' : unsettled > 30 ? 'oscillating' : 'busy' if (s.changes !== lastChanges) { lastChanges = s.changes + if (settled) sample() tick.value++ } } @@ -608,11 +667,14 @@ function create() { s.setClock(0) s.run(BUDGET) } + sample(true) s.setClock(1) s.run(BUDGET) cycles.value++ + sample(true) s.setClock(0) s.run(BUDGET) + sample(true) tick.value++ } @@ -2752,6 +2814,12 @@ function create() { val, faceVal, startLoop, + analyzerOpen, + trace, + traceVersion, + clearTrace, + watchSignal, + unwatch, step, rebuild, resetState, diff --git a/app/composables/useMenu.ts b/app/composables/useMenu.ts index d7ebab6..12e1317 100644 --- a/app/composables/useMenu.ts +++ b/app/composables/useMenu.ts @@ -7,6 +7,7 @@ import { cableInUse, cableOf } from '~/lib/logic/cables' import { INVERTIBLE } from '~/lib/logic/compile' import { cableBits, chipPins, portName, type Pt } from '~/lib/logic/geometry' import { SINK_KINDS, SOURCE_KINDS } from '~/lib/logic/ops' +import { probeAt, probeOfWire } from '~/lib/logic/probes' import { KIND_NAMES } from '~/lib/logic/progress' import { LAMP_COLORS, WIRE_COLORS, type CircuitNode, type NodeKind } from '~/lib/logic/types' import { baseOf, gateFamily, inputCount } from '~/lib/logic/wide' @@ -147,6 +148,11 @@ export function useMenu() { ) } if (n.kind === 'input') out.push({ label: n.on ? 'Switch off' : 'Switch on', icon: n.on ? 'lucide:toggle-right' : 'lucide:toggle-left', run: () => ed.toggleInput(n) }) + if (['input', 'button', 'clock', 'output', 'lamp'].includes(n.kind)) { + const dir = SOURCE_KINDS.includes(n.kind) ? 'out' : 'in' + const pin = dir === 'out' ? ed.shape(n).outputs[0]?.key : ed.shape(n).inputs[0]?.key + if (pin) out.push({ label: 'Watch in analyzer', icon: 'lucide:activity', run: () => ed.watchSignal(probeAt(ed.def.value, n, pin, dir, get)) }) + } if (NAMED.includes(n.kind)) out.push({ label: n.kind === 'note' ? 'Edit text' : 'Rename', icon: 'lucide:pencil', keys: 'Double-click', run: () => rename(n.id) }) const swaps = swapChoices([n]) if (swaps.length) out.push({ label: 'Change to', icon: 'lucide:replace', children: swaps }) @@ -420,6 +426,8 @@ export function useMenu() { { label: 'Place the ends yourself', icon: 'lucide:move', keys: 'Ctrl+Shift+G', run: () => ed.startCable() }, ) } + const signals = [...new Map(list.map(w => [`${w.from.node}:${w.from.pin}`, probeOfWire(w)])).values()] + if (signals.length <= 8) out.push({ label: 'Watch in analyzer', icon: 'lucide:activity', run: () => signals.forEach(p => ed.watchSignal(p)) }) if (list.length === 1) out.push({ label: 'Select the whole signal', icon: 'lucide:git-branch', keys: 'Double-click', run: () => ed.selectNet(list[0]!.id) }) const colors = new Set(list.map(w => w.color)) out.push({ diff --git a/app/lib/logic/probes.ts b/app/lib/logic/probes.ts new file mode 100644 index 0000000..67aa069 --- /dev/null +++ b/app/lib/logic/probes.ts @@ -0,0 +1,55 @@ +// The logic analyzer's signals: wires and cables of a circuit you watch. +// Each is a pin of a part there (an output, or an input's wire); a cable +// pin reads its whole cable as one number, wire 0 the lowest bit. + +import { cableBits, shapeOf, type DefLookup } from './geometry' +import { pinName } from './labels' +import type { CircuitNode, ComponentDef, Probe } from './types' + +/** How many bits a signal has: 1 for a wire, the cable's wires for a cable pin. */ +export function probeBits(def: ComponentDef, p: Probe): number { + const n = def.nodes.find(x => x.id === p.node) + if ((n?.kind === 'bundle' && p.pin === 'q') || (n?.kind === 'split' && p.pin === 'a')) return cableBits(n) + return 1 +} + +/** A signal's value now, read with \`pin(node, pin)\` (the simulator's). */ +export function probeValue(def: ComponentDef, p: Probe, pin: (node: string, pin: string) => number): number { + const n = def.nodes.find(x => x.id === p.node) + if (n && ((n.kind === 'bundle' && p.pin === 'q') || (n.kind === 'split' && p.pin === 'a'))) { + // A cable: its wires as they leave the bundle (a split reads the bundle that feeds it). + const bundle = n.kind === 'bundle' ? n : def.nodes.find(x => x.id === def.wires.find(w => w.to.node === n.id && w.to.pin === 'a')?.from.node) + if (!bundle || bundle.kind !== 'bundle') return 0 + let v = 0 + for (let i = 0; i < cableBits(n); i++) if (pin(bundle.id, `b${i}`)) v += 2 ** i + return v + } + return pin(p.node, p.pin) +} + +/** What a signal is called: its own name, else the pin's or the part's. */ +export function probeName(def: ComponentDef, p: Probe, get: DefLookup): string { + if (p.label?.trim()) return p.label.trim() + const n = def.nodes.find(x => x.id === p.node) + if (!n) return '?' + const own = n.label?.trim() && !n.autoLabel ? n.label.trim() : '' + const pin = pinName(n, p.pin, get) + const part = own || (n.kind === 'chip' ? (n.chip && get(n.chip)?.name) || 'Component' : n.kind) + if (n.kind === 'bundle' || n.kind === 'split') return own || `Cable ${probeBits(def, p)}` + if (['input', 'button', 'clock', 'output', 'lamp'].includes(n.kind)) return own || part + return pin ? `${part} ${pin}` : part +} + +/** The signal a wire carries: the pin it comes from. */ +export const probeOfWire = (w: { from: { node: string; pin: string } }): Probe => ({ node: w.from.node, pin: w.from.pin }) + +/** + * The signal at a pin: an output itself, an input by the wire into it (or, + * with none, the pin, which reads 0). + */ +export function probeAt(def: ComponentDef, node: CircuitNode, pin: string, dir: 'in' | 'out', get: DefLookup): Probe | null { + if (dir === 'out') return { node: node.id, pin } + const w = def.wires.find(x => x.to.node === node.id && x.to.pin === pin) + if (w) return probeOfWire(w) + return shapeOf(node, get).inputs.some(p => p.key === pin) ? { node: node.id, pin } : null +} diff --git a/app/lib/logic/project.ts b/app/lib/logic/project.ts index e2739f0..b2cec6f 100644 --- a/app/lib/logic/project.ts +++ b/app/lib/logic/project.ts @@ -143,6 +143,11 @@ export function toProject(data: unknown): Project { if (d.wide !== undefined && !(d.wide && typeof d.wide.base === 'string' && Number.isInteger(d.wide.n) && d.wide.n >= 2 && d.wide.n <= 16)) delete d.wide if (d.design !== undefined) cleanDesign(d) if (d.from !== undefined) cleanOrigin(d) + if (d.probes !== undefined) { + d.probes = Array.isArray(d.probes) ? d.probes.filter(p => p && typeof p.node === 'string' && typeof p.pin === 'string').slice(0, 64) : [] + for (const p of d.probes) if (p.label !== undefined && typeof p.label !== 'string') delete p.label + if (!d.probes.length) delete d.probes + } for (const n of d.nodes) cleanNode(n) for (const w of d.wires) if (w.color && !WIRE_COLORS.includes(w.color)) delete w.color for (const w of d.wires) if (w.pts !== undefined && !cornersOk(w.pts)) delete w.pts diff --git a/app/lib/logic/types.ts b/app/lib/logic/types.ts index 1aedc77..ac59f23 100644 --- a/app/lib/logic/types.ts +++ b/app/lib/logic/types.ts @@ -145,6 +145,16 @@ export interface ComponentDef { design?: FaceDesign /** Set when the component came from the public library (or was published there from here). */ from?: LibraryOrigin + /** Signals watched in the logic analyzer, top to bottom. */ + probes?: Probe[] +} + +/** A signal watched in the logic analyzer: a pin of a part (a cable pin reads the whole cable). */ +export interface Probe { + node: string + pin: string + /** A name of its own for the analyzer. */ + label?: string } /** Where a component of the public library came from: the entry, its version and who published it. */ diff --git a/tests/probes.test.ts b/tests/probes.test.ts new file mode 100644 index 0000000..457adde --- /dev/null +++ b/tests/probes.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it } from 'vitest' +import { bundleWires } from '../app/lib/logic/cables' +import { compile } from '../app/lib/logic/compile' +import { createProject, lookup } from '../app/lib/logic/ops' +import { probeAt, probeBits, probeName, probeOfWire, probeValue } from '../app/lib/logic/probes' +import { toProject } from '../app/lib/logic/project' +import { Simulator } from '../app/lib/logic/sim' +import type { ComponentDef } from '../app/lib/logic/types' + +/** Four switches into a cable, the cable to four lamps. */ +function setup() { + 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' } })), + } + p.components.push(def) + const res = bundleWires(def, ['w0', 'w1', 'w2', 'w3'], lookup(p)) + if (!res.ok) throw new Error(res.error) + return { p, def } +} + +describe('analyzer signals', () => { + it('a cable reads as one number, wire 0 the lowest bit; a wire as 0 or 1', () => { + const { p, def } = setup() + const s = new Simulator(compile(lookup(p), def.id)) + s.setSource('s0', true) + s.setSource('s2', true) + s.run() + const cable = def.wires.find(w => def.nodes.find(n => n.id === w.from.node)?.kind === 'bundle')! + const cp = probeOfWire(cable) + expect(probeBits(def, cp)).toBe(4) + expect(probeValue(def, cp, (n, pin) => s.pin(n, pin))).toBe(5) + const lamp = def.nodes.find(n => n.id === 'l2')! + const lp = probeAt(def, lamp, 'a', 'in', lookup(p))! + expect(probeBits(def, lp)).toBe(1) + expect(probeValue(def, lp, (n, pin) => s.pin(n, pin))).toBe(1) + expect(probeName(def, { node: 's1', pin: 'q' }, lookup(p))).toBe('S1') + expect(probeName(def, cp, lookup(p))).toBe('Cable 4') + }) + + it('watched signals are saved with the circuit and survive loading', () => { + const { p, def } = setup() + def.probes = [{ node: 's0', pin: 'q' }, { node: 'x', pin: 'q', label: 'mine' }] + const back = toProject(JSON.parse(JSON.stringify(p)))! + expect(back.components.find(c => c.id === 'root')!.probes).toEqual(def.probes) + }) +})