ORIXGraph — API
Pure computation: expressions in, render-ready geometry out. No SwiftUI / UIKit / CoreGraphics. Everything public is Sendable;
every heavy function is synchronous, thread-safe and polls Task.isCancelled, so call it from a background task (or use the
@concurrent async wrappers of GraphEngine).
All geometry is in function coordinates. Map to the screen with Viewport.toScreen(_:) (origin top-left, y down).
import ORIXExpression // EvalContext, Value, CalcError
import ORIXGraph1. From a text field to polylines
// 1. The context holds the angle mode, the slider values and the user functions.
var context = EvalContext()
context.angleMode = .radians
// 2. Parse once, when the text changes.
let item = try PlotParser.parse("a*sin(x)/x", context: context) // throws CalcError / GraphError.notPlottable
item.kind // .explicit(Expr)
item.parameters // ["a"] → create one slider per name
item.missingParameters(in: context) // ["a"]: names that still need a value
context.variables["a"] = Value(2.0) // slider value
// 3. Describe the canvas.
let viewport = Viewport(xMin: -10, xMax: 10, yMin: -7.5, yMax: 7.5, width: size.width, height: size.height)
// 4. Geometry (off the main actor). Re-run on every viewport or slider change; compilation is included and cheap.
let g = try await GraphEngine.geometryAsync(for: item, viewport: viewport, context: context)
// 5. Draw.
for line in g.polylines { // stroke each polyline separately — never join two of them
var path = Path()
path.addLines(line.points.map { let s = viewport.toScreen($0); return CGPoint(x: s.x, y: s.y) })
if line.isClosed { path.closeSubpath() }
canvas.stroke(path, with: .color(color), lineWidth: item.style.lineWidth)
}
for band in g.bands { // aliased region: fill, do not stroke a line through it
canvas.fill(path(of: band.polygon), with: .color(color.opacity(0.35)))
}
for hole in g.holes { drawOpenCircle(at: viewport.toScreen(hole)) } // removable discontinuities
for d in g.discontinuities where d.kind == .pole { drawDashedVertical(atX: viewport.screenX(d.x)) } // optional asymptotes
for n in g.notices { show(n.message) } // .aliased, .unreliable, .incomplete, .rejectedFalseContour, .infoA polyline with a single point is an isolated point of the graph (for example sign(0) = 0): draw a dot.
Several items at once: try await GraphEngine.geometries(for: items, viewport:context:) → [UUID: Result<PlotGeometry, CalcError>].
What PlotParser.parse understands
| Text | item.kind |
|---|---|
sin(x), y = x^2, x^2 = y, f(x) = x^2 (→ item.definedFunction) |
.explicit (variable x) |
x = y^2, x = 3 |
.explicitX (variable y) |
(cos(t), sin(2t)), optional for 0 <= t <= 2pi or {0 <= t <= 2pi} |
.parametric (variable t) |
r = 1 - cos(θ); angle written θ, theta or t; a bare expression in θ |
.polar (variable θ) |
x^2 + y^2 = 25, sin(x) = cos(y), xy = 1 |
.implicit(lhs:rhs:) |
y < x^2, x^2 + y^2 <= 4, 1 < x < 2, … and …, … or … |
.inequality(condition:boundaries:) |
(1, 2), (1, 2), (3, 4) |
.points(_, connected: false) |
z = x*y, h(x, y) = …, bare expression in x and y |
.surface (use §4) |
a = 3 |
.parameter(name:value:) (not drawable; set the slider) |
y = x^2 {-1 <= x <= 2} |
explicit with item.domain |
Piecewise functions use the expression engine: piecewise(x < 0, -x, x < 2, x^2), if(x > 0, 1, -1).
PlotParserOptions(splitUnknownIdentifiers:) (default true) reads ax as a·x; names already in
context.variables / context.functions are never split. Data: PlotItem.scatter(points), PlotItem.series(points).
PlotItem carries id, source, style (PlotStyle: colorIndex, lineWidth, dash, marker, fillOpacity — pure data),
isVisible, parameterRange (t / θ; default 0…2π or one full turn in the current angle unit), domain.
PlotGeometry
| Field | Meaning |
|---|---|
polylines: [Polyline] |
connected pieces (points, isClosed) |
bands: [EnvelopeBand] |
columns (x0, x1, yMin, yMax) where the function oscillates faster than the pixels; polygon is the outline to fill |
discontinuities: [Discontinuity] |
kind (.pole, .jump, .removable, .undefinedInterval, .essential), x, xEnd, leftLimit, rightLimit (.finite(v), .infinite(positive:), .undefined, .none), openStart/openEnd |
holes: [Point2] |
open-circle markers of removable discontinuities |
markers: [Point2] |
scatter points |
fill: RegionFill? |
inequality: spans = rectangles (x0, x1, y0, y1) to fill |
strictBoundary |
inequality with < / >: draw the boundary dashed |
transposed |
x = g(y): in bands / discontinuities the independent variable is y |
notices, isComplete, evaluations |
honesty notices; isComplete == false after cancellation or budget exhaustion |
Lower-level samplers (closures instead of items)
let f: RealFunction = { x in sin(x) / x } // return NaN where undefined
let plot = Sampler.sampleExplicit(f, viewport: viewport) // ExplicitPlot: polylines, bands, discontinuities, holes, poles
let side = Sampler.sampleExplicitX(g, viewport: viewport) // x = g(y)
let curve = Sampler.sampleParametric(x: fx, y: fy, range: 0...(2 * .pi), viewport: viewport) // CurvePlot
let rose = Sampler.samplePolar(r, range: 0...(2 * .pi), radiansPerUnit: 1, viewport: viewport)
let implicit = ImplicitPlotter.plot({ x, y in x * x + y * y - 25 }, viewport: viewport) // ImplicitPlot: polylines, reliable, reasons
let region = ImplicitPlotter.region({ x, y in y < x * x ? 1 : 0 }, viewport: viewport) // RegionFillOptions: SamplerOptions (tolerance 0.2 px, maxDepth 6, verticalPadding 1 viewport height, detectAliasing, xRange,
clipMode .split / .clamp, maxEvaluations), CurveOptions (tolerance, initialSamples 512, maxDepth 10, padding),
ImplicitOptions (cellSize 2 px, coarseFactor 4, maxEvaluations); grouped in GraphOptions for GraphEngine.
2. Viewport, ticks, grid
var v = Viewport(xMin: -10, xMax: 10, yMin: -7.5, yMax: 7.5, width: 800, height: 600) // always sanitised (inverted, NaN, zero span)
v = v.panned(byScreen: drag.width, drag.height) // content follows the finger
v = v.zoomed(by: magnification, aboutScreenPoint: Point2(pinch.x, pinch.y)) // > 1 zooms in, anchor stays put
v = v.equalAspect() // circles look round
v = v.resized(width: w, height: h)
v = GraphEngine.autoFit(items, viewport: v, context: context) // robust y-range (poles ignored); also v.autoFitY([f])
v.toScreen(p); v.toFunction(s); v.screenX(x); v.functionY(sy); v.unitsPerPixelX
let grid = GridLines(viewport: v, xMode: .piMultiples) // .decimal (1-2-5) or .piMultiples
for t in grid.x.major { drawLine(atX: v.screenX(t.value)); drawLabel(t.label) } // ≤ 25 ticks, minimal-digit labels ("0.5", "2e12", "3π/4")
for x in grid.x.minor { drawFaintLine(atX: v.screenX(x)) }
let ticks = AxisTicks.make(min: 0, max: 30, pixelLength: 600, targetSpacing: 90)3. Analysis (function coordinates)
f is a RealFunction; get it from an item with try item.compiled(context: context).explicitFunction.
let range = viewport.xMin...viewport.xMax
GraphAnalysis.roots(of: f, in: range) // [PointOfInterest] — poles and jumps through zero are excluded
GraphAnalysis.extrema(of: f, in: range) // .minimum / .maximum; no end points, plateaus, poles
GraphAnalysis.inflections(of: f, in: range)
GraphAnalysis.yIntercept(of: f) // nil when f(0) is undefined
GraphAnalysis.intersections(f, g, in: range) // shared poles excluded
// PointOfInterest: kind, x, y, residual, report (VerificationReport: show a badge only if report.isVerified)
let t = try GraphAnalysis.tangent(of: f, at: x0, scale: viewport.xSpan) // slope, intercept, slopeError, report; throws .refused at corners / undefined points
let (p, q) = t.segment(in: viewport)
let d = GraphAnalysis.derivative(of: f, at: x0, scale: viewport.xSpan) // NumericalEstimate (value, errorEstimate, converged)
let fPrime = GraphAnalysis.derivativeFunction(of: f, scale: viewport.xSpan) // RealFunction → Sampler.sampleExplicit(fPrime, …)
let i = try GraphAnalysis.integral(of: f, from: a, to: b, viewport: viewport) // throws GraphError.refused if a pole / undefined stretch is inside
i.value; i.errorEstimate; i.totalArea
for r in i.regions { fill(r.polygon, color: r.sign > 0 ? positive : negative) } // split at the roots
let area = try GraphAnalysis.areaBetween(f, g, from: a, to: b, viewport: viewport) // value = ∫(f − g), totalArea = ∫|f − g|, regions split at intersections
let length = try GraphAnalysis.arcLength(of: f, from: a, to: b).estimate.value
GraphAnalysis.discontinuities(of: f, in: a...b)
// Trace cursor: compute the snap targets once per (function, viewport), then per drag event:
let targets = GraphAnalysis.pointsOfInterest(of: f, viewport: viewport)
let tp = GraphAnalysis.trace(f, screenX: location.x, viewport: viewport, pointsOfInterest: targets, snapRadius: 12)
tp.x; tp.y /* nil = undefined */; tp.screen; tp.snapped?.kind
let rows = GraphAnalysis.table(of: f, start: -2, step: 0.5, count: 9) // row.y == nil → row.text == "undefined"Errors: GraphError.refused(message) carries a sentence fit for display ("The function has a pole at x ≈ 0.0 inside the interval…").
4. 3D surfaces
guard case .surface(let f) = try item.compiled(context: context) else { return }
let mesh = SurfacePlotter.mesh(f, x: -3...3, y: -3...3, options: SurfaceOptions(columns: 60, rows: 60))
// mesh.vertices [(columns+1)·(rows+1) Point3, row-major], mesh.normals (unit, up), mesh.indices [UInt32] (3 per triangle, CCW from above),
// mesh.colorParameters (0…1 height for a colour ramp), mesh.valid, mesh.clipped, mesh.zMin/zMax (robust), mesh.droppedTriangles, mesh.notices
let unit = mesh.normalized() // vertices in [−1, 1]³, normals transformed
var camera = Camera3D(yaw: -.pi / 3, pitch: .pi / 6, distance: 4.5)
camera = camera.orbited(yawBy: dx * 0.01, pitchBy: dy * 0.01).zoomed(by: pinch)
// Canvas fallback renderer (painter's algorithm): triangles sorted far → near, already projected
for t in PainterRenderer.project(unit, camera: camera, width: w, height: h) {
canvas.fill(trianglePath(t.a, t.b, t.c), with: .color(ramp(t.colorParameter).scaled(by: t.shade)))
}
// Or with your own pipeline:
let m = camera.viewProjectionMatrix(aspect: w / h) // 16 Doubles, column-major, OpenGL clip space
camera.project(Point3(0, 0, 1), width: w, height: h) // Projection(screen:, depth:)? (nil behind the camera)
PainterRenderer.depthOrder(unit, camera: camera) // triangle indices far → near
SurfacePlotter.inspect(f, x: 1, y: 2, scale: 6) // z, gradient (∂f/∂x, ∂f/∂y), normal
let levels = SurfacePlotter.niceLevels(zMin: mesh.zMin, zMax: mesh.zMax)
let contours = SurfacePlotter.contours(f, levels: levels, x: -3...3, y: -3...3) // [ContourLine(level, polylines, reliable)]
SurfacePlotter.parametricMesh({ u, v in Point3(cos(u) * sin(v), sin(u) * sin(v), cos(v)) }, u: 0...(2 * .pi), v: 0...(.pi))5. Data, fit overlay, export
let item = PlotItem.scatter(points) // or .series(points) for a connected line
DataSeries.bounds(points); DataSeries.fit(points, viewport: v) // window that shows all points
if let fit = DataSeries.linearFit(points) { fit.slope; fit.intercept; fit.rSquared; fit.segment(in: v) }
CSVExport.curve(g.polylines) // "x,y" at full double precision, blank line between polylines
CSVExport.curveWithSegments(g.polylines) // "segment,x,y"
CSVExport.table(rows) // undefined entries written as "undefined"
CSVExport.points(points)6. Cancellation and threading
- Synchronous entry points check
Task.isCancelled(once per pixel column / lattice row) and return what they have withisComplete == falseand an.incompletenotice. Throwing analysis functions useTask.checkCancellation(). GraphEngine.geometryAsync/geometriesare@concurrent(never on the main actor) and throwCancellationError.- Typical pattern: keep one
Taskper item; cancel it and start a new one on each viewport / slider change.