Unlock custom brushes, natural fill effects and intuitive hatching in p5.js
Prune low-signal unit tests
acamposuribe0e8517759731
diff --git a/test/unit/color.test.js b/test/unit/color.test.jsdeleted file mode 100644index 5bec473..0000000--- a/test/unit/color.test.js+++ /dev/null@@ -1,69 +0,0 @@-// ============================================================-// Standalone Color parsing (Vitest)-//-// Covers the argument forms Color accepts and, more importantly, what it does-// with input it cannot parse. A non-finite channel must not reach _array: the-// compositor compares _array against the cached colour to decide whether a-// stroke can keep accumulating into the pending mask, and NaN !== NaN makes-// every stroke read as a colour change, silently disabling stroke batching.-// ============================================================--import { describe, it, expect, vi } from "vitest";--// Color lives beside the runtime hooks, and that module imports core/save.js,-// which reaches GLSL sources through core/color.js. Node cannot load those.-// Color itself needs none of it.-vi.mock("../../src/core/save.js", () => ({ push: () => {}, pop: () => {} }));--const { Color } = await import("../../src/adapters/standalone/runtime.js");--describe("Color", () => {- it("accepts three numeric channels", () => {- expect(new Color(255, 128, 0)._array).toEqual([1, 128 / 255, 0, 1]);- });-- it("accepts an array, matching what p5's own color() takes", () => {- expect(new Color([255, 128, 0])._array).toEqual(new Color(255, 128, 0)._array);- });-- it("reads alpha from a four-element array", () => {- expect(new Color([255, 0, 0, 0.5])._array).toEqual([1, 0, 0, 0.5]);- });-- it("accepts an rgb() string", () => {- // Hex and named colours are resolved through a canvas context, which the- // Node test environment does not provide, so they are covered by the- // browser suites rather than here.- expect(new Color("rgb(255,128,0)")._array).toEqual(new Color(255, 128, 0)._array);- });-- it("copies an existing Color", () => {- const source = new Color(10, 20, 30);- expect(new Color(source)._array).toEqual(source._array);- });-- it("clamps out-of-range channels instead of rejecting them", () => {- expect(new Color(300, -20, 0)._array).toEqual([1, 0, 0, 1]);- });-- it("throws rather than producing a NaN channel", () => {- expect(() => new Color({})).toThrow(/Invalid color value/);- expect(() => new Color(NaN)).toThrow(/Invalid color value/);- expect(() => new Color([1, "x", 3])).toThrow(/Invalid color value/);- });-- it("never puts a non-finite value in _array", () => {- for (const args of [[0, 0, 0], [[1, 2, 3]], [[4, 5, 6, 0.25]], [255]]) {- expect(new Color(...args)._array.every(Number.isFinite)).toBe(true);- }- });-- it("compares equal for equal input, so batching can dedupe by colour", () => {- // The compositor's colour-change check is a componentwise compare of- // _array. Two separately constructed but equal colours must not read as a- // change, or every stroke forces its own composite pass.- const a = new Color([20, 20, 20])._array;- const b = new Color([20, 20, 20])._array;- expect(a.every((v, i) => v === b[i])).toBe(true);- });-});diff --git a/test/unit/fill.test.js b/test/unit/fill.test.jsdeleted file mode 100644index 7be8300..0000000--- a/test/unit/fill.test.js+++ /dev/null@@ -1,250 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--const { blend, currentAngleMode, drawPolygon, mockCtx, mockState } = vi.hoisted(() => ({- blend: vi.fn(),- currentAngleMode: { value: "degrees" },- drawPolygon: vi.fn(),- mockCtx: {- beginPath: vi.fn(),- fill: vi.fn(),- restore: vi.fn(),- save: vi.fn(),- setTransform: vi.fn(),- stroke: vi.fn(),- getTransform: vi.fn(() => ({- a: 1, b: 0, c: 0, d: 1, e: 0, f: 0,- })),- fillStyle: "",- globalCompositeOperation: "source-over",- lineCap: "round",- lineWidth: 0,- strokeStyle: "",- },- mockState: {},-}));--vi.mock("../../src/core/color.js", () => ({- Mix: {- blend,- ctx: mockCtx,- isBrush: true,- justChanged: false,- },- State: mockState,- registerFillComposite: () => {},-}));--vi.mock("../../src/core/target.js", () => ({- Renderer: {- color: () => ({- _getBlue: () => 64,- _getGreen: () => 128,- _getRed: () => 255,- }),- },- Cwidth: 800,- Cheight: 600,- Density: 1,-}));--vi.mock("../../src/fill/mask.js", () => ({- circle: vi.fn(),- drawPolygon,-}));--vi.mock("../../src/core/flowfield.js", () => ({- Matrix: {- a: () => 1,- b: () => 0,- c: () => 0,- d: () => 1,- x: () => 0,- y: () => 0,- },- isFieldReady: () => {},-}));--vi.mock("../../src/core/polygon.js", () => ({- Polygon: class Polygon {},-}));--vi.mock("../../src/core/plot.js", () => ({- Plot: class Plot {},-}));--vi.mock("../../src/core/runtime.js", () => ({- usesRadians: () => currentAngleMode.value === "radians",- createColor: (r, g, b) => ({- r: typeof r === 'string' ? 255 : r,- g: g ?? r ?? 0,- b: b ?? r ?? 0,- _getRed: function() { return this.r; },- _getGreen: function() { return this.g; },- _getBlue: function() { return this.b; },- }),- getAffineMatrix: () => ({- a: 1, b: 0, c: 0, d: 1, x: 0, y: 0,- }),-}));--import { createFill, fill, fillBleed, noFill } from "../../src/fill/fill.js";-import { seed } from "../../src/core/utils.js";--// Helper: builds a simple convex polygon object that fill.js expects.-function makePolygon(vertices) {- return {- vertices,- sides: vertices.map((v, i) => [v, vertices[(i + 1) % vertices.length]]),- intersect: () => [],- };-}--// Hexagonal polygon (6 vertices — uses centroid "simple average" fast path)-function makeHexagon(cx = 50, cy = 50, r = 40) {- const verts = [];- for (let i = 0; i < 6; i++) {- const a = (i / 6) * 2 * Math.PI;- verts.push({ x: cx + r * Math.cos(a), y: cy + r * Math.sin(a) });- }- return makePolygon(verts);-}--// 10-vertex polygon (uses shoelace centroid path)-function makeDodecagon(cx = 50, cy = 50, r = 40) {- const verts = [];- for (let i = 0; i < 10; i++) {- const a = (i / 10) * 2 * Math.PI;- verts.push({ x: cx + r * Math.cos(a), y: cy + r * Math.sin(a) });- }- return makePolygon(verts);-}--describe("createFill()", () => {- beforeEach(() => {- mockState.fill = {- opacity: 150,- bleed_strength: 0.07,- texture_strength: 0.8,- border_strength: 0.5,- direction: "out",- angle: null,- scatter: true,- isActive: false,- };- currentAngleMode.value = "degrees";-- blend.mockClear();- drawPolygon.mockClear();- mockCtx.beginPath.mockClear();- mockCtx.fill.mockClear();- mockCtx.restore.mockClear();- mockCtx.save.mockClear();- mockCtx.setTransform.mockClear();- mockCtx.stroke.mockClear();- mockCtx.globalCompositeOperation = "source-over";- });-- // ---- existing test ----- it("does not throw for small polygons in the centroid fast path", () => {- fill("#ff0000", 80);-- const vertices = [- { x: 10, y: 10 },- { x: 80, y: 10 },- { x: 110, y: 45 },- { x: 95, y: 90 },- { x: 35, y: 100 },- { x: 5, y: 55 },- ];-- const polygon = {- vertices,- sides: vertices.map((vertex, index) => [- vertex,- vertices[(index + 1) % vertices.length],- ]),- intersect: () => [],- };-- expect(() => createFill(polygon)).not.toThrow();- });-- // ---- characterization tests ------ it("throws the exact error message when fill is inactive", () => {- // isActive is false (set in beforeEach)- expect(() => createFill(makeHexagon())).toThrow(- "No fill color set. Call brush.fill(color) before drawing shapes.",- );- });-- it("throws the exact error message when fill is active but color is unset", () => {- mockState.fill.isActive = true;- mockState.fill.color = undefined;- expect(() => createFill(makeHexagon())).toThrow(- "No fill color set. Call brush.fill(color) before drawing shapes.",- );- });-- it("does not throw after fill() activates fill state (hexagon — small polygon path)", () => {- seed(12345);- fill("#00ff00", 120);- expect(() => createFill(makeHexagon())).not.toThrow();- });-- it("does not throw after fill() activates fill state (10-vertex polygon — shoelace path)", () => {- seed(12345);- fill("#0000ff", 200);- expect(() => createFill(makeDodecagon())).not.toThrow();- });-- it("invokes ctx.save() and ctx.restore() once each per fill pass", () => {- seed(12345);- fill("#ff0000", 100);- createFill(makeHexagon());- expect(mockCtx.save).toHaveBeenCalled();- expect(mockCtx.restore).toHaveBeenCalled();- expect(mockCtx.save.mock.calls.length).toBe(mockCtx.restore.mock.calls.length);- });-- it("calls blend at least once per fill pass (watercolor layering)", () => {- seed(12345);- fill("#aabbcc", 80);- createFill(makeHexagon());- expect(blend).toHaveBeenCalled();- });-- it("uses fillBleed angle to choose the watercolor start side", () => {- fill("#ff0000", 100);- fillBleed(0, "out", 0);- createFill(makePolygon([- { x: 10, y: 0 },- { x: 50, y: 30 },- { x: 90, y: 0 },- { x: 50, y: -30 },- ]));- expect(drawPolygon.mock.calls[0][0][0].x).toBe(10);- });-- it("captures fillBleed angle using the current angle mode at call time", () => {- currentAngleMode.value = "radians";- fill("#ff0000", 100);- fillBleed(0, "out", Math.PI);- currentAngleMode.value = "degrees";- createFill(makePolygon([- { x: 10, y: 0 },- { x: 50, y: 30 },- { x: 90, y: 0 },- { x: 50, y: -30 },- ]));- expect(drawPolygon.mock.calls[0][0][0].x).toBe(90);- });-- it("noFill() disables the fill so createFill throws afterward", () => {- fill("#ff0000", 100);- noFill();- expect(() => createFill(makeHexagon())).toThrow(- "No fill color set. Call brush.fill(color) before drawing shapes.",- );- });-});diff --git a/test/unit/flowfield.test.js b/test/unit/flowfield.test.jsindex ca904d3..3442f91 100644--- a/test/unit/flowfield.test.js+++ b/test/unit/flowfield.test.js@@ -1,287 +1,50 @@-// ============================================================-// p5.brush – Position / flowfield characterization tests-//-// Characterizes the current behavior of Position (isInCanvas,-// moveTo, _moveToDegrees, movePos) and field setup.-// Run: npx vitest run test/unit/flowfield.test.js-// ============================================================+import { describe, expect, it, vi } from "vitest";-import { describe, it, expect, vi, beforeEach } from "vitest";--// ---- Hoisted mock state -----const { currentAngleMode, mockState, plotInstances } = vi.hoisted(() => ({- currentAngleMode: { value: "radians" },+const { currentAngleMode, mockState } = vi.hoisted(() => ({+ currentAngleMode: { value: "degrees" },mockState: {},- plotInstances: [],}));vi.mock("../../src/core/color.js", () => ({- Mix: {},- State: mockState,- isCanvasReady: () => {},- isMixReady: () => {},+ Mix: {}, State: mockState, isCanvasReady: () => {}, isMixReady: () => {},}));-vi.mock("../../src/core/runtime.js", () => ({usesRadians: () => currentAngleMode.value === "radians",- fromDegrees: (angle) =>- currentAngleMode.value === "radians" ? (angle * Math.PI) / 180 : angle,+ fromDegrees: (angle) => currentAngleMode.value === "radians" ? angle * Math.PI / 180 : angle,createColor: () => ({}),getAffineMatrix: () => ({ a: 1, b: 0, c: 0, d: 1, x: 0, y: 0 }),setRuntime: () => {},}));-vi.mock("../../src/core/target.js", () => ({Renderer: {- angleMode: () => currentAngleMode.value,- RADIANS: "radians",- DEGREES: "degrees",- _renderer: {- uModelMatrix: {- mat4: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],- },- },+ angleMode: () => currentAngleMode.value, RADIANS: "radians", DEGREES: "degrees",+ _renderer: { uModelMatrix: { mat4: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] } },},- Cwidth: 800,- Cheight: 600,+ Cwidth: 800, Cheight: 600,}));-vi.mock("../../src/stroke/stroke.js", () => ({- BrushState: () => ({}),- BrushSetState: () => {},- set: () => {},- line: () => {},-}));--vi.mock("../../src/core/polygon.js", () => ({- Polygon: class Polygon {},+ BrushState: () => ({}), BrushSetState: () => {}, set: () => {}, line: () => {},}));--vi.mock("../../src/core/plot.js", () => ({- Plot: class Plot {- constructor(type) {- this.type = type;- this.addSegment = vi.fn();- this.endPlot = vi.fn();- this.draw = vi.fn();- this.show = vi.fn();- plotInstances.push(this);- }- },-}));--import { Position, addField, field as activateField, noField } from "../../src/core/flowfield.js";--// Canvas is 800×600 (mocked in target.js).-// isInCanvas margin = 0.5-// Valid x range: [-400, 1200] (-0.5*800 to 1.5*800)-// Valid y range: [-300, 900] (-0.5*600 to 1.5*600)--beforeEach(() => {- currentAngleMode.value = "radians";- plotInstances.length = 0;- if (mockState.field) {- mockState.field.isActive = false;- mockState.field.current = null;+vi.mock("../../src/core/polygon.js", () => ({ Polygon: class Polygon {} }));+vi.mock("../../src/core/plot.js", () => ({ Plot: class Plot {} }));++import { Position, addField, field, noField } from "../../src/core/flowfield.js";++describe("flowfield movement", () => {+ it("moves along the active field direction rather than the requested stroke direction", () => {+ addField("constant-down", (_time, grid) => {+ for (const column of grid) column.fill(90);+ return grid;+ }, { angleMode: "degrees" });+ field("constant-down");mockState.field.wiggle = 1;- }-});--// ----------------------------------------------------------------------------// 1. isInCanvas — margin pin-// ----------------------------------------------------------------------------describe("Position.isInCanvas() — margin = 0.5", () => {- it("returns true at canvas center (400, 300)", () => {- noField();- const pos = new Position(400, 300);- expect(pos.isInCanvas()).toBe(true);- });-- it("returns true at the canvas origin (0, 0)", () => {- noField();- const pos = new Position(0, 0);- expect(pos.isInCanvas()).toBe(true);- });-- it("returns true at the canvas edge (800, 600)", () => {- noField();- const pos = new Position(800, 600);- expect(pos.isInCanvas()).toBe(true);- });-- it("returns true at x=-400 (margin left boundary)", () => {- noField();- const pos = new Position(-400, 300);- expect(pos.isInCanvas()).toBe(true);- });-- it("returns false at x=-401 (just outside margin)", () => {- noField();- const pos = new Position(-401, 300);- expect(pos.isInCanvas()).toBe(false);- });-- it("returns true at x=1200 (margin right boundary)", () => {- noField();- const pos = new Position(1200, 300);- expect(pos.isInCanvas()).toBe(true);- });-- it("returns false at x=1201 (just outside margin right)", () => {- noField();- const pos = new Position(1201, 300);- expect(pos.isInCanvas()).toBe(false);- });-- it("returns true at y=-300 (margin top boundary)", () => {- noField();- const pos = new Position(400, -300);- expect(pos.isInCanvas()).toBe(true);- });-- it("returns false at y=-301 (just outside margin top)", () => {- noField();- const pos = new Position(400, -301);- expect(pos.isInCanvas()).toBe(false);- });-- it("returns true at y=900 (margin bottom boundary)", () => {- noField();- const pos = new Position(400, 900);- expect(pos.isInCanvas()).toBe(true);- });-- it("returns false at y=901 (just outside margin bottom)", () => {- noField();- const pos = new Position(400, 901);- expect(pos.isInCanvas()).toBe(false);- });-});--// ----------------------------------------------------------------------------// 2. moveTo — single step (radians and degrees modes)-// ----------------------------------------------------------------------------describe("Position.moveTo() — no active field", () => {- it("moves +x by L when direction is 0° (radians mode)", () => {- currentAngleMode.value = "radians";- noField();- const pos = new Position(400, 300);- pos.moveTo(0, 10, 10);- expect(pos.x).toBeCloseTo(410, 3);- expect(pos.y).toBeCloseTo(300, 3);- });-- it("moves -y by L when direction is 90° (up in y-down coords, radians mode)", () => {- currentAngleMode.value = "radians";- noField();- const pos = new Position(400, 300);- pos.moveTo(Math.PI / 2, 10, 10);- // cossin(-90°) = [cos(-90°), sin(-90°)] = [~0, -1], so y decreases- expect(pos.x).toBeCloseTo(400, 3);- expect(pos.y).toBeCloseTo(290, 3);- });-- it("moves +x by L when direction is 0° (degrees mode)", () => {- currentAngleMode.value = "degrees";- noField();- const pos = new Position(400, 300);- pos.moveTo(0, 10, 10);- expect(pos.x).toBeCloseTo(410, 3);- expect(pos.y).toBeCloseTo(300, 3);- });-- it("moves -y by L when direction is 90° (degrees mode)", () => {currentAngleMode.value = "degrees";- noField();- const pos = new Position(400, 300);- pos.moveTo(90, 10, 10);- expect(pos.x).toBeCloseTo(400, 3);- expect(pos.y).toBeCloseTo(290, 3);- });-});--// ----------------------------------------------------------------------------// 3. Repeated moveTo accumulates-// ----------------------------------------------------------------------------describe("Position.moveTo() — accumulated movement", () => {- it("accumulates 2×L after two calls in the same direction (radians)", () => {- currentAngleMode.value = "radians";- noField();- const pos = new Position(400, 300);- pos.moveTo(0, 10, 10); // move 10 along x- pos.moveTo(0, 10, 10); // move another 10 along x- expect(pos.x).toBeCloseTo(420, 3);- expect(pos.y).toBeCloseTo(300, 3);- });- it("plotted property accumulates step counts", () => {- currentAngleMode.value = "radians";- noField();- const pos = new Position(400, 300);- pos.moveTo(0, 10, 2); // 5 steps of size 2- expect(pos.plotted).toBeCloseTo(10, 3);- });-});+ const position = new Position(400, 300);+ position.moveTo(0, 10, 10);-// ----------------------------------------------------------------------------// 4. Position starting far outside canvas does not move-// ----------------------------------------------------------------------------describe("Position.movePos() — early exit when outside canvas", () => {- it("a position far outside the canvas does not move when movePos is called", () => {+ expect(position.x).toBeCloseTo(400, 1);+ expect(position.y).toBeCloseTo(310, 1);noField();- // x=5000 is well beyond the 1200 right margin- const pos = new Position(5000, 300);- const xBefore = pos.x;- const yBefore = pos.y;- // movePos is called internally by moveTo when field is active;- // call _moveConstant directly to test the isIn() early exit- pos._moveConstant(0, 100, 10);- // Should not have moved (isIn() returns false → early exit after single plotted increment)- expect(pos.x).toBeCloseTo(xBefore, 5);- expect(pos.y).toBeCloseTo(yBefore, 5);- });-- it("plotted still increments on the early-exit step", () => {- noField();- const pos = new Position(5000, 300);- pos._moveConstant(0, 100, 10);- // The early-exit branch adds _step (10) to plotted- expect(pos.plotted).toBeCloseTo(10, 5);- });-});--// ----------------------------------------------------------------------------// 5. With an active field — moveTo follows field angle-// ----------------------------------------------------------------------------describe("Position.moveTo() — with active constant field", () => {- it("field angle combines with direction arg: field=90°, dir=0° moves along +y, not +x", () => {- // Register a constant 90° field (points downward in y-down coords).- // movePos computes: angle = fieldAngle - plotAngle = 90 - 0 = 90- // cossin(90°) = [cos(90°), sin(90°)] = [0, 1]- // → x stays at 400, y increases by step (10) → final (400, 310)- // This DIFFERS from the no-field result (410, 300), so the test catches- // any regression where the field is silently ignored.- addField(- "const-ninety-deg",- (_t, field) => {- for (let c = 0; c < field.length; c++) {- for (let r = 0; r < field[c].length; r++) {- field[c][r] = 90; // 90 degrees → move along +y- }- }- return field;- },- { angleMode: "degrees" },- );-- activateField("const-ninety-deg");- mockState.field.wiggle = 1;-- const pos = new Position(400, 300);- currentAngleMode.value = "degrees";- pos.moveTo(0, 10, 10);- // field=90°, dir=0°: angle = 90 - 0 = 90 → cossin(90°) = [0, 1] → +y only- expect(pos.x).toBeCloseTo(400, 1);- expect(pos.y).toBeCloseTo(310, 1);});});diff --git a/test/unit/hatch.test.js b/test/unit/hatch.test.jsindex 89e3c85..d796ece 100644--- a/test/unit/hatch.test.js+++ b/test/unit/hatch.test.js@@ -1,18 +1,6 @@-// ============================================================-// p5.brush – Hatch characterization tests-//-// Characterizes getHatchLines() / hatch() behavior so that-// future refactors can be verified. Tests pin TODAY's behavior.-// Run: npx vitest run test/unit/hatch.test.js-// ============================================================+import { describe, expect, it, vi, beforeEach } from "vitest";-import { describe, it, expect, vi, beforeEach } from "vitest";--// ---- Hoisted mock state (mirrors unit.test.js pattern) -----const { currentAngleMode, mockState } = vi.hoisted(() => ({- currentAngleMode: { value: "radians" },- mockState: {},-}));+const { mockState } = vi.hoisted(() => ({ mockState: {} }));vi.mock("../../src/core/color.js", () => ({Mix: {},@@ -20,205 +8,44 @@ vi.mock("../../src/core/color.js", () => ({isCanvasReady: () => {},isMixReady: () => {},}));-vi.mock("../../src/core/runtime.js", () => ({- usesRadians: () => currentAngleMode.value === "radians",- fromDegrees: (angle) =>- currentAngleMode.value === "radians" ? (angle * Math.PI) / 180 : angle,+ usesRadians: () => false,+ fromDegrees: (angle) => angle,createColor: () => ({}),getAffineMatrix: () => ({ a: 1, b: 0, c: 0, d: 1, x: 0, y: 0 }),setRuntime: () => {},}));-vi.mock("../../src/core/target.js", () => ({- Renderer: {- angleMode: () => currentAngleMode.value,- RADIANS: "radians",- DEGREES: "degrees",- _renderer: {- uModelMatrix: {- mat4: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],- },- },- },+ Renderer: { angleMode: () => "degrees", RADIANS: "radians", DEGREES: "degrees" },Cwidth: 800,Cheight: 600,}));-vi.mock("../../src/stroke/stroke.js", () => ({- BrushState: () => ({}),- BrushSetState: () => {},- set: () => {},- line: () => {},-}));--vi.mock("../../src/core/polygon.js", () => ({- Polygon: class Polygon {},-}));--vi.mock("../../src/core/plot.js", () => ({- Plot: class Plot {},+ BrushState: () => ({}), BrushSetState: () => {}, set: () => {}, line: () => {},}));+vi.mock("../../src/core/polygon.js", () => ({ Polygon: class Polygon {} }));+vi.mock("../../src/core/plot.js", () => ({ Plot: class Plot {} }));-import { hatch, getHatchLines, noHatch } from "../../src/hatch/hatch.js";-import { seed } from "../../src/core/utils.js";+import { getHatchLines, hatch } from "../../src/hatch/hatch.js";-// ---- Polygon factory -----// hatch.js uses polygon.a — an array of [x, y] tuples-function makeSquare(x0 = 0, y0 = 0, size = 100) {- return {- a: [- [x0, y0],- [x0 + size, y0],- [x0 + size, y0 + size],- [x0, y0 + size],- ],- };+function square(x, y, size) {+ return { a: [[x, y], [x + size, y], [x + size, y + size], [x, y + size]] };}beforeEach(() => {- currentAngleMode.value = "radians";- // Reset hatch state before each test- if (mockState.hatch) {- mockState.hatch.isActive = false;- mockState.hatch.dist = 5;- mockState.hatch.angle = 45;- mockState.hatch.options = {};- mockState.hatch.hBrush = false;- }- seed(12345);-});--// ----------------------------------------------------------------------------// 1. Horizontal scanlines (angle = 0)-// ----------------------------------------------------------------------------describe("getHatchLines() — angle 0 → horizontal lines", () => {- it("returns a non-empty array for a 100×100 square at dist=10", () => {- hatch(10, 0, { rand: 0, continuous: false, gradient: false });- const lines = getHatchLines(makeSquare()).filter((l) => !l.isConnector);- expect(lines.length).toBeGreaterThan(0);- });-- it("every line has y1 === y2 (horizontal)", () => {- hatch(10, 0, { rand: 0, continuous: false, gradient: false });- const lines = getHatchLines(makeSquare()).filter((l) => !l.isConnector);- for (const line of lines) {- expect(line.y1).toBeCloseTo(line.y2, 5);- }- });-- it("produces approximately dist=10 spacing for 100-unit square", () => {- hatch(10, 0, { rand: 0, continuous: false, gradient: false });- const lines = getHatchLines(makeSquare()).filter((l) => !l.isConnector);- // 100 units / 10 dist → expect ~9 scanlines (first at 5, last at 95)- // Characterize: between 8 and 11 lines- expect(lines.length).toBeGreaterThanOrEqual(8);- expect(lines.length).toBeLessThanOrEqual(11);- });-});--// ----------------------------------------------------------------------------// 2. Vertical scanlines (angle = 90)-// ----------------------------------------------------------------------------describe("getHatchLines() — angle 90 → vertical lines", () => {- it("every non-connector line has x1 === x2 (vertical)", () => {- // angle 90 in degrees mode- currentAngleMode.value = "degrees";- hatch(10, 90, { rand: 0, continuous: false, gradient: false });- const lines = getHatchLines(makeSquare()).filter((l) => !l.isConnector);- expect(lines.length).toBeGreaterThan(0);- for (const line of lines) {- expect(line.x1).toBeCloseTo(line.x2, 5);- }- });+ mockState.hatch = { isActive: false, dist: 5, angle: 45, options: {}, hBrush: false };});-// ----------------------------------------------------------------------------// 3. Nested squares (donut) — even-odd parity-// ----------------------------------------------------------------------------describe("getHatchLines() — nested squares produce two runs per hole scanline", () => {- it("pairs crossings with even-odd parity (mirrors unit.test.js)", () => {+describe("hatch polygon arrays", () => {+ it("uses even-odd crossings so a nested polygon remains a hole", () => {hatch(4, 0, { rand: 0, continuous: false, gradient: false });-- const outer = makeSquare(0, 0, 10);- const inner = makeSquare(3, 3, 4); // inner square at (3,3)-(7,7)-- const lines = getHatchLines([outer, inner]).filter((l) => !l.isConnector);- // Scanline at y=6 crosses outer (enter+exit) and inner (enter+exit) → 2 segments- const centerLines = lines- .filter((l) => Math.abs(l.y1 - 6) < 0.01 && Math.abs(l.y2 - 6) < 0.01)+ const lines = getHatchLines([square(0, 0, 10), square(3, 3, 4)])+ .filter((line) => !line.isConnector);+ const center = lines+ .filter((line) => line.y1 === 6 && line.y2 === 6).sort((a, b) => a.x1 - b.x1);- expect(centerLines).toHaveLength(2);- expect(centerLines[0].x1).toBeCloseTo(0);- expect(centerLines[0].x2).toBeCloseTo(3);- expect(centerLines[1].x1).toBeCloseTo(7);- expect(centerLines[1].x2).toBeCloseTo(10);- });-- it("donut produces more total lines than a solid square of equal outer size", () => {- // The hole creates extra segments per scanline in the inner region- hatch(4, 0, { rand: 0, continuous: false, gradient: false });- const solid = getHatchLines(makeSquare(0, 0, 10)).filter((l) => !l.isConnector);- const donut = getHatchLines([makeSquare(0, 0, 10), makeSquare(3, 3, 4)]).filter(- (l) => !l.isConnector,- );- // Donut has the inner 4 scanlines split into 2 each → more total lines- expect(donut.length).toBeGreaterThan(solid.length);- });-});--// ----------------------------------------------------------------------------// 4. Gradient option → spacing increases monotonically-// ----------------------------------------------------------------------------describe("getHatchLines() — gradient > 0 increases scanline spacing", () => {- it("y-gaps between consecutive scanlines are non-decreasing", () => {- hatch(5, 0, { rand: 0, continuous: false, gradient: 0.8 });- const lines = getHatchLines(makeSquare(0, 0, 200)).filter((l) => !l.isConnector);- // Need enough lines for a meaningful assertion- expect(lines.length).toBeGreaterThanOrEqual(3);-- const ys = lines.map((l) => l.y1);- for (let i = 1; i < ys.length - 1; i++) {- expect(ys[i + 1] - ys[i]).toBeGreaterThanOrEqual(ys[i] - ys[i - 1] - 1e-9);- }- });-});--// ----------------------------------------------------------------------------// 5. Degenerate polygon (2 vertices, zero area)-// ----------------------------------------------------------------------------describe("getHatchLines() — degenerate polygon", () => {- it("returns empty array (no throw) for a 2-vertex polygon", () => {- hatch(5, 0, { rand: 0, continuous: false, gradient: false });- const degenerate = { a: [[0, 0], [10, 0]] }; // collinear, zero area- let result;- expect(() => {- result = getHatchLines(degenerate);- }).not.toThrow();- // No scanlines cross a zero-height polygon- expect(result.filter((l) => !l.isConnector)).toHaveLength(0);- });-- it("returns empty array for a single-vertex polygon", () => {- hatch(5, 0, { rand: 0, continuous: false, gradient: false });- const degenerate = { a: [[5, 5]] };- let result;- expect(() => {- result = getHatchLines(degenerate);- }).not.toThrow();- expect(result.filter((l) => !l.isConnector)).toHaveLength(0);- });-});--// ----------------------------------------------------------------------------// 6. noHatch() disables hatching (state check)-// ----------------------------------------------------------------------------describe("noHatch()", () => {- it("sets isActive to false and clears hBrush", () => {- hatch(10, 0);- noHatch();- expect(mockState.hatch.isActive).toBe(false);- expect(mockState.hatch.hBrush).toBe(false);+ expect(center).toHaveLength(2);+ expect(center.map(({ x1, x2 }) => [x1, x2])).toEqual([[0, 3], [7, 10]]);});});diff --git a/test/unit/mass.test.js b/test/unit/mass.test.jsdeleted file mode 100644index e320750..0000000--- a/test/unit/mass.test.js+++ /dev/null@@ -1,167 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--const {- arc,- BrushSetState,- getHatchLines,- mockState,- set,- wiggle,-} = vi.hoisted(() => ({- arc: vi.fn(),- BrushSetState: vi.fn(),- getHatchLines: vi.fn(() => [- { x1: 0, y1: 0, x2: 10, y2: 0, isConnector: false },- ]),- mockState: {- field: {},- },- set: vi.fn(),- wiggle: vi.fn(),-}));--vi.mock("../../src/core/color.js", () => ({- State: mockState,-}));--vi.mock("../../src/core/primitives.js", () => ({- arc,-}));--vi.mock("../../src/core/plot.js", () => ({- Plot: class Plot {},-}));--vi.mock("../../src/core/runtime.js", () => ({- fromDegrees: (angle) => angle,- usesRadians: () => false,-}));--vi.mock("../../src/hatch/hatch.js", () => ({- HatchState: () => ({}),- HatchSetState: () => {},- hatch: () => {},- getHatchLines,-}));--vi.mock("../../src/stroke/stroke.js", () => ({- BrushState: () => ({}),- BrushSetState,- getBrushParams: () => ({ scatter: 1 }),- set,-}));--vi.mock("../../src/core/flowfield.js", () => ({- wiggle,-}));--vi.mock("../../src/core/utils.js", () => ({- rr2: (min = 0, max = 1) => (min + max) / 2,- dist: (x1, y1, x2, y2) => Math.hypot(x2 - x1, y2 - y1),- calcAngle: (x1, y1, x2, y2) => {- const deg = (Math.atan2(-(y2 - y1), x2 - x1) * 180) / Math.PI;- return deg < 0 ? deg + 360 : deg;- },-}));--vi.mock("../../src/core/polygon.js", () => ({- Polygon: class Polygon {- constructor(pointsArray) {- this.a = pointsArray;- this.vertices = pointsArray.map(([x, y]) => ({ x, y }));- }-- draw() {}- },-}));--import { createMass, createMassArray, mass } from "../../src/hatch/mass.js";-import { Polygon } from "../../src/core/polygon.js";--function makeSquarePolygon(x0 = 0, y0 = 0, size = 10) {- return new Polygon([- [x0, y0],- [x0 + size, y0],- [x0 + size, y0 + size],- [x0, y0 + size],- ]);-}--describe("createMassArray()", () => {- beforeEach(() => {- arc.mockClear();- BrushSetState.mockClear();- getHatchLines.mockClear();- set.mockClear();- wiggle.mockClear();- mockState.mass = {- isActive: false,- brush: null,- color: null,- options: {},- };- mockState.field = { isActive: false };- });-- // ---- existing test ----- it("passes polygon arrays through the mass pipeline as combined layers", () => {- mass("HB", "#000", { strength: 1, precision: 0.5, gradient: 0.1 });-- const outer = makeSquarePolygon(0, 0, 10);- const inner = makeSquarePolygon(3, 3, 4);-- expect(() => createMassArray([outer, inner])).not.toThrow();- expect(getHatchLines).toHaveBeenCalled();- expect(getHatchLines.mock.calls[0][0]).toHaveLength(2);- expect(Array.isArray(getHatchLines.mock.calls[0][0])).toBe(true);- expect(arc).toHaveBeenCalled();- });-- // ---- characterization: first arc call arguments ----- it("first arc call receives a positive finite radius and finite start/end angles", () => {- mass("HB", "#000", { strength: 1, precision: 0.5, gradient: 0.1 });- createMassArray([makeSquarePolygon(0, 0, 10)]);-- expect(arc).toHaveBeenCalled();- const firstCall = arc.mock.calls[0];- // arc(cx, cy, radius, startAngle, endAngle)- const [_cx, _cy, radius, startAngle, endAngle] = firstCall;- expect(Number.isFinite(radius)).toBe(true);- expect(radius).toBeGreaterThan(0);- expect(Number.isFinite(startAngle)).toBe(true);- expect(Number.isFinite(endAngle)).toBe(true);- });-- // ---- characterization: single polygon createMass ----- it("createMass with a single polygon calls getHatchLines and arc", () => {- mass("HB", "#000", { strength: 1, precision: 0.5, gradient: 0.1 });- const polygon = makeSquarePolygon(0, 0, 10);-- expect(() => createMass(polygon, false)).not.toThrow();- expect(getHatchLines).toHaveBeenCalled();- expect(arc).toHaveBeenCalled();- });-- // ---- characterization: empty input ----- it("createMassArray([]) does not throw (getPolygonBounds degenerates to Infinity/NaN)", () => {- // Empty polygon array → getPolygonBounds produces Infinity/-Infinity bounds- // and NaN size. This is KNOWN degenerate behavior (characterized, not fixed).- getHatchLines.mockReturnValueOnce([]);- getHatchLines.mockReturnValueOnce([]);- getHatchLines.mockReturnValueOnce([]);- mass("HB", "#000", { strength: 1, precision: 0.5, gradient: 0.1 });- expect(() => createMassArray([])).not.toThrow();- // No hatch lines → no arcs drawn- expect(arc).not.toHaveBeenCalled();- });-- // ---- characterization: brush state restore ----- it("restores brush state after createMassArray completes", () => {- mass("HB", "#000", { strength: 1, precision: 0.5, gradient: 0.1 });- createMassArray([makeSquarePolygon(0, 0, 10)]);- // BrushSetState should have been called to restore the saved brush state- expect(BrushSetState).toHaveBeenCalled();- // The value passed is what BrushState() returned — an empty object in our mock- expect(BrushSetState.mock.calls[BrushSetState.mock.calls.length - 1][0]).toEqual({});- });-});\ No newline at end of filediff --git a/test/unit/stroke_pressure.test.js b/test/unit/stroke_pressure.test.jsindex 6f9ecd3..3ceb605 100644--- a/test/unit/stroke_pressure.test.js+++ b/test/unit/stroke_pressure.test.js@@ -1,140 +1,38 @@-import { describe, it, expect, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";vi.mock("../../src/core/color.js", () => ({- Mix: {},- State: {},- isCanvasReady: () => {},- registerStrokeComposite: () => {},+ Mix: {}, State: {}, isCanvasReady: () => {}, registerStrokeComposite: () => {},}));--vi.mock("../../src/core/target.js", () => ({- Cwidth: 800,- Cheight: 600,- Renderer: {},- Instance: null,-}));-+vi.mock("../../src/core/target.js", () => ({ Cwidth: 800, Cheight: 600, Renderer: {}, Instance: null }));vi.mock("../../src/core/utils.js", () => ({- rr: () => 0,- map: (value, start1, stop1, start2, stop2) =>- start2 + ((value - start1) / (stop1 - start1 || 1)) * (stop2 - start2),- dist: () => 0,- randInt: () => 0,- calcAngle: () => 0,- toDegrees: (v) => v,- gaussian: () => 0,- rArray: () => 0,- noise: () => 0,- _onSeed: () => {},+ rr: () => 0, map: (v, a, b, c, d) => c + ((v - a) / (b - a || 1)) * (d - c),+ dist: () => 0, randInt: () => 0, calcAngle: () => 0, toDegrees: (v) => v,+ gaussian: () => 0, rArray: () => 0, noise: () => 0, _onSeed: () => {},}));-vi.mock("../../src/core/flowfield.js", () => ({- Position: class Position {},- Matrix: {- a: () => 1,- b: () => 0,- c: () => 0,- d: () => 1,- x: () => 0,- y: () => 0,- },+ Position: class Position {}, Matrix: { a: () => 1, b: () => 0, c: () => 0, d: () => 1, x: () => 0, y: () => 0 },isFieldReady: () => {},}));--vi.mock("../../src/core/polygon.js", () => ({- Polygon: class Polygon {},-}));--vi.mock("../../src/core/plot.js", () => ({- Plot: class Plot {},-}));-+vi.mock("../../src/core/polygon.js", () => ({ Polygon: class Polygon {} }));+vi.mock("../../src/core/plot.js", () => ({ Plot: class Plot {} }));vi.mock("../../src/stroke/gl_draw.js", () => ({- isReady: () => {},- glDraw: () => {},- glDrawImages: () => {},- circle: () => {},- stampImage: () => {},- invalidateTexEntry: () => {},- snapshotMatrix: () => {},+ isReady: () => {}, glDraw: () => {}, glDrawImages: () => {}, circle: () => {},+ stampImage: () => {}, invalidateTexEntry: () => {}, snapshotMatrix: () => {},}));-import { add, box, normalizePressure } from "../../src/stroke/stroke.js";--describe("normalizePressure()", () => {- it("keeps function pressure in explicit custom mode", () => {- const curve = (t) => t;- expect(normalizePressure(curve)).toEqual({- type: "custom",- min_max: [0, 1],- curve,- variation: {- offset: 0.08,- scale: 0.08,- warp: 0.06,- tilt: 0.06,- },- });- });-- it("normalizes explicit gaussian mode objects", () => {- expect(- normalizePressure({- mode: "gaussian",- curve: [0.15, 0.2],- min_max: [1.1, 0.9],- }),- ).toEqual({- mode: "gaussian",- type: "gaussian",- curve: [0.15, 0.2],- min_max: [1.1, 0.9],- });- });+import { normalizePressure } from "../../src/stroke/stroke.js";- it("preserves legacy gaussian objects while making the mode explicit", () => {- expect(- normalizePressure({- curve: [0.35, 0.25],- min_max: [1.2, 0.85],- }),- ).toEqual({- type: "gaussian",- curve: [0.35, 0.25],- min_max: [1.2, 0.85],+describe("pressure profile compatibility", () => {+ it("preserves the explicit gaussian profile and its bounds", () => {+ const profile = { mode: "gaussian", curve: [0.15, 0.2], min_max: [1.1, 0.9] };+ expect(normalizePressure(profile)).toMatchObject({+ type: "gaussian", curve: [0.15, 0.2], min_max: [1.1, 0.9],});});- it("adds subtle default variation to simplified array pressure", () => {- expect(normalizePressure([0.5, 1.5, 0.5])).toMatchObject({- type: "custom",- min_max: [0.5, 1.5],- variation: {- offset: 0.08,- scale: 0.08,- warp: 0.06,- tilt: 0.06,- },+ it("continues to accept the legacy gaussian profile format", () => {+ expect(normalizePressure({ curve: [0.35, 0.25], min_max: [1.2, 0.85] })).toMatchObject({+ type: "gaussian", curve: [0.35, 0.25], min_max: [1.2, 0.85],});});});--describe("brush.add()", () => {- it("accepts gaussian pressure objects for custom brushes", () => {- add("gaussian-test-brush", {- weight: 0.3,- scatter: 0.6,- sharpness: 0.3,- grain: 10,- opacity: 170,- spacing: 0.1,- pressure: {- mode: "gaussian",- curve: [0.15, 0.2],- min_max: [1.1, 0.9],- },- });-- expect(box()).toContain("gaussian-test-brush");- });-});diff --git a/test/unit/unit.test.js b/test/unit/unit.test.jsindex ddb54db..ef39062 100644--- a/test/unit/unit.test.js+++ b/test/unit/unit.test.js@@ -1,414 +1,37 @@-// ============================================================-// p5.brush Unit Tests (Vitest)-//-// Tests pure utility functions that have no browser dependency.-// Run: npm test-// ============================================================+import { beforeEach, describe, expect, it, vi } from "vitest";-import { describe, it, expect, vi, beforeAll, beforeEach } from "vitest";--const { currentAngleMode, mockState, plotInstances } = vi.hoisted(() => ({- currentAngleMode: { value: "radians" },- mockState: {},- plotInstances: [],-}));--// Mock color.js (pulls in GLSL shaders and WebGL — not available in Node)-vi.mock("../../src/core/color.js", () => ({- Mix: {},- State: mockState,- isCanvasReady: () => {},- isMixReady: () => {},+const { currentAngleMode, plots } = vi.hoisted(() => ({+ currentAngleMode: { value: "degrees" },+ plots: [],}));-// Mock runtime.js to properly handle angle modevi.mock("../../src/core/runtime.js", () => ({usesRadians: () => currentAngleMode.value === "radians",- fromDegrees: (angle) => currentAngleMode.value === "radians" ? (angle * Math.PI) / 180 : angle,- createColor: () => ({}),- getAffineMatrix: () => ({ a: 1, b: 0, c: 0, d: 1, x: 0, y: 0 }),- setRuntime: () => {},+ fromDegrees: (angle) => currentAngleMode.value === "radians" ? angle * Math.PI / 180 : angle,}));-vi.mock("../../src/core/target.js", () => ({- Renderer: {- angleMode: () => currentAngleMode.value,- RADIANS: "radians",- DEGREES: "degrees",- _renderer: {- uModelMatrix: {- mat4: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],- },- },- },- Cwidth: 800,- Cheight: 600,-}));--vi.mock("../../src/stroke/stroke.js", () => ({- BrushState: () => ({}),- BrushSetState: () => {},- set: () => {},- line: () => {},-}));--vi.mock("../../src/core/polygon.js", () => ({- Polygon: class Polygon {},+ Renderer: { angleMode: () => currentAngleMode.value, RADIANS: "radians", DEGREES: "degrees" },}));-+vi.mock("../../src/core/polygon.js", () => ({ Polygon: class Polygon {} }));vi.mock("../../src/core/plot.js", () => ({Plot: class Plot {- constructor(type) {- this.type = type;- this.addSegment = vi.fn();- this.endPlot = vi.fn();- this.draw = vi.fn();- this.show = vi.fn();- plotInstances.push(this);- }+ constructor() { this.addSegment = vi.fn(); this.endPlot = vi.fn(); this.draw = vi.fn(); plots.push(this); }},}));-import {- map,- constrain,- dist,- cos,- sin,- rotate,- intersectLines,- rr,- randInt,- seed,- weightedRand,- toDegreesSigned,-} from "../../src/core/utils.js";-import { arc, beginShape, vertex, endShape } from "../../src/core/primitives.js";-import { Position, addField, field as activateField, noField } from "../../src/core/flowfield.js";-import { getHatchLines, hatch } from "../../src/hatch/hatch.js";--beforeEach(() => {- currentAngleMode.value = "radians";- plotInstances.length = 0;- if (mockState.field) {- mockState.field.isActive = false;- mockState.field.current = null;- mockState.field.wiggle = 1;- }- if (mockState.hatch) {- mockState.hatch.isActive = false;- mockState.hatch.dist = 5;- mockState.hatch.angle = 45;- mockState.hatch.options = {};- mockState.hatch.hBrush = false;- }-});--// ---- map() -----describe("map()", () => {- it("maps midpoint correctly", () => {- expect(map(5, 0, 10, 0, 100)).toBeCloseTo(50);- });-- it("maps minimum", () => {- expect(map(0, 0, 10, 0, 100)).toBeCloseTo(0);- });-- it("maps maximum", () => {- expect(map(10, 0, 10, 0, 100)).toBeCloseTo(100);- });-- it("maps to inverted range", () => {- expect(map(0, 0, 10, 100, 0)).toBeCloseTo(100);- expect(map(10, 0, 10, 100, 0)).toBeCloseTo(0);- });-- it("clamps when withinBounds=true", () => {- expect(map(20, 0, 10, 0, 100, true)).toBeCloseTo(100);- expect(map(-5, 0, 10, 0, 100, true)).toBeCloseTo(0);- });-- it("does NOT clamp by default", () => {- expect(map(20, 0, 10, 0, 100)).toBeCloseTo(200);- });-});--// ---- constrain() -----describe("constrain()", () => {- it("returns value when within bounds", () => {- expect(constrain(5, 0, 10)).toBe(5);- });-- it("clamps to lower bound", () => {- expect(constrain(-3, 0, 10)).toBe(0);- });-- it("clamps to upper bound", () => {- expect(constrain(15, 0, 10)).toBe(10);- });-- it("handles equal bounds", () => {- expect(constrain(7, 5, 5)).toBe(5);- });-});--// ---- dist() -----describe("dist()", () => {- it("returns 0 for same point", () => {- expect(dist(3, 4, 3, 4)).toBe(0);- });-- it("returns correct Euclidean distance", () => {- expect(dist(0, 0, 3, 4)).toBeCloseTo(5);- });-- it("is symmetric", () => {- expect(dist(1, 2, 5, 6)).toBeCloseTo(dist(5, 6, 1, 2));- });-});--// ---- cos() / sin() — degree-based lookup table -----describe("cos() and sin()", () => {- it("cos(0) === 1", () => expect(cos(0)).toBeCloseTo(1));- it("cos(90) === 0", () => expect(cos(90)).toBeCloseTo(0, 3));- it("cos(180) === -1", () => expect(cos(180)).toBeCloseTo(-1));- it("sin(0) === 0", () => expect(sin(0)).toBeCloseTo(0, 3));- it("sin(90) === 1", () => expect(sin(90)).toBeCloseTo(1));- it("sin(180) === 0", () => expect(sin(180)).toBeCloseTo(0, 3));-- it("cos² + sin² === 1 for arbitrary angle", () => {- const a = 37;- expect(cos(a) ** 2 + sin(a) ** 2).toBeCloseTo(1);- });-- it("handles negative angles", () => {- expect(cos(-90)).toBeCloseTo(cos(270));- });-- it("handles angles > 360", () => {- expect(cos(450)).toBeCloseTo(cos(90));- });-});--describe("toDegreesSigned()", () => {- it("matches p5's default radians mode when angleMode() has not been changed", () => {- expect(toDegreesSigned(Math.PI / 2)).toBeCloseTo(90);- });-- it("converts radians without wrapping signed angles", () => {- currentAngleMode.value = "radians";- expect(toDegreesSigned(-Math.PI / 4)).toBeCloseTo(-45);- });-});--// ---- rotate() -----describe("rotate()", () => {- it("rotating (1,0) by 90° around origin gives ~(0,1)", () => {- const r = rotate(0, 0, 1, 0, 90);- expect(r.x).toBeCloseTo(0, 3);- expect(r.y).toBeCloseTo(-1, 3); // y-down coordinate system- });-- it("rotating by 0° returns same point", () => {- const r = rotate(0, 0, 5, 3, 0);- expect(r.x).toBeCloseTo(5);- expect(r.y).toBeCloseTo(3);- });-- it("rotating by 360° returns same point", () => {- const r = rotate(2, 2, 7, 5, 360);- expect(r.x).toBeCloseTo(7);- expect(r.y).toBeCloseTo(5);- });-});--// ---- intersectLines() -----describe("intersectLines()", () => {- const mkPt = (x, y) => ({ x, y });-- it("finds intersection of two crossing lines", () => {- const pt = intersectLines(- mkPt(0, 0),- mkPt(10, 10),- mkPt(0, 10),- mkPt(10, 0),- true,- );- expect(pt).not.toBe(false);- expect(pt.x).toBeCloseTo(5);- expect(pt.y).toBeCloseTo(5);- });-- it("returns false for parallel lines", () => {- const pt = intersectLines(- mkPt(0, 0),- mkPt(10, 0),- mkPt(0, 5),- mkPt(10, 5),- true,- );- expect(pt).toBe(false);- });-- it("returns false when intersection is outside second segment bounds (default)", () => {- // Segment 1: long horizontal at y=-5- // Segment 2: short vertical from y=0 to y=3 — intersection at y=-5 is outside it- const pt = intersectLines(- mkPt(0, -5),- mkPt(10, -5),- mkPt(5, 0),- mkPt(5, 3),- );- expect(pt).toBe(false);- });-- it("returns false for point-like segments", () => {- const pt = intersectLines(mkPt(0, 0), mkPt(0, 0), mkPt(1, 0), mkPt(2, 0));- expect(pt).toBe(false);- });-});--// ---- rr() and randInt() — seeded RNG -----describe("rr() — seeded random", () => {- beforeAll(() => seed(42));-- it("returns a number in [min, max)", () => {- for (let i = 0; i < 50; i++) {- const v = rr(5, 10);- expect(v).toBeGreaterThanOrEqual(5);- expect(v).toBeLessThan(10);- }- });-- it("default range is [0, 1)", () => {- for (let i = 0; i < 50; i++) {- const v = rr();- expect(v).toBeGreaterThanOrEqual(0);- expect(v).toBeLessThan(1);- }- });-- it("produces consistent values with same seed", () => {- seed(1234);- const a = rr(0, 100);- seed(1234);- const b = rr(0, 100);- expect(a).toBeCloseTo(b);- });-});--describe("randInt()", () => {- beforeAll(() => seed(42));-- it("returns integers in range", () => {- for (let i = 0; i < 100; i++) {- const v = randInt(0, 10);- expect(Number.isInteger(v)).toBe(true);- expect(v).toBeGreaterThanOrEqual(0);- expect(v).toBeLessThan(10);- }- });-});--// ---- weightedRand() -----describe("weightedRand()", () => {- beforeAll(() => seed(99));-- it("always returns a key from the weights object", () => {- const weights = { a: 1, b: 2, c: 7 };- for (let i = 0; i < 100; i++) {- const v = weightedRand(weights);- expect(["a", "b", "c"]).toContain(String(v));- }- });-- it("returns numeric keys as numbers", () => {- const weights = { 1: 1, 2: 2, 3: 7 };- for (let i = 0; i < 100; i++) {- const v = weightedRand(weights);- expect(typeof v).toBe("number");- }- });-- it("strongly favours the high-weight key", () => {- const weights = { rare: 1, common: 999 };- seed(0);- const counts = { rare: 0, common: 0 };- for (let i = 0; i < 500; i++) {- const v = String(weightedRand(weights));- counts[v]++;- }- // common should win more than 98% of the time- expect(counts.common).toBeGreaterThan(480);- });-});--describe("hatch()", () => {- it("captures the hatch angle using the current angle mode at call time", () => {- currentAngleMode.value = "radians";- hatch(8, Math.PI / 2);- expect(mockState.hatch.angle).toBeCloseTo(90);-- currentAngleMode.value = "degrees";- expect(mockState.hatch.angle).toBeCloseTo(90);- });-- it("pairs crossings across polygon arrays with even-odd parity", () => {- hatch(4, 0, { rand: 0, continuous: false, gradient: false });-- const outer = {- a: [- [0, 0],- [10, 0],- [10, 10],- [0, 10],- ],- };- const inner = {- a: [- [3, 3],- [7, 3],- [7, 7],- [3, 7],- ],- };-- const lines = getHatchLines([outer, inner]).filter((line) => !line.isConnector);- const centerLines = lines- .filter((line) => line.y1 === 6 && line.y2 === 6)- .sort((a, b) => a.x1 - b.x1);-- expect(centerLines).toHaveLength(2);- expect(centerLines[0].x1).toBeCloseTo(0);- expect(centerLines[0].x2).toBeCloseTo(3);- expect(centerLines[1].x1).toBeCloseTo(7);- expect(centerLines[1].x2).toBeCloseTo(10);- });-});--describe("arc()", () => {- it("matches p5-style top-half arc geometry in degrees mode", () => {- currentAngleMode.value = "degrees";-- arc(100, 120, 40, 20, 145);+import { arc } from "../../src/core/primitives.js";+import { cos, sin } from "../../src/core/utils.js";- const plot = plotInstances.at(-1);- expect(plot).toBeTruthy();- expect(plot.addSegment).toHaveBeenCalledTimes(2);- expect(plot.addSegment.mock.calls[0][0]).toBeCloseTo(110);- expect(plot.addSegment.mock.calls[1][0]).toBeCloseTo(172.5);- expect(plot.endPlot).toHaveBeenCalledWith(235, 1, true);- expect(plot.draw.mock.calls[0][0]).toBeCloseTo(100 + 40 * cos(20));- expect(plot.draw.mock.calls[0][1]).toBeCloseTo(120 - 40 * sin(20));- });+beforeEach(() => { plots.length = 0; });- it("uses equivalent geometry in radians mode", () => {- currentAngleMode.value = "radians";+describe("arc geometry", () => {+ it.each(["degrees", "radians"])("uses p5-style sweep and coordinates in %s mode", (mode) => {+ currentAngleMode.value = mode;+ const angle = (degrees) => mode === "radians" ? degrees * Math.PI / 180 : degrees;- arc(100, 120, 40, (20 * Math.PI) / 180, (145 * Math.PI) / 180);+ arc(100, 120, 40, angle(20), angle(145));- const plot = plotInstances.at(-1);- expect(plot).toBeTruthy();+ const plot = plots[0];expect(plot.addSegment).toHaveBeenCalledTimes(2);expect(plot.addSegment.mock.calls[0][0]).toBeCloseTo(110);expect(plot.endPlot).toHaveBeenCalledWith(235, 1, true);@@ -416,91 +39,3 @@ describe("arc()", () => {expect(plot.draw.mock.calls[0][1]).toBeCloseTo(120 - 40 * sin(20));});});--describe("Position.moveTo()", () => {- it("interprets its public direction argument using the current angle mode", () => {- currentAngleMode.value = "radians";- noField();-- const pos = new Position(400, 300);- pos.moveTo(Math.PI / 2, 10, 10);-- expect(pos.x).toBeCloseTo(400, 3);- expect(pos.y).toBeCloseTo(290, 3);- });-- it("keeps the internal degree-based path stable", () => {- currentAngleMode.value = "radians";- noField();-- const pos = new Position(400, 300);- pos._moveToDegrees(90, 10, 10);-- expect(pos.x).toBeCloseTo(400, 3);- expect(pos.y).toBeCloseTo(290, 3);- });-});--describe("addField()", () => {- it("supports custom fields declared in radians without losing signed direction", () => {- addField(- "neg-radians-test",- (_t, field) => {- for (let c = 0; c < field.length; c++) {- for (let r = 0; r < field[c].length; r++) {- field[c][r] = -Math.PI / 4;- }- }- return field;- },- { angleMode: "radians" },- );-- activateField("neg-radians-test");- mockState.field.wiggle = 2;-- const pos = new Position(400, 300);- expect(pos.angle()).toBeCloseTo(-90, 3);- });-});--// ---- arc() return value -----describe("arc() return value", () => {- it("returns the Plot instance that was drawn (non-zero sweep)", () => {- const result = arc(0, 0, 50, 0, Math.PI);- expect(result).toBe(plotInstances[0]);- expect(plotInstances[0].draw).toHaveBeenCalled();- });-- it("returns null and constructs no Plot when sweep is zero", () => {- // same start and end angle → sweepDeg === 0- const result = arc(0, 0, 50, 10, 10);- expect(result).toBeNull();- expect(plotInstances).toHaveLength(0);- });-});--// ---- endShape() return value -----describe("endShape() return value", () => {- it("returns a Plot instance (not false) after a valid shape", () => {- beginShape(0);- vertex(0, 0);- vertex(10, 0);- vertex(10, 10);- const result = endShape();- // The Plot mock is pushed into plotInstances by _createSpline inside endShape- expect(result).toBeTruthy();- expect(result).not.toBe(false);- // result is one of the Plot instances constructed during the call- expect(plotInstances).toContain(result);- });-- it("throws on a second endShape() call (the _current=false guard is preserved)", () => {- beginShape(0);- vertex(0, 0);- vertex(10, 0);- vertex(10, 10);- endShape();- expect(() => endShape()).toThrow();- });-});