diff --git a/src/common/bits.ts b/src/common/bits.ts new file mode 100644 index 0000000..ad3a300 --- /dev/null +++ b/src/common/bits.ts @@ -0,0 +1,13 @@ +import type { SimulationValue } from "../store/simulation"; + +/** `value` in `width` bits, the most significant first, as in `SimulationValue` */ +export function bitsOf(value: number, width: number): SimulationValue { + return Array.from( + { length: width }, + (_, i) => ((value >> (width - 1 - i)) & 1) === 1, + ); +} + +export function numberOf(bits: SimulationValue): number { + return bits.reduce((value, bit) => value * 2 + (bit ? 1 : 0), 0); +} diff --git a/src/components/TruthTableView.tsx b/src/components/TruthTableView.tsx index 7cd6869..75f0630 100644 --- a/src/components/TruthTableView.tsx +++ b/src/components/TruthTableView.tsx @@ -2,13 +2,16 @@ import { Box, type Theme } from "@mui/material"; import { useContext } from "react"; import { bitDigit, bitLabel } from "../common/bitLabel"; import type { TruthTable } from "../store/intrinsics/truthTable"; +import type { SimulationValue } from "../store/simulation"; import { theme } from "../style"; import { BitNotationContext } from "./bitNotation"; const divider = (muiTheme: Theme) => `1px solid ${muiTheme.palette.divider}`; +const onSx = { color: theme.colors.primary, fontWeight: "bold" } as const; +const binaryOf = (value: SimulationValue) => value.map(bitDigit).join(""); export function TruthTableView({ table }: { table: TruthTable }) { - const labelOf = + const singleBitLabel = useContext(BitNotationContext) === "digits" ? bitDigit : bitLabel; const columns = [ ...table.inputs.map((name) => ({ key: `in-${name}`, name })), @@ -26,7 +29,11 @@ export function TruthTableView({ table }: { table: TruthTable }) { return ( @@ -43,20 +50,19 @@ export function TruthTableView({ table }: { table: TruthTable }) { {table.rows.map((row) => ( - + {[...row.inputs, ...row.outputs].map((value, i) => ( - - {labelOf(value)} + + {value.map((bit, index) => ( + + {value.length === 1 ? singleBitLabel(bit) : bitDigit(bit)} + + ))} ))} diff --git a/src/i18n/en.ts b/src/i18n/en.ts index ff6dd0c..d4923a9 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -6,6 +6,7 @@ const listOf = (names: readonly string[]) => names.length < 2 ? names.join("") : `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`; +const digits = (count: number) => (count === 1 ? "1 digit" : `${count} digits`); const themOf = (names: readonly string[]) => names.length === 1 ? "it" : "them"; @@ -14,7 +15,7 @@ type StageTexts = { title: string; goal: string; steps: readonly string[] }; const stageTexts: Record = { and: { title: "Both switches", - goal: "Make the lamp Out light up only when both switches A and B are ON. The stage is cleared when the circuit works as in the table below.", + goal: "Make the lamp Out turn ON only when both switches A and B are ON. The stage is cleared when the circuit works as in the table below.", steps: [ "Pick a part in the Parts list and drag it onto the editor on the right.", "The small squares on the edges of a part are its pins. A pin on the left side is an input, which receives ON or OFF, and a pin on the right side is an output, which sends ON or OFF. Drag between an output pin and an input pin to connect them with a wire.", @@ -25,12 +26,12 @@ const stageTexts: Record = { }, "a-only": { title: "Only switch A", - goal: "Make the lamp Out light up only when switch A is ON and B is OFF. This time, one part alone is not enough.", + goal: "Make the lamp Out turn ON only when switch A is ON and B is OFF. This time, one part alone is not enough.", steps: [], }, xor: { title: "Only one switch", - goal: 'Make the lamp Out light up when exactly one of the switches A and B is ON. It does not light up when both are ON. "Only switch A" is ready to use as a part.', + goal: 'Make the lamp Out turn ON when exactly one of the switches A and B is ON. It stays OFF when both are ON. "Only switch A" is ready to use as a part.', steps: [], }, "half-adder": { @@ -43,6 +44,16 @@ const stageTexts: Record = { goal: 'Output A + B + Cin as a two-digit binary number to C and S. Cin is the carry coming up from the next lower digit. The answer is 0 to 3, and 3 is 11 in binary. "Adding one digit" is ready to use as a part: add A and B with one, then add Cin to its S with another. This circuit is called a full adder.', steps: [], }, + "four-bit-adder": { + title: "Adding four digits", + goal: "A and B are four-digit binary numbers. Output A + B in four digits to S, and its fifth digit, the sixteens digit, to C: C is 1 when A + B is 16 or more. The table shows some examples.", + steps: [ + 'Place four "Adding with a carry". From the top, the pins on the right of Decompose and on the left of Aggregate are the eights, fours, twos and ones digits.', + "For each digit, connect that digit's pin on the upper Decompose, which A goes into, and on the lower one, which B goes into, to the A and B of one \"Adding with a carry\". Connect the S of that adder to the same digit's pin of Aggregate.", + "Connect the C of each digit's adder to the Cin of the adder one digit up. The ones digit's adder gets False on its Cin, and the C of the eights digit's adder goes to the output C on the right.", + "While playing, click a digit of A or B to switch it between 0 and 1. The sum S is shown as one character on the Display at the top right. The 7seg before it turns the binary number into the shape of a numeral. To write 10 to 15 with one character, A (10), b (11), C (12), d (13), E (14) and F (15) are used. This way of writing is called hexadecimal.", + ], + }, }; export const en = { @@ -62,6 +73,10 @@ export const en = { XOR: "ON when exactly one input is ON", TRUE: "Always ON", FALSE: "Always OFF", + DECOMPOSE: + "Splits a number of several digits, from the highest digit down", + AGGREGATE: + "Joins values into one number, the upper pins as the higher digits", }, about: (name: string) => `About ${name}`, ofStage: "Available parts", @@ -152,6 +167,8 @@ export const en = { backToStages: "Back to the stages", missingPin: (pinType: "input" | "output", pinName: string) => `There is no ${pinType} pin named ${pinName}. "Reset this stage" brings back how the stage started.`, + wrongBitWidth: (pinName: string, expected: number, actual: number) => + `${pinName} should have ${digits(expected)}, but it has ${digits(actual)}. Check what it is connected to.`, wrongOutput: ( inputs: readonly { name: string; value: string }[], pinName: string, @@ -159,6 +176,8 @@ export const en = { actual: string | null, ) => `When ${listOf(inputs.map(({ name, value }) => `${name} is ${value}`))}, ${pinName} should be ${expected}, but it ${actual === null ? "has no value" : `is ${actual}`}.`, + checkFailed: + "Something went wrong while checking. Change the circuit a little and press Check again.", simulationFailed: (detail: string) => `The circuit could not be simulated. ${detail}`, resetStage: "Reset this stage", diff --git a/src/i18n/ja.ts b/src/i18n/ja.ts index ab50e73..1c8c72f 100644 --- a/src/i18n/ja.ts +++ b/src/i18n/ja.ts @@ -21,6 +21,8 @@ export const ja: Messages = { XOR: "片方だけが ON のとき ON", TRUE: "いつも ON", FALSE: "いつも OFF", + DECOMPOSE: "何桁もある数を、上の桁から順に分ける", + AGGREGATE: "上のピンを大きい桁として、1つの数にまとめる", }, about: (name) => `${name} について`, ofStage: "使える部品", @@ -110,8 +112,12 @@ export const ja: Messages = { backToStages: "課題の一覧へ", missingPin: (pinType, pinName) => `${pinName} という名前の${pinType === "input" ? "入力" : "出力"}ピンが見つかりません。「この課題をやり直す」で最初の状態に戻せます。`, + wrongBitWidth: (pinName, expected, actual) => + `${pinName} は ${expected}桁のはずですが、${actual}桁になっています。つないだ先を確かめてください。`, wrongOutput: (inputs, pinName, expected, actual) => `${inputs.map(({ name, value }) => `${name} が ${value}`).join("、")} のとき、${pinName} は ${expected} になるはずが、${actual === null ? "値がありませんでした" : `${actual} でした`}。`, + checkFailed: + "確かめる途中で問題が起きました。回路を少し変えてから、もう一度押してください。", simulationFailed: (detail) => `回路をシミュレーションできませんでした。${detail}`, resetStage: "この課題をやり直す", @@ -124,7 +130,7 @@ export const ja: Messages = { stageTexts: { and: { title: "両方のスイッチ", - goal: "スイッチ A と B が両方 ON のときだけ、ランプ Out がつくようにしましょう。下の表のとおりに動けばクリアです。", + goal: "スイッチ A と B が両方 ON のときだけ、ランプ Out が ON になるようにしましょう。下の表のとおりに動けばクリアです。", steps: [ "「部品」の一覧から部品を選び、右のエディタにドラッグして置きます。", "部品の端にある小さな四角を「ピン」といいます。左側のピンは ON か OFF を受け取る「入力」、右側のピンは ON か OFF を送り出す「出力」です。出力のピンと入力のピンのあいだをドラッグして、線でつなぎます。", @@ -135,24 +141,34 @@ export const ja: Messages = { }, "a-only": { title: "A だけのスイッチ", - goal: "スイッチ A が ON で、B が OFF のときだけ、ランプ Out がつくようにしましょう。今度は、部品を1つ置くだけではできません。", + goal: "スイッチ A が ON で、B が OFF のときだけ、ランプ Out が ON になるようにしましょう。今度は、部品を1つ置くだけではできません。", steps: [], }, xor: { title: "片方だけのスイッチ", - goal: "スイッチ A と B のどちらか片方だけが ON のときに、ランプ Out がつくようにしましょう。両方 ON のときはつきません。「A だけのスイッチ」を部品として使えます。", + goal: "スイッチ A と B のどちらか片方だけが ON のときに、ランプ Out が ON になるようにしましょう。両方 ON のときは OFF です。「A だけのスイッチ」を部品として使えます。", steps: [], }, "half-adder": { - title: "1けたの足し算", - goal: "ここからは ON を 1、OFF を 0 と考え、表もそう書きます。すると、A+B は 0、1、2 のどれかです。2進数では、0 と 1 だけで数を書きます。ふだんの数で 9+1 が繰り上がって 10 になるように、2進数では 1+1 が繰り上がって 10 になります。そのため、0、1、2 は2けたで 00、01、10 です。左のけた(2の位)を C に、右のけた(1の位)を S に出しましょう。C を「桁上がり」、S を「和」といい、この回路を「半加算器」といいます。", + title: "1桁の足し算", + goal: "ここからは ON を 1、OFF を 0 と考え、表もそう書きます。すると、A+B は 0、1、2 のどれかです。2進数では、0 と 1 だけで数を書きます。ふだんの数で 9+1 が繰り上がって 10 になるように、2進数では 1+1 が繰り上がって 10 になります。そのため、0、1、2 は2桁で 00、01、10 です。左の桁(2の位)を C に、右の桁(1の位)を S に出しましょう。C を「桁上がり」、S を「和」といい、この回路を「半加算器」といいます。", steps: [], }, "full-adder": { title: "桁上がりつきの足し算", - goal: "A+B+Cin の答えを、2けたの2進数で C と S に出しましょう。Cin は、下のけたから来る桁上がりです。答えは 0 から 3 で、3 は2進数で 11 です。「1けたの足し算」を部品として使えます。1つで A と B を足し、もう1つでその S と Cin を足します。この回路を「全加算器」といいます。", + goal: "A+B+Cin の答えを、2桁の2進数で C と S に出しましょう。Cin は、下の桁から来る桁上がりです。答えは 0 から 3 で、3 は2進数で 11 です。「1桁の足し算」を部品として使えます。1つで A と B を足し、もう1つでその S と Cin を足します。この回路を「全加算器」といいます。", steps: [], }, + "four-bit-adder": { + title: "4桁の足し算", + goal: "A と B は4桁の2進数です。A+B を4桁で S に、5桁目(16の位)を C に出しましょう。A+B が 16 以上なら、C は 1 です。表はその例です。", + steps: [ + "「桁上がりつきの足し算」を4つ置きます。Decompose の右側のピンと Aggregate の左側のピンは、どちらも上から8の位・4の位・2の位・1の位です。", + "桁ごとに、A につないだ上の Decompose と、B につないだ下の Decompose から、その桁のピンを1つの「桁上がりつきの足し算」の A と B につなぎます。その足し算の S は、Aggregate の同じ桁のピンにつなぎます。", + "それぞれの桁の足し算の C を、1つ上の桁の足し算の Cin につなぎます。1の位の足し算の Cin には False を、8の位の足し算の C は右の出力 C につなぎます。", + "再生中は、A と B の桁をクリックして 0 と 1 を切り替えられます。答えの S は、右上の Display に1文字で表示されます。その手前の 7seg が、2進数を数字の形に変えています。10 から 15 は1文字で書くために、A(10)、b(11)、C(12)、d(13)、E(14)、F(15)を使います。この書き方を16進数といいます。", + ], + }, }, }, componentProperties: { diff --git a/src/i18n/messages.test.ts b/src/i18n/messages.test.ts index 2bf764c..17cf576 100644 --- a/src/i18n/messages.test.ts +++ b/src/i18n/messages.test.ts @@ -132,6 +132,20 @@ describe("the message on a wrong output", () => { }); }); +describe("the message on a pin of the wrong width", () => { + it("counts digits in both languages", () => { + expect(messagesByLanguage.en.tutorial.wrongBitWidth("A", 4, 1)).toBe( + "A should have 4 digits, but it has 1 digit. Check what it is connected to.", + ); + expect(messagesByLanguage.en.tutorial.wrongBitWidth("C", 1, 4)).toBe( + "C should have 1 digit, but it has 4 digits. Check what it is connected to.", + ); + expect(messagesByLanguage.ja.tutorial.wrongBitWidth("A", 4, 1)).toBe( + "A は 4桁のはずですが、1桁になっています。つないだ先を確かめてください。", + ); + }); +}); + describe("English messages", () => { it("lists the inputs reset with their bit widths", () => { expect( diff --git a/src/pages/edit/Editor/components/ValueEditor/value.ts b/src/pages/edit/Editor/components/ValueEditor/value.ts index 6c3351d..575a92e 100644 --- a/src/pages/edit/Editor/components/ValueEditor/value.ts +++ b/src/pages/edit/Editor/components/ValueEditor/value.ts @@ -1,5 +1,6 @@ import { chunk } from "es-toolkit"; import invariant from "tiny-invariant"; +import { bitsOf, numberOf } from "../../../../../common/bits"; import type { Messages } from "../../../../../i18n/messages"; import type { CCIntrinsicComponentConstSpecConfigViewMode as Mode } from "../../../../../store/intrinsics/types"; import type { SimulationValue } from "../../../../../store/simulation"; @@ -7,18 +8,6 @@ import type { SimulationValue } from "../../../../../store/simulation"; const bitsPerHexDigit = 4; const bitsPerByte = 8; -/** Bits are ordered from the most significant one, as in `SimulationValue`. */ -function toBits(value: number, bitCount: number): boolean[] { - return Array.from( - { length: bitCount }, - (_, i) => ((value >> (bitCount - 1 - i)) & 1) === 1, - ); -} - -function fromBits(bits: boolean[]): number { - return bits.reduce((value, bit) => value * 2 + (bit ? 1 : 0), 0); -} - /** Pads the head with zeros so that the length becomes a multiple of `unit`. */ function padBits(bits: SimulationValue, unit: number): boolean[] { const padding = (unit - (bits.length % unit)) % unit; @@ -34,12 +23,12 @@ export function formatSimulationValue( return data.map((bit) => (bit ? "1" : "0")).join(""); case "hex": return chunk(padBits(data, bitsPerHexDigit), bitsPerHexDigit) - .map((digit) => fromBits(digit).toString(16)) + .map((digit) => numberOf(digit).toString(16)) .join(""); case "utf-8": { const bytes = Uint8Array.from( chunk(padBits(data, bitsPerByte), bitsPerByte), - fromBits, + numberOf, ); return new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes); } @@ -61,13 +50,13 @@ export function parseSimulationValue( const digits = text.replace(/\s/g, "").replace(/^0x/i, ""); if (!/^[0-9a-f]+$/i.test(digits)) return null; return [...digits].flatMap((digit) => - toBits(Number.parseInt(digit, 16), bitsPerHexDigit), + bitsOf(Number.parseInt(digit, 16), bitsPerHexDigit), ); } case "utf-8": { const bytes = new TextEncoder().encode(text); if (bytes.length === 0) return null; - return [...bytes].flatMap((byte) => toBits(byte, bitsPerByte)); + return [...bytes].flatMap((byte) => bitsOf(byte, bitsPerByte)); } } } diff --git a/src/pages/edit/Editor/store/index.tsx b/src/pages/edit/Editor/store/index.tsx index 55463e3..7d415dd 100644 --- a/src/pages/edit/Editor/store/index.tsx +++ b/src/pages/edit/Editor/store/index.tsx @@ -15,6 +15,7 @@ export type EditorStoreOptions = { isProtectedNode?: (nodeId: CCNodeId) => boolean; isOffered?: OffersComponent; canCreateComponents?: boolean; + fitsNodesInView?: boolean; hasProperties?: (componentId: CCComponentId) => boolean; }; @@ -26,6 +27,7 @@ export function createEditorStore( isOffered = () => true, hasProperties = () => true, canCreateComponents = true, + fitsNodesInView = false, }: EditorStoreOptions = {}, ) { const props = { store, componentId }; @@ -38,6 +40,7 @@ export function createEditorStore( isOffered, hasProperties, canCreateComponents, + fitsNodesInView, ...coreSlice.define(set, get), ...perspectiveSlice.define(set, get), ...contextMenuSlice.define(set, get), diff --git a/src/pages/edit/Editor/store/slices/perspective/fit.test.ts b/src/pages/edit/Editor/store/slices/perspective/fit.test.ts new file mode 100644 index 0000000..a33d480 --- /dev/null +++ b/src/pages/edit/Editor/store/slices/perspective/fit.test.ts @@ -0,0 +1,79 @@ +import { describe, expect, it } from "vitest"; +import type { Perspective } from "../../../../../../common/types"; +import type { Vector2 } from "../../../../../../common/vector2"; +import { fitPadding, perspectiveFitting } from "./fit"; + +const rendererSize = { x: 900, y: 800 }; + +function toCanvas(point: Vector2, { center, scale }: Perspective): Vector2 { + return { + x: (point.x - center.x) / scale + rendererSize.x / 2, + y: (point.y - center.y) / scale + rendererSize.y / 2, + }; +} + +function expectInsideRoom( + rects: { position: Vector2; size: Vector2 }[], + perspective: Perspective, +) { + for (const { position, size } of rects) { + const topLeft = toCanvas(position, perspective); + const bottomRight = toCanvas( + { x: position.x + size.x, y: position.y + size.y }, + perspective, + ); + expect(topLeft.x).toBeGreaterThanOrEqual(fitPadding.left - 1e-9); + expect(topLeft.y).toBeGreaterThanOrEqual(fitPadding.top - 1e-9); + expect(bottomRight.x).toBeLessThanOrEqual( + rendererSize.x - fitPadding.right + 1e-9, + ); + expect(bottomRight.y).toBeLessThanOrEqual( + rendererSize.y - fitPadding.bottom + 1e-9, + ); + } +} + +describe("perspectiveFitting", () => { + it("keeps the size of nodes that fit, and moves them clear of the edges", () => { + const rects = [ + { position: { x: -350, y: -115 }, size: { x: 100, y: 30 } }, + { position: { x: 250, y: -15 }, size: { x: 100, y: 30 } }, + ]; + const perspective = perspectiveFitting(rects, rendererSize); + + expect(perspective.scale).toBe(1); + expectInsideRoom(rects, perspective); + }); + + it("zooms out just enough for nodes that do not fit", () => { + const rects = [ + { position: { x: -500, y: -400 }, size: { x: 100, y: 100 } }, + { position: { x: 600, y: 500 }, size: { x: 100, y: 100 } }, + ]; + const perspective = perspectiveFitting(rects, rendererSize); + + expect(perspective.scale).toBeGreaterThan(1); + expectInsideRoom(rects, perspective); + expect( + perspective.scale * (rendererSize.y - fitPadding.top - fitPadding.bottom), + ).toBeCloseTo(1000); + }); + + it("stays finite on a renderer smaller than the padding", () => { + const perspective = perspectiveFitting( + [{ position: { x: 0, y: 0 }, size: { x: 100, y: 100 } }], + { x: 50, y: 200 }, + ); + + expect(Number.isFinite(perspective.scale)).toBe(true); + expect(Number.isFinite(perspective.center.x)).toBe(true); + expect(Number.isFinite(perspective.center.y)).toBe(true); + }); + + it("shows the middle when there are no nodes", () => { + expect(perspectiveFitting([], rendererSize)).toEqual({ + center: { x: 0, y: 0 }, + scale: 1, + }); + }); +}); diff --git a/src/pages/edit/Editor/store/slices/perspective/fit.ts b/src/pages/edit/Editor/store/slices/perspective/fit.ts new file mode 100644 index 0000000..4748959 --- /dev/null +++ b/src/pages/edit/Editor/store/slices/perspective/fit.ts @@ -0,0 +1,42 @@ +import type { Perspective } from "../../../../../../common/types"; +import type { Vector2 } from "../../../../../../common/vector2"; + +/** Room kept clear of nodes: the title bar is at the top and the play button at the bottom right */ +export const fitPadding = { top: 130, right: 30, bottom: 110, left: 30 }; + +/** + * The perspective showing every rectangle inside a renderer of `rendererSize`, zoomed + * out only as far as needed, never in + */ +export function perspectiveFitting( + rects: readonly { position: Vector2; size: Vector2 }[], + rendererSize: Vector2, +): Perspective { + if (rects.length === 0) return { center: { x: 0, y: 0 }, scale: 1 }; + const left = Math.min(...rects.map((rect) => rect.position.x)); + const top = Math.min(...rects.map((rect) => rect.position.y)); + const right = Math.max(...rects.map((rect) => rect.position.x + rect.size.x)); + const bottom = Math.max( + ...rects.map((rect) => rect.position.y + rect.size.y), + ); + // A renderer smaller than the padding still gets a finite scale + const roomX = Math.max( + 1, + rendererSize.x - fitPadding.left - fitPadding.right, + ); + const roomY = Math.max( + 1, + rendererSize.y - fitPadding.top - fitPadding.bottom, + ); + const scale = Math.max(1, (right - left) / roomX, (bottom - top) / roomY); + // The middle of the room is off the middle of the renderer by half the uneven padding + return { + center: { + x: + (left + right) / 2 - ((fitPadding.left - fitPadding.right) / 2) * scale, + y: + (top + bottom) / 2 - ((fitPadding.top - fitPadding.bottom) / 2) * scale, + }, + scale, + }; +} diff --git a/src/pages/edit/Editor/store/slices/perspective/index.tsx b/src/pages/edit/Editor/store/slices/perspective/index.tsx index 593c87d..ba1b3f0 100644 --- a/src/pages/edit/Editor/store/slices/perspective/index.tsx +++ b/src/pages/edit/Editor/store/slices/perspective/index.tsx @@ -1,12 +1,15 @@ import { vector2 } from "../../../../../../common/vector2"; +import { getCCComponentEditorRendererNodeGeometry } from "../../../renderer/Node/geometry"; import type { ComponentEditorSliceCreator } from "../../types"; +import { perspectiveFitting } from "./fit"; import type { PerspectiveStoreSlice } from "./types"; const createComponentEditorStorePerspectiveSlice: ComponentEditorSliceCreator< PerspectiveStoreSlice -> = () => { +> = ({ store, componentId }) => { let resizeObserver: ResizeObserver | null; let rendererElement: SVGSVGElement | null; + let hasFitted = false; const registerRendererElement = (element: SVGSVGElement | null) => { if (!resizeObserver) return; if (rendererElement) resizeObserver.unobserve(rendererElement); @@ -53,11 +56,31 @@ const createComponentEditorStorePerspectiveSlice: ComponentEditorSliceCreator< postCreate(editorStore) { resizeObserver = new ResizeObserver((entries) => { if (!entries[0]) return; + const rendererSize = { + x: entries[0].contentRect.width, + y: entries[0].contentRect.height, + }; + const state = editorStore.getState(); + const fitsNow = + state.fitsNodesInView && + !hasFitted && + rendererSize.x > 0 && + rendererSize.y > 0; + if (fitsNow) hasFitted = true; editorStore.setState({ - rendererSize: { - x: entries[0].contentRect.width, - y: entries[0].contentRect.height, - }, + rendererSize, + ...(fitsNow && { + perspective: perspectiveFitting( + store.nodes + .getManyByParentComponentId(componentId) + .map( + (node) => + getCCComponentEditorRendererNodeGeometry(store, node.id) + .rect, + ), + rendererSize, + ), + }), }); }); }, diff --git a/src/pages/edit/Editor/store/types.ts b/src/pages/edit/Editor/store/types.ts index cb5ad00..d60c6a8 100644 --- a/src/pages/edit/Editor/store/types.ts +++ b/src/pages/edit/Editor/store/types.ts @@ -12,6 +12,8 @@ export type ComponentEditorStoreValue = { readonly isProtectedNode: (nodeId: CCNodeId) => boolean; readonly isOffered: OffersComponent; readonly canCreateComponents: boolean; + /** whether the view is fitted to the nodes when the editor first gets its size */ + readonly fitsNodesInView: boolean; readonly hasProperties: (componentId: CCComponentId) => boolean; } & EditorStoreCoreSlice & PerspectiveStoreSlice & diff --git a/src/pages/tutorial/stage.tsx b/src/pages/tutorial/stage.tsx index c6ea692..098db80 100644 --- a/src/pages/tutorial/stage.tsx +++ b/src/pages/tutorial/stage.tsx @@ -16,7 +16,6 @@ import { useNavigate, useParams, } from "react-router"; -import { valueLabel } from "../../common/bitLabel"; import { BitNotationContext } from "../../components/bitNotation"; import { ConfirmDialog } from "../../components/ConfirmDialog"; import { @@ -24,17 +23,16 @@ import { PartDescriptionView, } from "../../components/PartDescription"; import { TruthTableView } from "../../components/TruthTableView"; -import { type Messages, useMessages } from "../../i18n"; -import type CCStore from "../../store"; +import { useMessages } from "../../i18n"; import { definitionByComponentId } from "../../store/intrinsics/definitions"; -import { SimulationNodeError } from "../../store/netlist"; import { StoreScope } from "../../store/react"; import { theme } from "../../style"; import { type CheckResult, checkCombinational, - truthTableOfCheck, + goalTableOf, } from "../../tutorial/check"; +import { describeFailure } from "../../tutorial/failure"; import { markStageCleared } from "../../tutorial/progress"; import { getTutorialStageStore, @@ -53,36 +51,6 @@ import CCComponentEditor from "../edit/Editor"; import type { OffersComponent } from "../edit/placement"; import SidePanel from "../edit/SidePanel"; -function describeFailure( - result: Exclude, - store: CCStore, - messages: Messages, -): string { - const texts = messages.tutorial; - switch (result.type) { - case "missingPin": - return texts.missingPin(result.pinType, result.pinName); - case "wrongOutput": - return texts.wrongOutput( - result.inputs.map(({ name, value }) => ({ - name, - value: valueLabel(value), - })), - result.pinName, - valueLabel(result.expected), - result.actual ? valueLabel(result.actual) : null, - ); - case "simulationFailed": - return texts.simulationFailed( - result.error instanceof SimulationNodeError - ? result.error.describe(store, messages.simulation) - : result.error instanceof Error - ? result.error.message - : String(result.error), - ); - } -} - function SectionHeading({ children }: { children: ReactNode }) { return ( texts.stageTexts[id].title; - const goalTable = truthTableOfCheck(stage.check); + const goalTable = goalTableOf(stage.check, stage.examples); const stageTexts = texts.stageTexts[stage.id]; const [store, setStore] = useState(() => @@ -129,6 +97,7 @@ function StageView({ stage }: { stage: TutorialStage }) { const check = () => { const checked = checkCombinational(store, stage.componentId, stage.check); + if (checked.type === "checkFailed") console.error(checked.error); setResult(checked); if (checked.type === "passed") markStageCleared(stage.id); }; @@ -223,16 +192,16 @@ function StageView({ stage }: { stage: TutorialStage }) { } /> ))} - {stage.givenParts.map((id) => ( - - ))} + {stage.givenParts + .map((id) => nullthrows(findTutorialStage(id))) + .map((given) => ( + + ))} @@ -299,6 +268,7 @@ function StageView({ stage }: { stage: TutorialStage }) { isProtectedNode: (nodeId) => isStagePinNode(store, stage, nodeId), isOffered, canCreateComponents: stage.allowsNewComponents, + fitsNodesInView: true, hasProperties: (componentId) => !isStageComponent(stage, componentId), }} diff --git a/src/store/intrinsics/truthTable.test.ts b/src/store/intrinsics/truthTable.test.ts index 11df91b..6d3d482 100644 --- a/src/store/intrinsics/truthTable.test.ts +++ b/src/store/intrinsics/truthTable.test.ts @@ -20,24 +20,24 @@ describe("truthTableOf", () => { inputs: ["A", "B"], outputs: ["Out"], rows: [ - { inputs: [false, false], outputs: [false] }, - { inputs: [false, true], outputs: [false] }, - { inputs: [true, false], outputs: [false] }, - { inputs: [true, true], outputs: [true] }, + { inputs: [[false], [false]], outputs: [[false]] }, + { inputs: [[false], [true]], outputs: [[false]] }, + { inputs: [[true], [false]], outputs: [[false]] }, + { inputs: [[true], [true]], outputs: [[true]] }, ], }); expect(truthTableOf(xor)?.rows.map((row) => row.outputs[0])).toEqual([ - false, - true, - true, - false, + [false], + [true], + [true], + [false], ]); expect(truthTableOf(not)?.rows).toEqual([ - { inputs: [false], outputs: [true] }, - { inputs: [true], outputs: [false] }, + { inputs: [[false]], outputs: [[true]] }, + { inputs: [[true]], outputs: [[false]] }, ]); expect(truthTableOf(true_)?.rows).toEqual([ - { inputs: [], outputs: [true] }, + { inputs: [], outputs: [[true]] }, ]); }); diff --git a/src/store/intrinsics/truthTable.ts b/src/store/intrinsics/truthTable.ts index cd9cd38..4a03b3f 100644 --- a/src/store/intrinsics/truthTable.ts +++ b/src/store/intrinsics/truthTable.ts @@ -1,11 +1,12 @@ import { mapValues } from "es-toolkit"; import nullthrows from "nullthrows"; +import type { SimulationValue } from "../simulation"; import { IntrinsicComponentDefinition } from "./base"; export type TruthTable = { inputs: string[]; outputs: string[]; - rows: { inputs: boolean[]; outputs: boolean[] }[]; + rows: { inputs: SimulationValue[]; outputs: SimulationValue[] }[]; }; const maxInputCount = 2; @@ -45,9 +46,9 @@ export function truthTableOf( }, ); return { - inputs, + inputs: inputs.map((input) => [input]), outputs: outputKeys.map((key) => - nullthrows(values[key]?.[0]?.[0], `No value for ${key}`), + nullthrows(values[key]?.[0], `No value for ${key}`), ), }; }); diff --git a/src/store/testUtils.ts b/src/store/testUtils.ts index a8309ec..52e86d2 100644 --- a/src/store/testUtils.ts +++ b/src/store/testUtils.ts @@ -1,6 +1,7 @@ import nullthrows from "nullthrows"; import invariant from "tiny-invariant"; import { expect, vi } from "vitest"; +import { bitsOf, numberOf } from "../common/bits"; import CCStore from "."; import { type CCComponent, @@ -189,18 +190,10 @@ export function testComponentPin( ); } -/** MSB-first bit array of `value` in `width` bits. */ -export function testBits(value: number, width: number): SimulationValue { - return Array.from( - { length: width }, - (_, i) => ((value >> (width - 1 - i)) & 1) === 1, - ); -} +export const testBits = bitsOf; -/** Decimal reading of an MSB-first bit array. */ export function testNumber(value: SimulationValue | undefined): number | null { - if (!value) return null; - return Number.parseInt(value.map((bit) => (bit ? "1" : "0")).join(""), 2); + return value ? numberOf(value) : null; } export function thrownBy( diff --git a/src/tutorial/check.test.ts b/src/tutorial/check.test.ts index 687a25c..1fef46c 100644 --- a/src/tutorial/check.test.ts +++ b/src/tutorial/check.test.ts @@ -1,18 +1,23 @@ import nullthrows from "nullthrows"; import { describe, expect, it } from "vitest"; import { extractNodesIntoNewComponent } from "../store/extractComponent"; -import { and, or } from "../store/intrinsics/definitions"; +import { aggregate, and, decompose, or } from "../store/intrinsics/definitions"; import { connectTestNodePins, createTestStore, + registerTestComponent, + registerTestInputNode, registerTestNode, + registerTestOutputNode, + splitTestNodePin, testNodePin, + tryConnectTestNodePins, } from "../store/testUtils"; import { type CombinationalCheck, checkCombinational, + goalTableOf, inputCombinations, - truthTableOfCheck, } from "./check"; import { findTutorialStage, @@ -65,16 +70,16 @@ describe("inputCombinations", () => { }); }); -describe("truthTableOfCheck", () => { +describe("goalTableOf", () => { it("lists what the stage asks for, in the order the check tries the inputs", () => { - expect(truthTableOfCheck(xorStage.check)).toEqual({ + expect(goalTableOf(xorStage.check, [])).toEqual({ inputs: ["A", "B"], outputs: ["Out"], rows: [ - { inputs: [false, false], outputs: [false] }, - { inputs: [false, true], outputs: [true] }, - { inputs: [true, false], outputs: [true] }, - { inputs: [true, true], outputs: [false] }, + { inputs: [[false], [false]], outputs: [[false]] }, + { inputs: [[false], [true]], outputs: [[true]] }, + { inputs: [[true], [false]], outputs: [[true]] }, + { inputs: [[true], [true]], outputs: [[false]] }, ], }); }); @@ -82,32 +87,25 @@ describe("truthTableOfCheck", () => { it("lists several outputs in the order the stage names them", () => { const halfAdder = nullthrows(findTutorialStage("half-adder")); - expect(truthTableOfCheck(halfAdder.check)).toEqual({ - inputs: ["A", "B"], - outputs: ["C", "S"], - rows: [ - { inputs: [false, false], outputs: [false, false] }, - { inputs: [false, true], outputs: [false, true] }, - { inputs: [true, false], outputs: [false, true] }, - { inputs: [true, true], outputs: [true, false] }, - ], - }); + expect(goalTableOf(halfAdder.check, [])?.rows).toEqual([ + { inputs: [[false], [false]], outputs: [[false], [false]] }, + { inputs: [[false], [true]], outputs: [[false], [true]] }, + { inputs: [[true], [false]], outputs: [[false], [true]] }, + { inputs: [[true], [true]], outputs: [[true], [false]] }, + ]); }); - it("gives no table when a pin carries more than one bit", () => { - const wideInput: CombinationalCheck = { + it("shows only the examples when an input has several bits", () => { + const wide: CombinationalCheck = { inputs: [{ name: "A", bitWidth: 2 }], outputs: ["Out"], - expected: () => ({ Out: [false] }), - }; - const wideOutput: CombinationalCheck = { - inputs: [{ name: "A", bitWidth: 1 }], - outputs: ["Out"], - expected: () => ({ Out: [false, false] }), + expected: (values) => ({ Out: [...nullthrows(values.A)].reverse() }), }; - expect(truthTableOfCheck(wideInput)).toBeNull(); - expect(truthTableOfCheck(wideOutput)).toBeNull(); + expect(goalTableOf(wide, [])).toBeNull(); + expect(goalTableOf(wide, [{ A: [true, false] }])?.rows).toEqual([ + { inputs: [[true, false]], outputs: [[false, true]] }, + ]); }); it("refuses a check that gives no value for an output", () => { @@ -117,7 +115,7 @@ describe("truthTableOfCheck", () => { expected: () => ({}), }; - expect(() => truthTableOfCheck(check)).toThrow("Out"); + expect(() => goalTableOf(check, [])).toThrow("Out"); }); }); @@ -173,6 +171,20 @@ describe("checkCombinational", () => { }); }); + it("reports a check that throws instead of throwing", () => { + const { store } = stageStore(andStage); + const error = new Error("broken"); + + expect( + checkCombinational(store, andStage.componentId, { + ...andStage.check, + expected: () => { + throw error; + }, + }), + ).toEqual({ type: "checkFailed", error }); + }); + it("reports a circuit that cannot be simulated", () => { const { store } = stageStore(andStage); @@ -198,3 +210,110 @@ describe("checkCombinational", () => { }); }); }); + +describe("checkCombinational on pins of several bits", () => { + const twoBitCheck: CombinationalCheck = { + inputs: [{ name: "A", bitWidth: 2 }], + outputs: ["Out"], + expected: (values) => ({ Out: [...nullthrows(values.A)] }), + }; + + it("tells an input left one bit wide", () => { + const store = createTestStore(); + const component = registerTestComponent(store, "Wide"); + registerTestInputNode(store, component.id, "A"); + registerTestOutputNode(store, component.id, "Out"); + + expect(checkCombinational(store, component.id, twoBitCheck)).toEqual({ + type: "wrongBitWidth", + pinName: "A", + expected: 2, + actual: 1, + }); + }); + + it("leaves an unconnected output to the simulation", () => { + const store = createTestStore(); + const component = registerTestComponent(store, "Wide"); + const a = registerTestInputNode(store, component.id, "A"); + registerTestOutputNode(store, component.id, "Out"); + const split = registerTestNode(store, component.id, decompose.component.id); + splitTestNodePin(store, split, decompose.outputPin.Out, [1, 1]); + connectTestNodePins( + store, + component.id, + a.out, + testNodePin(store, split, decompose.inputPin.In), + ); + + expect(checkCombinational(store, component.id, twoBitCheck)).toMatchObject({ + type: "simulationFailed", + }); + }); + + it("leaves a pin in a width conflict to the simulation", () => { + const store = createTestStore(); + const component = registerTestComponent(store, "Wide"); + const a = registerTestInputNode(store, component.id, "A"); + registerTestOutputNode(store, component.id, "Out"); + const split = registerTestNode(store, component.id, decompose.component.id); + splitTestNodePin(store, split, decompose.outputPin.Out, [1, 1]); + const joined = registerTestNode( + store, + component.id, + aggregate.component.id, + ); + connectTestNodePins( + store, + component.id, + a.out, + testNodePin(store, split, decompose.inputPin.In), + ); + tryConnectTestNodePins( + store, + component.id, + a.out, + testNodePin(store, joined, aggregate.inputPin.In), + { allowBitWidthConflict: true }, + ); + + expect(store.nodePins.isInBitWidthConflict(a.out)).toBe(true); + expect(checkCombinational(store, component.id, twoBitCheck)).toMatchObject({ + type: "simulationFailed", + }); + }); + + it("tells an output fixed to another width", () => { + const store = createTestStore(); + const component = registerTestComponent(store, "Wide"); + const a = registerTestInputNode(store, component.id, "A"); + const out = registerTestOutputNode(store, component.id, "Out"); + const split = registerTestNode(store, component.id, decompose.component.id); + splitTestNodePin(store, split, decompose.outputPin.Out, [1, 1]); + const joined = registerTestNode( + store, + component.id, + aggregate.component.id, + ); + splitTestNodePin(store, joined, aggregate.inputPin.In, [1, 1, 1]); + connectTestNodePins( + store, + component.id, + a.out, + testNodePin(store, split, decompose.inputPin.In), + ); + connectTestNodePins( + store, + component.id, + testNodePin(store, joined, aggregate.outputPin.Out), + out.in, + ); + + expect(checkCombinational(store, component.id, twoBitCheck)).toEqual({ + type: "wrongBitWidth", + pinName: "Out", + expected: 2, + actual: 3, + }); + }); +}); diff --git a/src/tutorial/check.ts b/src/tutorial/check.ts index 291a767..b2816cd 100644 --- a/src/tutorial/check.ts +++ b/src/tutorial/check.ts @@ -3,6 +3,7 @@ import type CCStore from "../store"; import type { CCComponentId } from "../store/component"; import type { CCComponentPinId } from "../store/componentPin"; import type { TruthTable } from "../store/intrinsics/truthTable"; +import { DEFAULT_SIMULATION_BIT_WIDTH } from "../store/netlist"; import type { CCNodePinId } from "../store/nodePin"; import simulateComponent, { type SimulationFrame, @@ -21,7 +22,14 @@ export type CombinationalCheck = { export type CheckResult = | { type: "passed" } | { type: "missingPin"; pinType: "input" | "output"; pinName: string } + | { + type: "wrongBitWidth"; + pinName: string; + expected: number; + actual: number; + } | { type: "simulationFailed"; error: unknown } + | { type: "checkFailed"; error: unknown } | { type: "wrongOutput"; inputs: readonly { name: string; value: SimulationValue }[]; @@ -53,27 +61,28 @@ function expectedValueOf(expected: PinValues, name: string) { return nullthrows(expected[name], `The check gives no value for ${name}`); } -/** null when a pin carries more than one bit */ -export function truthTableOfCheck( +/** + * Every combination of the inputs when each is one bit, or else the given examples, + * with what the outputs should be; null when there is nothing to show + */ +export function goalTableOf( check: CombinationalCheck, + examples: readonly PinValues[], ): TruthTable | null { - if (check.inputs.some(({ bitWidth }) => bitWidth !== 1)) return null; - const rows: TruthTable["rows"] = []; - for (const inputs of inputCombinations(check.inputs)) { - const expected = check.expected(inputs); - const outputs = check.outputs.map((name) => - expectedValueOf(expected, name), - ); - if (outputs.some((value) => value.length !== 1)) return null; - rows.push({ - inputs: check.inputs.map(({ name }) => nullthrows(inputs[name]?.[0])), - outputs: outputs.map((value) => nullthrows(value[0])), - }); - } + const rows = check.inputs.every(({ bitWidth }) => bitWidth === 1) + ? [...inputCombinations(check.inputs)] + : examples; + if (rows.length === 0) return null; return { inputs: check.inputs.map(({ name }) => name), outputs: [...check.outputs], - rows, + rows: rows.map((inputs) => { + const expected = check.expected(inputs); + return { + inputs: check.inputs.map(({ name }) => nullthrows(inputs[name])), + outputs: check.outputs.map((name) => expectedValueOf(expected, name)), + }; + }), }; } @@ -89,6 +98,18 @@ export function checkCombinational( store: CCStore, componentId: CCComponentId, check: CombinationalCheck, +): CheckResult { + try { + return checkCircuit(store, componentId, check); + } catch (error) { + return { type: "checkFailed", error }; + } +} + +function checkCircuit( + store: CCStore, + componentId: CCComponentId, + check: CombinationalCheck, ): CheckResult { const pins = store.componentPins.getManyByComponentId(componentId); const findPin = (pinType: "input" | "output", pinName: string) => @@ -109,6 +130,46 @@ export function checkCombinational( outputNodePinIds.set(name, pin.implementation); } + // An input nothing fixes is simulated one bit wide. A conflict or an unconnected + // output is left to the simulation, which tells what is wrong with it. + const bitWidthOf = (nodePinId: CCNodePinId, pinType: "input" | "output") => { + if (store.nodePins.isInBitWidthConflict(nodePinId)) return null; + const status = store.nodePins.getNodePinBitWidthStatus(nodePinId); + if (status.isFixed) return status.bitWidth; + return pinType === "input" ? DEFAULT_SIMULATION_BIT_WIDTH : null; + }; + const someExpected = check.expected( + nullthrows(inputCombinations(check.inputs).next().value), + ); + const expectedBitWidths = [ + ...check.inputs.map(({ name, bitWidth }) => ({ + name, + pinType: "input" as const, + bitWidth, + nodePinId: nullthrows( + store.componentPins.get(nullthrows(inputPinIds.get(name))) + ?.implementation, + ), + })), + ...check.outputs.map((name) => ({ + name, + pinType: "output" as const, + bitWidth: expectedValueOf(someExpected, name).length, + nodePinId: nullthrows(outputNodePinIds.get(name)), + })), + ]; + for (const { name, pinType, bitWidth, nodePinId } of expectedBitWidths) { + const actual = bitWidthOf(nodePinId, pinType); + if (actual !== null && actual !== bitWidth) { + return { + type: "wrongBitWidth", + pinName: name, + expected: bitWidth, + actual, + }; + } + } + for (const inputs of inputCombinations(check.inputs)) { const inputValues = new Map(); for (const [name, pinId] of inputPinIds) { diff --git a/src/tutorial/circuit.ts b/src/tutorial/circuit.ts index 534e5b5..5e012c1 100644 --- a/src/tutorial/circuit.ts +++ b/src/tutorial/circuit.ts @@ -6,7 +6,7 @@ import type { CCComponentId } from "../store/component"; import type { CCComponentPin } from "../store/componentPin"; import { CCConnectionStore } from "../store/connection"; import { type CCNode, CCNodeStore } from "../store/node"; -import type { CCNodePinId } from "../store/nodePin"; +import { type CCNodePinId, CCNodePinStore } from "../store/nodePin"; /** Builds a circuit inside one component, as the editor would when drawn by hand */ export class StageCircuit { @@ -26,25 +26,57 @@ export class StageCircuit { ); } - place(componentId: CCComponentId, position: Vector2): CCNode { + place( + componentId: CCComponentId, + position: Vector2, + config?: CCNode["config"], + ): CCNode { const node = CCNodeStore.create({ parentComponentId: this.componentId, componentId, position, }); + if (config !== undefined) node.config = config; this.store.nodes.register(node); return node; } - /** By name only on a stage's component, as intrinsic pins are named for display */ - pinOf(node: CCNode, pin: CCComponentPin | string): CCNodePinId { + split(node: CCNode, componentPin: CCComponentPin, widths: readonly number[]) { + const [first, ...rest] = widths; + const existing = this.store.nodePins.getManyByNodeIdAndComponentPinId( + node.id, + componentPin.id, + ); + invariant( + first !== undefined && existing.length === 1 && existing[0], + "Only a pin not split yet can be split", + ); + this.store.nodePins.update(existing[0].id, { manualBitWidth: first }); + for (const [index, manualBitWidth] of rest.entries()) { + this.store.nodePins.register( + CCNodePinStore.create({ + nodeId: node.id, + componentPinId: componentPin.id, + order: index + 1, + manualBitWidth, + }), + ); + } + } + + /** + * By name only on a stage's component, as intrinsic pins are named for display. + * `index` picks one of the pins a split pin became, from the top. + */ + pinOf(node: CCNode, pin: CCComponentPin | string, index = 0): CCNodePinId { const nodePin = this.store.nodePins .getManyByNodeId(node.id) - .find((nodePin) => + .filter((nodePin) => typeof pin === "string" ? this.store.componentPins.get(nodePin.componentPinId)?.name === pin : nodePin.componentPinId === pin.id, - ); + ) + .toSorted((a, b) => a.order - b.order)[index]; return nullthrows( nodePin, `The node has no pin ${typeof pin === "string" ? pin : pin.name}`, diff --git a/src/tutorial/failure.ts b/src/tutorial/failure.ts new file mode 100644 index 0000000..b29ffc1 --- /dev/null +++ b/src/tutorial/failure.ts @@ -0,0 +1,43 @@ +import { valueLabel } from "../common/bitLabel"; +import type { Messages } from "../i18n"; +import type CCStore from "../store"; +import { SimulationNodeError } from "../store/netlist"; +import type { CheckResult } from "./check"; + +export function describeFailure( + result: Exclude, + store: CCStore, + messages: Messages, +): string { + const texts = messages.tutorial; + switch (result.type) { + case "missingPin": + return texts.missingPin(result.pinType, result.pinName); + case "wrongBitWidth": + return texts.wrongBitWidth( + result.pinName, + result.expected, + result.actual, + ); + case "wrongOutput": + return texts.wrongOutput( + result.inputs.map(({ name, value }) => ({ + name, + value: valueLabel(value), + })), + result.pinName, + valueLabel(result.expected), + result.actual ? valueLabel(result.actual) : null, + ); + case "checkFailed": + return texts.checkFailed; + case "simulationFailed": + return texts.simulationFailed( + result.error instanceof SimulationNodeError + ? result.error.describe(store, messages.simulation) + : result.error instanceof Error + ? result.error.message + : String(result.error), + ); + } +} diff --git a/src/tutorial/stages.test.ts b/src/tutorial/stages.test.ts index aa77176..42cd7e0 100644 --- a/src/tutorial/stages.test.ts +++ b/src/tutorial/stages.test.ts @@ -14,7 +14,6 @@ import { registerTestNode, } from "../store/testUtils"; import { checkCombinational } from "./check"; -import { StageCircuit } from "./circuit"; import { findTutorialStage, isStagePart, @@ -55,16 +54,21 @@ describe("tutorialStages", () => { "%s is cleared by its solution, made of the parts it offers", (_, solved) => { const store = createTestStore(); - setUpTutorialStage(store, solved, titleOf); + const solve = setUpTutorialStage(store, solved, titleOf); + const laidOut = new Set( + store.nodes + .getManyByParentComponentId(solved.componentId) + .map((node) => node.id), + ); - solved.solve(new StageCircuit(store, solved.componentId)); + solve(); expect( checkCombinational(store, solved.componentId, solved.check), ).toEqual({ type: "passed" }); const placed = store.nodes .getManyByParentComponentId(solved.componentId) - .filter((node) => !isStagePinNode(store, solved, node.id)) + .filter((node) => !laidOut.has(node.id)) .map((node) => node.componentId); const offered = [ ...solved.parts, @@ -152,6 +156,23 @@ describe("isStagePart", () => { expect(isStagePart(stage, xor.component, own.id)).toBe(false); }); + it("offers only the parts handed over directly, not those built into them", () => { + const fourBit = nullthrows(findTutorialStage("four-bit-adder")); + const store = createTestStore(); + setUpTutorialStage(store, fourBit, titleOf); + const componentOf = (id: TutorialStageId) => + nullthrows( + store.components.get(nullthrows(findTutorialStage(id)).componentId), + ); + + expect( + isStagePart(fourBit, componentOf("full-adder"), fourBit.componentId), + ).toBe(true); + expect( + isStagePart(fourBit, componentOf("half-adder"), fourBit.componentId), + ).toBe(false); + }); + it("offers inside a part handed over what its own stage offers, and no pins", () => { const inGiven = (component: Parameters[1]) => isStagePart(xorStage, component, aOnlyStage.componentId); diff --git a/src/tutorial/stages.ts b/src/tutorial/stages.ts index 31e547f..fd69b34 100644 --- a/src/tutorial/stages.ts +++ b/src/tutorial/stages.ts @@ -1,5 +1,6 @@ import nullthrows from "nullthrows"; import type { BitNotation } from "../common/bitLabel"; +import { bitsOf, numberOf } from "../common/bits"; import type CCStore from "../store"; import { type CCComponent, @@ -8,15 +9,20 @@ import { } from "../store/component"; import type { CCComponentPin } from "../store/componentPin"; import { + aggregate, and, + decompose, + display, + false_, input, not, or, output, + seven_segment, xor, } from "../store/intrinsics/definitions"; import { type CCNodeId, CCNodeStore } from "../store/node"; -import type { CombinationalCheck } from "./check"; +import type { CombinationalCheck, PinValues } from "./check"; import { StageCircuit } from "./circuit"; export const tutorialStageIds = [ @@ -25,6 +31,7 @@ export const tutorialStageIds = [ "xor", "half-adder", "full-adder", + "four-bit-adder", ] as const; export type TutorialStageId = (typeof tutorialStageIds)[number]; export type StageTitleOf = (id: TutorialStageId) => string; @@ -41,7 +48,15 @@ export type TutorialStage = { tableNotation: BitNotation; /** also the input and output pins the stage starts with */ check: CombinationalCheck; - solve(circuit: StageCircuit): void; + /** inputs the goal shows when every combination of them is too many */ + examples: readonly PinValues[]; + /** how far left and right of the middle the input and output pins sit */ + pinDistance: number; + /** + * Places what the stage starts with besides its pins, and returns how to clear it + * from there. Decorations, such as a display, are only placed for the player. + */ + layOut(circuit: StageCircuit, options: { decorate: boolean }): () => void; }; const gateParts = [and, or, not].map((gate) => gate.component.id); @@ -52,26 +67,52 @@ const isOn = (value: readonly boolean[] | undefined) => nullthrows(value?.[0]); const oneBitInputs = (...names: string[]) => names.map((name) => ({ name, bitWidth: 1 })); -type StageDefinition = Pick & - Partial>; +/** For a stage that starts with nothing but its pins */ +type Solving = { solve(circuit: StageCircuit): void }; + +type StageDefinition = Pick & + Partial< + Pick< + TutorialStage, + "givenParts" | "tableNotation" | "pinDistance" | "examples" + > + > & + (Pick | Solving); function defineStage( id: TutorialStageId, definition: StageDefinition, ): TutorialStage { + const { + parts, + check, + givenParts = [], + tableNotation = "onOff", + pinDistance = 300, + examples = [], + } = definition; return { id, componentId: `tutorial-${id}` as CCComponentId, - givenParts: [], + parts, + check, + givenParts, + tableNotation, + pinDistance, + examples, allowsNewComponents: false, - tableNotation: "onOff", - ...definition, + layOut: + "layOut" in definition + ? definition.layOut + : (circuit) => () => definition.solve(circuit), }; } function twoSwitchesStage( id: TutorialStageId, - definition: Omit, + definition: Pick & + Partial> & + Solving, lampIsOn: (a: boolean, b: boolean) => boolean, ): TutorialStage { return defineStage(id, { @@ -214,12 +255,114 @@ const fullAdderStage = defineStage("full-adder", { }, }); +const digitCount = 4; + +const fourBitAdderStage = defineStage("four-bit-adder", { + parts: [decompose, aggregate, false_].map((part) => part.component.id), + givenParts: ["full-adder"], + tableNotation: "digits", + pinDistance: 420, + check: { + inputs: [ + { name: "A", bitWidth: digitCount }, + { name: "B", bitWidth: digitCount }, + ], + outputs: ["C", "S"], + expected: (values) => { + const total = + numberOf(nullthrows(values.A)) + numberOf(nullthrows(values.B)); + return { + C: bit(total >= 2 ** digitCount), + S: bitsOf(total % 2 ** digitCount, digitCount), + }; + }, + }, + examples: [ + [3, 5], + [6, 7], + [9, 8], + ].map(([a, b]) => ({ + A: bitsOf(nullthrows(a), digitCount), + B: bitsOf(nullthrows(b), digitCount), + })), + layOut(circuit, { decorate }) { + const single = new Array(digitCount).fill(1); + const splitA = circuit.place(decompose.component.id, { x: -250, y: -170 }); + const splitB = circuit.place(decompose.component.id, { x: -250, y: 170 }); + const joined = circuit.place(aggregate.component.id, { x: 150, y: 100 }); + circuit.split(splitA, decompose.outputPin.Out, single); + circuit.split(splitB, decompose.outputPin.Out, single); + circuit.split(joined, aggregate.inputPin.In, single); + circuit.connect( + circuit.pin("A"), + circuit.pinOf(splitA, decompose.inputPin.In), + ); + circuit.connect( + circuit.pin("B"), + circuit.pinOf(splitB, decompose.inputPin.In), + ); + const sum = circuit.pinOf(joined, aggregate.outputPin.Out); + circuit.connect(sum, circuit.pin("S")); + if (decorate) { + const digit = circuit.place(seven_segment.component.id, { + x: 290, + y: -250, + }); + const screen = circuit.place( + display.component.id, + { x: 430, y: -250 }, + { resolution: { x: 4, y: 7 }, pixelOrder: "row-major" }, + ); + circuit.connect(sum, circuit.pinOf(digit, seven_segment.inputPin.In)); + circuit.connect( + circuit.pinOf(digit, seven_segment.outputPin.Out), + circuit.pinOf(screen, display.inputPin.Pixels), + ); + } + return () => { + const adders = Array.from({ length: digitCount }, (_, index) => + circuit.place(fullAdderStage.componentId, { + x: -50, + y: -300 + 200 * index, + }), + ); + const noCarry = circuit.place(false_.component.id, { x: -200, y: 390 }); + for (const [index, adder] of adders.entries()) { + circuit.connect( + circuit.pinOf(splitA, decompose.outputPin.Out, index), + circuit.pinOf(adder, "A"), + ); + circuit.connect( + circuit.pinOf(splitB, decompose.outputPin.Out, index), + circuit.pinOf(adder, "B"), + ); + circuit.connect( + circuit.pinOf(adder, "S"), + circuit.pinOf(joined, aggregate.inputPin.In, index), + ); + const lower = adders[index + 1]; + circuit.connect( + lower + ? circuit.pinOf(lower, "C") + : circuit.pinOf(noCarry, false_.outputPin.Out), + circuit.pinOf(adder, "Cin"), + ); + } + circuit.connect( + circuit.pinOf(nullthrows(adders[0]), "C"), + circuit.pin("C"), + ); + }; + }, +}); + export const tutorialStages: readonly TutorialStage[] = [ andStage, aOnlyStage, xorStage, halfAdderStage, fullAdderStage, + fourBitAdderStage, ]; export function findTutorialStage(id: string | undefined) { @@ -255,14 +398,19 @@ export function isStagePart( editedComponentId: CCComponentId, ) { const owner = stageOwning(stage, editedComponentId); + const isGivenTo = (receiver: TutorialStage) => + receiver.givenParts.some( + (id) => tutorialStageById(id).componentId === component.id, + ); if (owner && owner !== stage) { return component.intrinsicType ? owner.parts.includes(component.id) - : owner.givenParts.some( - (id) => tutorialStageById(id).componentId === component.id, - ); + : isGivenTo(owner); + } + if (!component.intrinsicType) { + // A part handed over to a part handed over is built in, not offered + return !isStageComponent(stage, component.id) || isGivenTo(stage); } - if (!component.intrinsicType) return true; if (owner) return owner.parts.includes(component.id); // A component of the player's own gets its pins from Input and Output nodes return ( @@ -332,9 +480,14 @@ function registerStageComponent( input.component.id, input.outputPin.Out, stage.check.inputs.map(({ name }) => name), - -300, + -stage.pinDistance, + ); + place( + output.component.id, + output.inputPin.In, + stage.check.outputs, + stage.pinDistance, ); - place(output.component.id, output.inputPin.In, stage.check.outputs, 300); } /** Skips the parts `store` already has, as a save from before may lack only some */ @@ -347,19 +500,25 @@ export function registerGivenParts( if (store.components.get(given.componentId)) continue; registerGivenParts(store, given, titleOf); registerStageComponent(store, given, titleOf(given.id)); - given.solve(new StageCircuit(store, given.componentId)); + given.layOut(new StageCircuit(store, given.componentId), { + decorate: false, + })(); } } /** - * Lay out the component of `stage`, with its input and output pins, and the components - * it hands over, in a mounted store + * Lay out the component of `stage`, with its pins and what else it starts with, and the + * components it hands over, in a mounted store + * @returns builds the stage's solution from there */ export function setUpTutorialStage( store: CCStore, stage: TutorialStage, titleOf: StageTitleOf, -): void { +): () => void { registerGivenParts(store, stage, titleOf); registerStageComponent(store, stage, titleOf(stage.id)); + return stage.layOut(new StageCircuit(store, stage.componentId), { + decorate: true, + }); }