@nakafa/aksara-contracts 6.0.0 → 6.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/assessment/figure.d.ts +567 -6
  2. package/dist/math/bounds.d.ts +3 -2
  3. package/dist/math/bounds.js +55 -9
  4. package/dist/math/curve.d.ts +64 -0
  5. package/dist/math/curve.js +83 -0
  6. package/dist/math/formula/box.d.ts +61 -0
  7. package/dist/math/formula/box.js +68 -0
  8. package/dist/math/formula/compile.d.ts +11 -0
  9. package/dist/math/formula/compile.js +100 -0
  10. package/dist/math/formula/contour.d.ts +17 -0
  11. package/dist/math/formula/contour.js +162 -0
  12. package/dist/math/formula/field.d.ts +42 -0
  13. package/dist/math/formula/field.js +54 -0
  14. package/dist/math/formula/mesh.d.ts +25 -0
  15. package/dist/math/formula/mesh.js +28 -0
  16. package/dist/math/formula/names.d.ts +4 -0
  17. package/dist/math/formula/names.js +23 -0
  18. package/dist/math/formula/parse.d.ts +10 -0
  19. package/dist/math/formula/parse.js +240 -0
  20. package/dist/math/formula/plane.d.ts +75 -0
  21. package/dist/math/formula/plane.js +121 -0
  22. package/dist/math/formula/reader.d.ts +102 -0
  23. package/dist/math/formula/reader.js +58 -0
  24. package/dist/math/formula/region.d.ts +16 -0
  25. package/dist/math/formula/region.js +94 -0
  26. package/dist/math/formula/sample.d.ts +14 -0
  27. package/dist/math/formula/sample.js +182 -0
  28. package/dist/math/formula/scope.d.ts +41 -0
  29. package/dist/math/formula/scope.js +151 -0
  30. package/dist/math/formula/slider.d.ts +9 -0
  31. package/dist/math/formula/slider.js +32 -0
  32. package/dist/math/formula/space.d.ts +10 -0
  33. package/dist/math/formula/space.js +94 -0
  34. package/dist/math/formula/syntax.d.ts +77 -0
  35. package/dist/math/formula/syntax.js +111 -0
  36. package/dist/math/formula/token.d.ts +43 -0
  37. package/dist/math/formula/token.js +150 -0
  38. package/dist/math/plane.d.ts +148 -5
  39. package/dist/math/plane.js +16 -4
  40. package/dist/math/scene.js +17 -4
  41. package/dist/math/solid.d.ts +124 -0
  42. package/dist/math/solid.js +86 -0
  43. package/dist/math/space.d.ts +214 -0
  44. package/dist/math/space.js +8 -2
  45. package/dist/math/visual.d.ts +545 -3
  46. package/dist/math/visual.js +12 -2
  47. package/package.json +57 -1
@@ -0,0 +1,121 @@
1
+ import { Array as Arr, Option, Result, Schema } from "effect";
2
+ import { SamplePointSchema, } from "#contracts/math/formula/box";
3
+ import { compileFormula, } from "#contracts/math/formula/compile";
4
+ import { contourLines, } from "#contracts/math/formula/contour";
5
+ import { SampleGridSchema } from "#contracts/math/formula/mesh";
6
+ import { readFormula, readRelation } from "#contracts/math/formula/parse";
7
+ import { regionGeometry } from "#contracts/math/formula/region";
8
+ import { sampleCurve } from "#contracts/math/formula/sample";
9
+ const BranchSchema = Schema.Array(SamplePointSchema);
10
+ /**
11
+ * What a formula object draws once sampled: curves, marked points, a shaded
12
+ * region with solid or dashed edges, a surface grid, or the faces of a solid.
13
+ */
14
+ export const FormulaGeometrySchema = Schema.Union([
15
+ Schema.Struct({
16
+ branches: Schema.Array(BranchSchema),
17
+ kind: Schema.Literal("curves"),
18
+ }),
19
+ Schema.Struct({ kind: Schema.Literal("points"), points: BranchSchema }),
20
+ Schema.Struct({
21
+ boundary: Schema.Array(Schema.Struct({ points: BranchSchema, strict: Schema.Boolean })),
22
+ fill: Schema.Array(BranchSchema),
23
+ kind: Schema.Literal("region"),
24
+ }),
25
+ Schema.Struct({ grid: SampleGridSchema, kind: Schema.Literal("grid") }),
26
+ Schema.Struct({
27
+ faces: Schema.Array(BranchSchema),
28
+ kind: Schema.Literal("faces"),
29
+ }),
30
+ ]);
31
+ /** Compiles one authored expression into its evaluator. */
32
+ export function compileText(text) {
33
+ return Result.map(readFormula(text), compileFormula);
34
+ }
35
+ /** Evaluates one compiled formula with one more variable bound. */
36
+ export function evaluateWith(evaluate, scope, name, value) {
37
+ return evaluate({ ...scope, [name]: value });
38
+ }
39
+ /** A plane point, with z kept at zero. */
40
+ function planePoint(x, y) {
41
+ return { x, y, z: 0 };
42
+ }
43
+ /**
44
+ * Places one formula point with the sliders' current values. A coordinate
45
+ * that is not finite there, such as ln(0), places nothing.
46
+ */
47
+ export function planeFormulaPoint(point, scope) {
48
+ return Result.gen(function* () {
49
+ const x = (yield* compileText(point.x))(scope);
50
+ const y = (yield* compileText(point.y))(scope);
51
+ return Number.isFinite(x) && Number.isFinite(y)
52
+ ? Option.some(planePoint(x, y))
53
+ : Option.none();
54
+ });
55
+ }
56
+ /**
57
+ * Places every point of a path, back to the first for a loop; one point that
58
+ * is not finite breaks it.
59
+ */
60
+ function pathBranch(points, closed, scope) {
61
+ return Result.map(Result.all(Arr.map(points, (point) => planeFormulaPoint(point, scope))), (placed) => Option.match(Option.all(placed), {
62
+ onNone: () => [],
63
+ onSome: (corners) => [
64
+ closed ? [...corners, ...Arr.take(corners, 1)] : corners,
65
+ ],
66
+ }));
67
+ }
68
+ /**
69
+ * Samples one plane formula object inside its frame. `named` holds the input
70
+ * values a function must hit exactly, such as the x of each of its labels.
71
+ */
72
+ export function planeFormulaGeometry(object, box, scope, named = []) {
73
+ return Result.gen(function* () {
74
+ if (object.kind === "function") {
75
+ const f = yield* compileText(object.formula);
76
+ const axis = object.inputAxis ?? "x";
77
+ const range = object.domain ?? box[axis];
78
+ const branches = sampleCurve((input) => {
79
+ const output = evaluateWith(f, scope, axis, input);
80
+ return axis === "x"
81
+ ? planePoint(input, output)
82
+ : planePoint(output, input);
83
+ }, box, range, named);
84
+ return { branches, kind: "curves" };
85
+ }
86
+ if (object.kind === "parametric") {
87
+ const fx = yield* compileText(object.x);
88
+ const fy = yield* compileText(object.y);
89
+ const branches = sampleCurve((t) => planePoint(evaluateWith(fx, scope, "t", t), evaluateWith(fy, scope, "t", t)), box, object.parameter);
90
+ return { branches, kind: "curves" };
91
+ }
92
+ if (object.kind === "polar") {
93
+ const fr = yield* compileText(object.radius);
94
+ const branches = sampleCurve((theta) => {
95
+ const r = evaluateWith(fr, scope, "theta", theta);
96
+ return planePoint(r * Math.cos(theta), r * Math.sin(theta));
97
+ }, box, object.angle);
98
+ return { branches, kind: "curves" };
99
+ }
100
+ if (object.kind === "marker") {
101
+ const placed = yield* planeFormulaPoint(object, scope);
102
+ return { kind: "points", points: Option.toArray(placed) };
103
+ }
104
+ if (object.kind === "path" || object.kind === "loop") {
105
+ const branches = yield* pathBranch(object.points, object.kind === "loop", scope);
106
+ return { branches, kind: "curves" };
107
+ }
108
+ if (object.kind === "implicit") {
109
+ const relation = yield* readRelation(object.equation);
110
+ const left = compileFormula(relation.left);
111
+ const right = compileFormula(relation.right);
112
+ /** How far the two sides of the equation are apart at a point. */
113
+ const field = (x, y) => {
114
+ const point = { ...scope, x, y };
115
+ return left(point) - right(point);
116
+ };
117
+ return { branches: contourLines(field, box), kind: "curves" };
118
+ }
119
+ return yield* regionGeometry(object.inequalities, box, scope);
120
+ });
121
+ }
@@ -0,0 +1,102 @@
1
+ import { Option, Result, Schema } from "effect";
2
+ import { FormulaError, type FormulaProblem } from "#contracts/math/formula/syntax";
3
+ /**
4
+ * The tokens of one formula and the reader's place in them: the token it
5
+ * stands at and how many absolute bars are open around it.
6
+ */
7
+ declare const ReaderSchema: Schema.Struct<{
8
+ readonly bars: Schema.mutableKey<Schema.Int>;
9
+ readonly index: Schema.mutableKey<Schema.Int>;
10
+ readonly length: Schema.Int;
11
+ readonly tokens: Schema.$Array<Schema.Union<readonly [Schema.Struct<{
12
+ readonly kind: Schema.Literal<"number">;
13
+ readonly position: Schema.Int;
14
+ readonly value: Schema.Finite;
15
+ }>, Schema.Struct<{
16
+ readonly kind: Schema.Literal<"name">;
17
+ readonly name: Schema.String;
18
+ readonly position: Schema.Int;
19
+ }>, Schema.Struct<{
20
+ readonly kind: Schema.Literal<"symbol">;
21
+ readonly position: Schema.Int;
22
+ readonly symbol: Schema.Literals<readonly ["(", ")", "*", "+", ",", "-", "/", "^", "_", "|", "°", "√"]>;
23
+ }>, Schema.Struct<{
24
+ readonly comparison: Schema.Literals<readonly ["=", "<", "<=", ">", ">="]>;
25
+ readonly kind: Schema.Literal<"comparison">;
26
+ readonly position: Schema.Int;
27
+ }>]>>;
28
+ }>;
29
+ export type Reader = typeof ReaderSchema.Type;
30
+ /** Builds the failure for one problem at one place in the text. */
31
+ export declare function problemAt(problem: FormulaProblem, position: number, message: string): Result.Result<never, FormulaError>;
32
+ /** Returns the current token without moving past it. */
33
+ export declare function peek(reader: Reader): Option.Option<{
34
+ readonly kind: "number";
35
+ readonly position: number;
36
+ readonly value: number;
37
+ } | {
38
+ readonly kind: "name";
39
+ readonly name: string;
40
+ readonly position: number;
41
+ } | {
42
+ readonly kind: "symbol";
43
+ readonly position: number;
44
+ readonly symbol: "(" | ")" | "*" | "+" | "," | "-" | "/" | "^" | "_" | "|" | "°" | "√";
45
+ } | {
46
+ readonly comparison: "<" | "<=" | "=" | ">" | ">=";
47
+ readonly kind: "comparison";
48
+ readonly position: number;
49
+ }>;
50
+ /** Whether the current token is one symbol. */
51
+ export declare function at(reader: Reader, symbol: string): boolean;
52
+ /** Where the current token starts, or the end of the text. */
53
+ export declare function here(reader: Reader): number;
54
+ /** Moves past one expected symbol, or fails where it should stand. */
55
+ export declare function expect(reader: Reader, symbol: string): Result.Result<string, never> | Result.Result<never, FormulaError>;
56
+ /** Starts reading the tokens of one formula. */
57
+ export declare function startReader(text: string): Result.Result<{
58
+ bars: number;
59
+ index: number;
60
+ readonly length: number;
61
+ readonly tokens: readonly ({
62
+ readonly kind: "number";
63
+ readonly position: number;
64
+ readonly value: number;
65
+ } | {
66
+ readonly kind: "name";
67
+ readonly name: string;
68
+ readonly position: number;
69
+ } | {
70
+ readonly kind: "symbol";
71
+ readonly position: number;
72
+ readonly symbol: "(" | ")" | "*" | "+" | "," | "-" | "/" | "^" | "_" | "|" | "°" | "√";
73
+ } | {
74
+ readonly comparison: "<" | "<=" | "=" | ">" | ">=";
75
+ readonly kind: "comparison";
76
+ readonly position: number;
77
+ })[];
78
+ }, FormulaError>;
79
+ /** Fails on the first token a complete reading left behind. */
80
+ export declare function finished(reader: Reader): Result.Result<never, FormulaError> | Result.Result<{
81
+ bars: number;
82
+ index: number;
83
+ readonly length: number;
84
+ readonly tokens: readonly ({
85
+ readonly kind: "number";
86
+ readonly position: number;
87
+ readonly value: number;
88
+ } | {
89
+ readonly kind: "name";
90
+ readonly name: string;
91
+ readonly position: number;
92
+ } | {
93
+ readonly kind: "symbol";
94
+ readonly position: number;
95
+ readonly symbol: "(" | ")" | "*" | "+" | "," | "-" | "/" | "^" | "_" | "|" | "°" | "√";
96
+ } | {
97
+ readonly comparison: "<" | "<=" | "=" | ">" | ">=";
98
+ readonly kind: "comparison";
99
+ readonly position: number;
100
+ })[];
101
+ }, never>;
102
+ export {};
@@ -0,0 +1,58 @@
1
+ import { Array as Arr, Option, Result, Schema } from "effect";
2
+ import { FormulaError, } from "#contracts/math/formula/syntax";
3
+ import { FormulaTokenSchema, tokenizeFormula, } from "#contracts/math/formula/token";
4
+ /**
5
+ * The tokens of one formula and the reader's place in them: the token it
6
+ * stands at and how many absolute bars are open around it.
7
+ */
8
+ const ReaderSchema = Schema.Struct({
9
+ bars: Schema.mutableKey(Schema.Int),
10
+ index: Schema.mutableKey(Schema.Int),
11
+ length: Schema.Int,
12
+ tokens: Schema.Array(FormulaTokenSchema),
13
+ });
14
+ /** Builds the failure for one problem at one place in the text. */
15
+ export function problemAt(problem, position, message) {
16
+ return Result.fail(new FormulaError({ message, position, problem }));
17
+ }
18
+ /** Returns the current token without moving past it. */
19
+ export function peek(reader) {
20
+ return Arr.get(reader.tokens, reader.index);
21
+ }
22
+ /** Whether the current token is one symbol. */
23
+ export function at(reader, symbol) {
24
+ return Option.exists(peek(reader), (token) => token.kind === "symbol" && token.symbol === symbol);
25
+ }
26
+ /** Where the current token starts, or the end of the text. */
27
+ export function here(reader) {
28
+ return Option.match(peek(reader), {
29
+ onNone: () => reader.length,
30
+ onSome: (token) => token.position,
31
+ });
32
+ }
33
+ /** Moves past one expected symbol, or fails where it should stand. */
34
+ export function expect(reader, symbol) {
35
+ if (!at(reader, symbol)) {
36
+ return problemAt("group-unclosed", here(reader), `Expected "${symbol}".`);
37
+ }
38
+ reader.index += 1;
39
+ return Result.succeed(symbol);
40
+ }
41
+ /** Starts reading the tokens of one formula. */
42
+ export function startReader(text) {
43
+ return Result.map(tokenizeFormula(text), (tokens) => ({
44
+ bars: 0,
45
+ index: 0,
46
+ length: text.length,
47
+ tokens,
48
+ }));
49
+ }
50
+ /** Fails on the first token a complete reading left behind. */
51
+ export function finished(reader) {
52
+ return Option.match(peek(reader), {
53
+ onNone: () => Result.succeed(reader),
54
+ onSome: (token) => token.kind === "comparison"
55
+ ? problemAt("comparison-unexpected", token.position, "Expected an expression, not an equation or an inequality.")
56
+ : problemAt("operator-expected", token.position, "Expected an operator or the end of the formula."),
57
+ });
58
+ }
@@ -0,0 +1,16 @@
1
+ import { Result } from "effect";
2
+ import { type SampleBox } from "#contracts/math/formula/box";
3
+ import { type FormulaScope } from "#contracts/math/formula/compile";
4
+ /** The region where every inequality holds, with each edge marked strict or not. */
5
+ export declare function regionGeometry(inequalities: readonly [string, ...string[]], box: SampleBox, scope: FormulaScope): Result.Result<{
6
+ boundary: {
7
+ readonly points: readonly {
8
+ readonly x: number;
9
+ readonly y: number;
10
+ readonly z: number;
11
+ }[];
12
+ readonly strict: boolean;
13
+ }[];
14
+ fill: readonly import("./sample.js").SampleBranch[];
15
+ kind: "region";
16
+ }, import("./syntax.js").FormulaError>;
@@ -0,0 +1,94 @@
1
+ import { Array as Arr, MutableList, Option, Order, Result, Schema, } from "effect";
2
+ import { SamplePointSchema, } from "#contracts/math/formula/box";
3
+ import { compileFormula, } from "#contracts/math/formula/compile";
4
+ import { contourFill, contourLines, } from "#contracts/math/formula/contour";
5
+ import { readRelation } from "#contracts/math/formula/parse";
6
+ /** How far a boundary piece lies from one inequality's edge, and whether that edge is strict. */
7
+ const ConstraintGapSchema = Schema.Struct({
8
+ gap: Schema.Finite,
9
+ strict: Schema.Boolean,
10
+ });
11
+ /** One piece of a region's outline, between two consecutive samples. */
12
+ const EdgePieceSchema = Schema.Struct({
13
+ next: SamplePointSchema,
14
+ point: SamplePointSchema,
15
+ strict: Schema.Boolean,
16
+ });
17
+ /** One run of an outline that is all strict or all inclusive. */
18
+ const EdgeRunSchema = Schema.Struct({
19
+ points: Schema.Array(SamplePointSchema),
20
+ strict: Schema.Boolean,
21
+ });
22
+ /**
23
+ * Joins consecutive outline pieces of the same kind into one line, so a
24
+ * renderer draws a few dashed and solid edges instead of every short piece.
25
+ */
26
+ function edgeRuns(pieces) {
27
+ const runs = MutableList.make();
28
+ let points = MutableList.make();
29
+ let strict = false;
30
+ Arr.forEach(pieces, (piece, index) => {
31
+ if (index === 0 || piece.strict !== strict) {
32
+ if (index > 0) {
33
+ MutableList.append(runs, {
34
+ points: MutableList.toArray(points),
35
+ strict,
36
+ });
37
+ }
38
+ points = MutableList.make();
39
+ MutableList.append(points, piece.point);
40
+ ({ strict } = piece);
41
+ }
42
+ MutableList.append(points, piece.next);
43
+ });
44
+ MutableList.append(runs, { points: MutableList.toArray(points), strict });
45
+ return MutableList.toArray(runs);
46
+ }
47
+ /** The signed room an inequality leaves at a point: positive where it holds. */
48
+ function margin(text) {
49
+ return Result.map(readRelation(text), ({ comparison, left, right }) => {
50
+ const leftValue = compileFormula(left);
51
+ const rightValue = compileFormula(right);
52
+ const below = comparison === "<" || comparison === "<=";
53
+ return {
54
+ field: (scope) => (x, y) => {
55
+ const point = { ...scope, x, y };
56
+ const gap = rightValue(point) - leftValue(point);
57
+ return below ? gap : -gap;
58
+ },
59
+ strict: comparison === "<" || comparison === ">",
60
+ };
61
+ });
62
+ }
63
+ /** The region where every inequality holds, with each edge marked strict or not. */
64
+ export function regionGeometry(inequalities, box, scope) {
65
+ return Result.map(Result.all(Arr.map(inequalities, margin)), (margins) => {
66
+ const constraints = Arr.map(margins, (each) => ({
67
+ field: each.field(scope),
68
+ strict: each.strict,
69
+ }));
70
+ /** The tightest margin at a point: where it is not negative, every inequality holds. */
71
+ const field = (x, y) => Math.min(...Arr.map(constraints, (each) => each.field(x, y)));
72
+ const byGap = Order.mapInput(Order.Number, (piece) => piece.gap);
73
+ /** Whether the inequality nearest a boundary piece is strict, so it draws dashed. */
74
+ const strictAt = (from, to) => {
75
+ const x = (from.x + to.x) / 2;
76
+ const y = (from.y + to.y) / 2;
77
+ const gaps = Arr.map(constraints, (each) => ({
78
+ gap: Math.abs(each.field(x, y)),
79
+ strict: each.strict,
80
+ }));
81
+ return Option.exists(Arr.head(Arr.sort(gaps, byGap)), ({ strict }) => strict);
82
+ };
83
+ const boundary = Arr.flatMap(contourLines(field, box), (line) => edgeRuns(Arr.zipWith(line, Arr.drop(line, 1), (point, next) => ({
84
+ next,
85
+ point,
86
+ strict: strictAt(point, next),
87
+ }))));
88
+ return {
89
+ boundary,
90
+ fill: contourFill(field, box),
91
+ kind: "region",
92
+ };
93
+ });
94
+ }
@@ -0,0 +1,14 @@
1
+ import { type SampleBox, type SamplePoint, type SampleRange } from "#contracts/math/formula/box";
2
+ /** One visible, unbroken run of a sampled curve, in authored coordinates. */
3
+ export type SampleBranch = readonly SamplePoint[];
4
+ /** Where a curve stands for one parameter value; NaN where it is undefined. */
5
+ export type SampleTrace = (parameter: number) => SamplePoint;
6
+ /** Fewest samples on each visible branch, the Aksara visuals rule. */
7
+ export declare const MINIMUM_BRANCH_SAMPLES = 200;
8
+ /**
9
+ * Samples one curve inside its frame. Every visible branch holds at least 200
10
+ * samples, more where it bends or climbs, with an exact sample at each named
11
+ * parameter value and at each frame edge it crosses. Breaks, undefined
12
+ * stretches, and asymptotes split the curve into separate branches.
13
+ */
14
+ export declare function sampleCurve(trace: SampleTrace, box: SampleBox, range: SampleRange, named?: readonly number[]): readonly SampleBranch[];
@@ -0,0 +1,182 @@
1
+ import { Array as Arr, MutableList, Order, Schema } from "effect";
2
+ import { clipSegment, finite, insideBox, SamplePointSchema, spanDistance, } from "#contracts/math/formula/box";
3
+ /** Fewest samples on each visible branch, the Aksara visuals rule. */
4
+ export const MINIMUM_BRANCH_SAMPLES = 200;
5
+ const BASE_SAMPLES = 2 * MINIMUM_BRANCH_SAMPLES;
6
+ const MAXIMUM_DEPTH = 12;
7
+ const MAXIMUM_SAMPLES = 24_000;
8
+ /** Largest gap between a curve and its chord, as a fraction of the frame. */
9
+ const FLATNESS = 0.0015;
10
+ /** A chord longer than this is split further even where the curve looks flat. */
11
+ const JUMP = 0.2;
12
+ /** A chord this long at the deepest split crosses a break, a step, or an asymptote. */
13
+ const BREAK = 0.004;
14
+ /** One sample: its parameter, its point, and whether a break follows it. */
15
+ const SampleSchema = Schema.Struct({
16
+ broken: Schema.mutableKey(Schema.Boolean),
17
+ parameter: Schema.Finite,
18
+ point: SamplePointSchema,
19
+ });
20
+ /**
21
+ * Splits one interval until the curve is flat between its samples, and marks
22
+ * a break where the chord still jumps at the deepest split or the curve is
23
+ * undefined inside it.
24
+ */
25
+ function refine(trace, box, from, to, depth, out) {
26
+ const parameter = (from.parameter + to.parameter) / 2;
27
+ const middle = { broken: false, parameter, point: trace(parameter) };
28
+ const bothFinite = finite(from.point) && finite(to.point);
29
+ if (out.length >= MAXIMUM_SAMPLES) {
30
+ from.broken = from.broken || !bothFinite;
31
+ return;
32
+ }
33
+ if (depth >= MAXIMUM_DEPTH) {
34
+ from.broken =
35
+ from.broken ||
36
+ !bothFinite ||
37
+ spanDistance(box, from.point, to.point) > BREAK;
38
+ return;
39
+ }
40
+ if (bothFinite && finite(middle.point)) {
41
+ const chordMiddle = {
42
+ x: (from.point.x + to.point.x) / 2,
43
+ y: (from.point.y + to.point.y) / 2,
44
+ z: (from.point.z + to.point.z) / 2,
45
+ };
46
+ const flat = spanDistance(box, chordMiddle, middle.point) <= FLATNESS;
47
+ const short = spanDistance(box, from.point, to.point) <= JUMP;
48
+ if (flat && short) {
49
+ return;
50
+ }
51
+ }
52
+ else if (!(finite(from.point) || finite(to.point) || finite(middle.point))) {
53
+ from.broken = true;
54
+ return;
55
+ }
56
+ refine(trace, box, from, middle, depth + 1, out);
57
+ MutableList.append(out, middle);
58
+ refine(trace, box, middle, to, depth + 1, out);
59
+ }
60
+ /** Samples a parameter range densely and adaptively, keeping named values exact. */
61
+ function sampleRange(trace, box, min, max, named) {
62
+ const uniform = Arr.makeBy(BASE_SAMPLES + 1, (index) => min + ((max - min) * index) / BASE_SAMPLES);
63
+ const parameters = Arr.dedupe(Arr.sort(Arr.appendAll(uniform, Arr.filter(named, (value) => value > min && value < max)), Order.Number));
64
+ const base = Arr.map(parameters, (parameter) => ({
65
+ broken: false,
66
+ parameter,
67
+ point: trace(parameter),
68
+ }));
69
+ const out = MutableList.make();
70
+ Arr.forEach(base, (sample, index) => {
71
+ MutableList.append(out, sample);
72
+ const next = base[index + 1];
73
+ if (next) {
74
+ refine(trace, box, sample, next, 0, out);
75
+ }
76
+ });
77
+ return Arr.sort(MutableList.toArray(out), Order.mapInput(Order.Number, (sample) => sample.parameter));
78
+ }
79
+ /** The point a fraction of the way along a segment, and its parameter. */
80
+ function along(from, to, fraction) {
81
+ /** One coordinate the same fraction of the way along. */
82
+ const at = (axis) => from.point[axis] + (to.point[axis] - from.point[axis]) * fraction;
83
+ return {
84
+ broken: false,
85
+ parameter: from.parameter + (to.parameter - from.parameter) * fraction,
86
+ point: { x: at("x"), y: at("y"), z: at("z") },
87
+ };
88
+ }
89
+ const EDGE_STEPS = 48;
90
+ /**
91
+ * Finds where the curve itself crosses the frame edge between a sample inside
92
+ * and a sample outside, by halving the parameter interval, so the edge sample
93
+ * lies on the curve rather than on a chord.
94
+ */
95
+ function edge(trace, box, inner, outer) {
96
+ let inside = inner.parameter;
97
+ let outside = outer.parameter;
98
+ for (let step = 0; step < EDGE_STEPS; step += 1) {
99
+ const middle = (inside + outside) / 2;
100
+ if (insideBox(box, trace(middle))) {
101
+ inside = middle;
102
+ }
103
+ else {
104
+ outside = middle;
105
+ }
106
+ }
107
+ return { broken: false, parameter: inside, point: trace(inside) };
108
+ }
109
+ /** The sample where a visible piece of a segment starts: its start, or its entry on the curve. */
110
+ function entry(trace, box, from, to, clip) {
111
+ if (clip.enter === 0) {
112
+ return from;
113
+ }
114
+ return clip.leave === 1
115
+ ? edge(trace, box, to, from)
116
+ : along(from, to, clip.enter);
117
+ }
118
+ /** The sample where a visible piece of a segment ends: its end, or its exit on the curve. */
119
+ function exit(trace, box, from, to, clip) {
120
+ if (clip.leave === 1) {
121
+ return to;
122
+ }
123
+ return clip.enter === 0
124
+ ? edge(trace, box, from, to)
125
+ : along(from, to, clip.leave);
126
+ }
127
+ /** Collects runs of samples, keeping only runs of two or more. */
128
+ function runCollector() {
129
+ const runs = MutableList.make();
130
+ let run = MutableList.make();
131
+ return {
132
+ add: (sample) => MutableList.append(run, sample),
133
+ close: () => {
134
+ const items = MutableList.toArray(run);
135
+ if (Arr.isReadonlyArrayNonEmpty(items) && items.length > 1) {
136
+ MutableList.append(runs, items);
137
+ }
138
+ run = MutableList.make();
139
+ },
140
+ empty: () => run.length === 0,
141
+ runs: () => MutableList.toArray(runs),
142
+ };
143
+ }
144
+ /** Splits samples into visible runs inside the frame, cut exactly at its edges. */
145
+ function visibleRuns(trace, box, samples) {
146
+ const collector = runCollector();
147
+ Arr.forEach(samples, (from, index) => {
148
+ const to = samples[index + 1];
149
+ const clip = to && !from.broken && finite(from.point) && finite(to.point)
150
+ ? clipSegment(box, from.point, to.point)
151
+ : undefined;
152
+ if (!(to && clip)) {
153
+ collector.close();
154
+ return;
155
+ }
156
+ if (clip.enter > 0 || collector.empty()) {
157
+ collector.close();
158
+ collector.add(entry(trace, box, from, to, clip));
159
+ }
160
+ collector.add(exit(trace, box, from, to, clip));
161
+ if (clip.leave < 1) {
162
+ collector.close();
163
+ }
164
+ });
165
+ collector.close();
166
+ return collector.runs();
167
+ }
168
+ /**
169
+ * Samples one curve inside its frame. Every visible branch holds at least 200
170
+ * samples, more where it bends or climbs, with an exact sample at each named
171
+ * parameter value and at each frame edge it crosses. Breaks, undefined
172
+ * stretches, and asymptotes split the curve into separate branches.
173
+ */
174
+ export function sampleCurve(trace, box, range, named = []) {
175
+ const runs = visibleRuns(trace, box, sampleRange(trace, box, range.min, range.max, named));
176
+ return Arr.flatMap(runs, (run) => {
177
+ const dense = run.length >= MINIMUM_BRANCH_SAMPLES
178
+ ? [run]
179
+ : visibleRuns(trace, box, sampleRange(trace, box, Arr.headNonEmpty(run).parameter, Arr.lastNonEmpty(run).parameter, named));
180
+ return Arr.map(dense, (each) => Arr.map(each, (sample) => sample.point));
181
+ });
182
+ }
@@ -0,0 +1,41 @@
1
+ import { Schema } from "effect";
2
+ import type { SampleBox } from "#contracts/math/formula/box";
3
+ import type { FormulaScope } from "#contracts/math/formula/compile";
4
+ import type { FormulaParameter } from "#contracts/math/formula/field";
5
+ import type { FormulaGeometry } from "#contracts/math/formula/plane";
6
+ import type { PlaneMathObject } from "#contracts/math/plane";
7
+ import type { SpaceMathObject } from "#contracts/math/space";
8
+ /** One authored formula of an object: where it stands and what it may read. */
9
+ declare const FormulaFieldSchema: Schema.Struct<{
10
+ readonly path: Schema.$Array<Schema.Union<readonly [Schema.String, Schema.Int]>>;
11
+ readonly relation: Schema.Boolean;
12
+ readonly text: Schema.String;
13
+ readonly variables: Schema.$Array<Schema.String>;
14
+ }>;
15
+ export type FormulaField = typeof FormulaFieldSchema.Type;
16
+ /** Builds one expression field. */
17
+ export declare function expression(path: readonly (string | number)[], text: string, variables: readonly string[]): FormulaField;
18
+ /**
19
+ * Lists every formula a plane object holds and the variables each may read:
20
+ * its input axis for a function, t for a parametric curve, theta for a polar
21
+ * curve, and x and y for an equation or a region.
22
+ */
23
+ export declare function planeFormulaFields(object: PlaneMathObject): readonly FormulaField[];
24
+ /**
25
+ * Lists every formula a space object holds and the variables each may read:
26
+ * t for a curve, x and y for a surface z = f(x, y), u and v for a parametric
27
+ * surface, and the axis variable for a solid of revolution.
28
+ */
29
+ export declare function spaceFormulaFields(object: SpaceMathObject): readonly FormulaField[];
30
+ /** Reports one formula that reads a name it may not, at its root path. */
31
+ export declare function strayIssues(field: FormulaField, declared: readonly string[], root: readonly (string | number)[]): Schema.FilterIssue[];
32
+ /**
33
+ * Reports every formula that reads a name its object does not offer, and every
34
+ * slider whose name repeats an earlier one.
35
+ */
36
+ export declare function formulaScopeIssues<Object>(objects: readonly Object[], fields: (object: Object) => readonly FormulaField[], parameters: readonly FormulaParameter[]): readonly Schema.FilterIssue[];
37
+ /** Each slider's starting value by its name, the scope a scene first draws with. */
38
+ export declare function parameterScope(parameters: readonly FormulaParameter[]): FormulaScope;
39
+ /** Whether sampled geometry shows anything inside its frame. */
40
+ export declare function geometryVisible(geometry: FormulaGeometry, box: SampleBox): boolean;
41
+ export {};