Repository Public MIT
1<!--2ORIX Calc3File: docs/architecture/graph-engine.md4Author: Simon-Pierre Boucher5Contact: contact@spboucher.ai6-->7# Graph engine (`ORIXGraph` and `ORIXFeatureGraph`)89Graphing is split in two packages. `ORIXGraph` is pure computation: expressions in, render-ready geometry out, with no10SwiftUI, UIKit or CoreGraphics. `ORIXFeatureGraph` owns the state of the Graph environment and the one renderer that turns11that geometry into pixels. The engine's public surface is in [`Packages/ORIXGraph/API.md`](../../Packages/ORIXGraph/API.md);12what it guarantees, the measured accuracy and the limits are in13[`Packages/ORIXGraph/VALIDATION.md`](../../Packages/ORIXGraph/VALIDATION.md).1415The rule the whole pipeline serves: *a graph must not misrepresent a function*. A curve is never joined across a pole or a16jump, an oscillation faster than the pixels is drawn as a band and not as a fake line, and anything the engine could not17establish is reported as a notice.1819## Pipeline2021```mermaid22flowchart TD23 Text["Entry text<br/>'a*sin(x)/x', 'x^2 + y^2 = 25', 'z = x*y'"] --> Parser["PlotParser.parse<br/>(ORIXExpression parser + EvalContext)"]24 Parser --> Item["PlotItem<br/>kind · parameters · domain · style"]25 Ctx["EvalContext<br/>angle mode · slider values · user functions"] --> Compile26 Item --> Compile["PlotItem.compiled(context:)<br/>CompiledExpression closures, NaN where undefined"]27 Compile --> Exp["Sampler.sampleExplicit / sampleExplicitX<br/>adaptive, discontinuity classification, aliased bands"]28 Compile --> Cur["Sampler.sampleParametric / samplePolar"]29 Compile --> Imp["ImplicitPlotter.plot / region<br/>adaptive marching squares, validated crossings"]30 Compile --> Sur["SurfacePlotter.mesh<br/>SurfaceMesh"]31 Exp --> Geo["PlotGeometry<br/>polylines · bands · discontinuities · holes · markers · fill · notices"]32 Cur --> Geo33 Imp --> Geo34 VP["Viewport<br/>window + pixel size"] --> Exp35 VP --> Cur36 VP --> Imp37 Geo --> R2["GraphRenderer (SwiftUI Canvas)<br/>grid · axes · curves · bands · holes · asymptote guides · regions"]38 Sur --> Norm["SurfaceMesh.normalized()<br/>cube [−1, 1]³"]39 Norm --> Paint["PainterRenderer.project<br/>Camera3D, far → near"]40 Paint --> R3["Surface3DView (SwiftUI Canvas)"]41 Compile --> An["GraphAnalysis<br/>roots · extrema · intersections · tangent · integral · arc length · trace · table"]42 An --> R243```4445`GraphEngine.geometry(for:viewport:context:)` is the single entry point from a `PlotItem` to a `PlotGeometry`. It is46synchronous and thread-safe; `geometryAsync` and `geometries` are `@concurrent` wrappers that never run on the main actor47and throw `CancellationError`.4849## Engine source files5051All under `Packages/ORIXGraph/Sources/ORIXGraph/`.5253| File | Role |54|---|---|55| `PlotParser.swift` | Entry text → `PlotItem` (explicit, `x = g(y)`, parametric, polar, implicit, inequality, points, surface, parameter) |56| `PlotItem.swift` | Plot definitions as pure data and their compilation to closures |57| `Viewport.swift` | Visible window in function coordinates with its pixel size; screen mapping, pan, zoom, equal aspect, robust auto-fit |58| `Sampler.swift` | Adaptive sampler for `y = f(x)` |59| `CurveSampler.swift` | Adaptive sampler for parametric and polar curves |60| `ImplicitPlotter.swift` | Implicit curves `F(x, y) = 0` and inequality regions |61| `Surface.swift` | 3D surfaces `z = f(x, y)`, parametric surfaces, contours, inspection |62| `Camera3D.swift` | Orbit camera matrices, point projection, painter's-algorithm ordering |63| `Analysis.swift` | Roots, extrema, intersections, tangent, derivative curve, integrals with shading, arc length, trace, tables |64| `Ticks.swift` | Axis ticks (1-2-5 steps or multiples of π), minimal-digit labels |65| `Geometry.swift` | Value types shared by the samplers (points, polylines, envelope bands, discontinuities, notices) |66| `Data.swift` | Scatter / series helpers, least-squares line for the fit overlay, CSV export |67| `GraphEngine.swift` | Entry point, async wrappers, auto-fit of several items |6869## Stage 1 — text to `PlotItem`7071`PlotParser.parse(_:context:)` uses the expression parser of `ORIXExpression` and classifies the line:7273| Text | `PlotItem.kind` |74|---|---|75| `sin(x)`, `y = x^2`, `f(x) = x^2` | `.explicit` |76| `x = y^2` | `.explicitX` |77| `(cos(t), sin(2t))` | `.parametric` |78| `r = 1 - cos(θ)` | `.polar` |79| `x^2 + y^2 = 25` | `.implicit(lhs:rhs:)` |80| `y < x^2`, `1 < x < 2` | `.inequality(condition:boundaries:)` |81| `(1, 2), (3, 4)` | `.points` |82| `z = x*y` | `.surface` |83| `a = 3` | `.parameter(name:value:)` (sets a slider; not drawable) |8485`item.parameters` lists the free identifiers; the UI creates one slider per name and injects the values through86`EvalContext.variables`. `item.compiled(context:)` turns the expressions into `Double` closures that return NaN where the87expression is undefined; compilation is repeated on every slider change.8889## Stage 2 — sampling9091### Explicit sampler (`Sampler.sampleExplicit`)9293- **Grid**: one sample per pixel column, no jitter. Each column is also tested at one interior point whose position varies94 from column to column, so that no frequency can alias with both the grid and the test points.95- **Refinement**: a column is bisected (up to 2⁶ pieces, `SamplerOptions.maxDepth` 6) while the screen distance to the96 chord exceeds 0.2 px (`tolerance`); inside refined regions three points per piece are tested.97- **Aliasing**: columns that rise by more than 8 px, or whose test fails, get 7 irregular probes. Three or more reversals98 (or two that are not a single adverse step, decided with 8 more samples) mean aliasing: the column becomes a min/max99 `EnvelopeBand`, and inside a band every column is probed.100- **Discontinuity classification**: at the refinement cap, a remaining gap is bisected down to adjacent doubles. If it101 shrinks, the piece is continuous. Otherwise one-sided limits are estimated from geometric sequences of samples and the102 break is classified as `.jump`, `.pole` or `.essential`.103- **Domain**: undefined samples are bracketed by bisection to adjacent doubles (`.undefinedInterval`). An isolated104 undefined point with equal finite limits is a `.removable` discontinuity: the curve is drawn through and a hole marker105 is emitted.106- **Even poles**: poles between two samples off the same edge are found by golden-section search on `|f|`.107- **Clipping**: polylines are clipped (not clamped) to the viewport ± one viewport height.108109### Parametric and polar (`CurveSampler`)110111512 initial samples (`CurveOptions.initialSamples`), refined by screen-space deviation up to depth 10, broken at undefined112values and jumps. Jump versus pole is decided by distance from the screen (≥ 1000 viewport sizes = pole).113114### Implicit curves and regions (`ImplicitPlotter`)115116A coarse lattice (8 px) is scanned first; cells with a sign change, an undefined corner, or `|F|` small compared with its117variation are refined, and marching squares runs at 2 px (`ImplicitOptions.cellSize`) with propagation into neighbouring118coarse cells. Every crossing is validated: `F` at the interpolated vertex must be far below both end values, otherwise the119bracket is shrunk 16-fold and must have come down (a zero) rather than stayed (a jump) or grown (a pole). Segments are120stitched through shared lattice edges. The result carries `reliable` and its reasons; inequality fills are 2 px cells.121122## Stage 3 — geometry123124`PlotGeometry` is the contract between engine and renderer, in function coordinates:125126| Field | How it must be drawn |127|---|---|128| `polylines` | Stroke each one separately; never join two. A single-point polyline is an isolated point |129| `bands` | Fill the band polygon at reduced opacity; do not stroke a line through it |130| `discontinuities` | Poles may get a dashed asymptote guide; removable ones get hole markers |131| `holes`, `markers` | Open circles; scatter points |132| `fill`, `strictBoundary` | Inequality region; dashed boundary for `<` / `>` |133| `notices`, `isComplete` | Shown to the user (`.aliased`, `.unreliable`, `.incomplete`, `.rejectedFalseContour`, `.info`) |134135## Stage 4 — rendering (`ORIXFeatureGraph`)136137All under `Packages/ORIXFeatureGraph/Sources/ORIXFeatureGraph/`.138139- `GraphModel.swift` holds entries, sliders, the viewport and the sampled geometry. Sampling runs off the main actor, one140 pass per entry at a time; a request that arrives meanwhile marks the entry dirty, the running pass is applied when it141 lands and the latest state is sampled next. Geometry is stored with the viewport it was sampled for and drawn through142 the *current* viewport, so pan and zoom follow the fingers while fresh samples are on their way.143- `GraphRenderer.swift` is the one 2D renderer (grid, axes, curves, bands, holes, asymptote guides, regions, markers). It144 is shared by the interactive graph (`GraphCanvasView.swift`), the embeddable preview used by other environments145 (`GraphPreview.swift`, exposed through `FeatureRegistry.graphPreview`), the exports and the tests.146- The render tests (`Packages/ORIXFeatureGraph/Tests/ORIXFeatureGraphTests/RenderTests.swift`) rasterise the renderer and inspect pixels: no stroke147 in the column of the asymptote of `1/x`, none at any asymptote of `tan x`, no risers on `floor(x)`.148149## Analysis (`GraphAnalysis`)150151| Function | Method |152|---|---|153| `roots`, `intersections` | 2000-sample scan with `RootFinder.allRoots` (Brent on each sign change); poles and jumps through zero are excluded, shared poles of two curves too |154| `extrema` | Scan, golden-section refinement, then Brent on the Ridders derivative; no end points, plateaus or poles |155| `inflections` | Sign change of a finite-difference second derivative (800 samples) |156| `tangent`, `derivative`, `derivativeFunction` | Ridders differentiation with an error estimate; `tangent` throws `.refused` at corners and undefined points |157| `integral`, `areaBetween` | The interval is first scanned for poles and undefined stretches with the plotter at 2048 columns and refused with a message if one is inside. Adaptive Gauss–Kronrod between jumps; tanh-sinh for end-point singularities (with a warning). Regions are split at roots / intersections for shading |158| `arcLength` | Gauss–Kronrod on `√(1 + f′²)` with a finite-difference derivative |159| `trace`, `pointsOfInterest`, `table` | Cursor with snapping to precomputed points; `nil` where undefined |160161Every `PointOfInterest` and estimate carries a `VerificationReport`; the UI shows a badge only when `isVerified`.162163## 3D164165- **`SurfacePlotter.mesh`** builds a grid mesh of `(columns + 1) × (rows + 1)` vertices. The automatic z-range uses Tukey166 fences so that a pole cannot flatten the rest of the surface. A triangle is dropped when a vertex is undefined, when all167 three vertices are clipped on the same side, or when an edge that climbs more than 5 % of the z-range (or is clipped)168 fails the same shrinking-gap test as the 2D sampler. `SurfaceMesh` carries `vertices`, `normals`, `indices`,169 `colorParameters`, `valid`, `clipped`, `zMin`/`zMax`, `droppedTriangles` and `notices`.170- **`SurfaceMesh.normalized()`** maps the mesh into the cube [−1, 1]³ so that the picture does not depend on axis units.171- **`Camera3D`** is a pure-math orbit camera (yaw, pitch, distance) producing column-major view-projection matrices in the172 OpenGL clip-space convention, plus `project(_:width:height:)`.173- **`PainterRenderer.project`** projects every triangle and sorts them far to near by the depth of the triangle centroid174 (painter's algorithm); `depthOrder` returns the order alone.175- **Renderer.** The app draws 3D with a SwiftUI `Canvas` painter's renderer over the engine's mesh176 (`Surface3DView.swift`), so the triangles the engine dropped stay holes in the picture. Surface triangles and contour177 segments are depth-sorted together; fills are not antialiased so that adjacent facets meet without seams. When triangles178 were dropped, `Surface3DModel.swift` surfaces a notice ("… cells are left open where the function is undefined, jumps or179 has a pole").180- `SurfacePlotter.contours` traces level sets by marching squares with the same validated crossings as implicit curves;181 `inspect` returns height, gradient and normal at a point; `parametricMesh` handles `(u, v) ↦ (x, y, z)`.182183## Guarantees184185As asserted by the test suite (`Packages/ORIXGraph/Tests/ORIXGraphTests/Support.swift`), three independent checks are186applied to explicit plots, plus two bounds:187188| Check | Meaning |189|---|---|190| `hiddenBreaks` | Between every pair of consecutive vertices the function is re-evaluated at 64 points; it must be defined everywhere (except at a reported hole) and climb gradually. A segment that hides a jump or a pole fails |191| `spans` | No segment contains an analytically known discontinuity strictly between its two vertices |192| `uncovered` | At 4000 abscissas, wherever the function is visible some polyline or band covers that abscissa |193| `maxScreenError` | Distance in pixels from the true curve to the polyline, 8 points per segment; smooth functions are tested for < 0.5 px |194| `bounded` | All coordinates lie inside the padded viewport |195196Implicit curves, parametric / polar curves and surfaces have their own versions of the rule (no contour across a pole or a197jump; unreliable zero sets flagged `reliable == false` with a reason; no triangle across a pole).198199## Documented limits200201Stated in `VALIDATION.md` §5; the main ones:202203- **Explicit curves.** A spike, dip or even-order pole lying wholly between two grid samples and not hit by the column's204 test point is not seen when both neighbours look flat. Classification is numerical: a logarithmic singularity is205 reported as a pole; a very slowly converging cusp may be labelled a pole or `.none`. Inside an aliased band the envelope206 comes from 31–39 samples per column and can fall slightly short of the true extremes; an undefined point inside a band207 is reported as `.essential` even when a limit exists. Functions defined on a scattered set of points produce many208 fragments.209- **Implicit curves and regions.** Reliability is limited by the grid: finest cell 2 px, coarse scan 8 px. A closed loop210 smaller than about 6 px, or two branches closer than a cell, can be missed or merged without notice. Zero sets without a211 sign change cannot be traced; their detection is a local search, not a proof. Curves stop up to one cell short of the212 boundary of the domain of `F`. A sliver thinner than 8 px that misses every coarse corner and centre is not shaded.213- **Parametric / polar.** A loop or excursion shorter than one initial step whose midpoint falls on the chord is missed.214- **Analysis.** Two roots closer than range/2000 can be merged or missed; even-multiplicity roots are located to about215 1e-6 … 1e-8. A pole too narrow for the 2048-column scan would not be refused before integration. Arc length and the216 derivative curve use finite differences (relative accuracy about 1e-8).217- **3D.** Vertices outside the z-range are clamped, so the cut edge is accurate only to one cell. Jumps or poles smaller218 than 5 % of the z-range across one cell are bridged. Sorting triangle centroids is correct for height fields seen from219 outside, not guaranteed for self-overlapping parametric surfaces.220- **General.** `Task.isCancelled` is polled once per pixel column / lattice row / 4096 triangles; one evaluation of a very221 expensive expression is not interruptible. With `splitUnknownIdentifiers` (default) an unknown multi-letter name is read222 as a product of letters unless it is already a variable of the context.223