using GraphTUI.Core.Math; using GraphTUI.Core.Models; namespace GraphTUI.Rendering; public sealed class PlotRenderer { public sealed record AxisTick(int CellCol, int CellRow, string Text, bool IsXAxis); public static List Render( BrailleCanvas canvas, Viewport viewport, IReadOnlyList functions, Func? paramLookup, bool showGrid = true, bool showCrosshair = false, double crosshairX = 0, double crosshairY = 0, UserFunctionEvaluator? userFuncLookup = null) { canvas.Clear(ColorRgb.Background); var ticks = new List(); int subW = canvas.SubpixelWidth; int subH = canvas.SubpixelHeight; // 1. Grid lines and Ticks calculation double xStep = CalculateNiceStep(viewport.Width, canvas.CellWidth / 8); double yStep = CalculateNiceStep(viewport.Height, canvas.CellHeight / 4); if (showGrid) { RenderGridLines(canvas, viewport, xStep, yStep); } // 2. Axes lines RenderAxes(canvas, viewport); // 3. Compute Tick Labels ComputeTickLabels(canvas, viewport, xStep, yStep, ticks); // 4. Render Functions & Calculus Overlays foreach (var fn in functions) { if (!fn.IsVisible || !fn.IsGraphable || fn.CompilationError != null) continue; RenderFunction(canvas, viewport, fn, paramLookup, crosshairX, userFuncLookup); } // 5. Crosshair if (showCrosshair) { RenderCrosshair(canvas, viewport, crosshairX, crosshairY); } return ticks; } private static void RenderAxes(BrailleCanvas canvas, Viewport viewport) { int subW = canvas.SubpixelWidth; int subH = canvas.SubpixelHeight; // X axis: y = 0 // If y = 0 is on-screen, draw at axisY. // If y = 0 is off-screen, draw a reference border axis line along the edge (bottom if YMin > 0, top if YMax < 0). bool hasXAxisOnScreen = viewport.MathYToSubpixel(0, subH, out int axisY); int drawAxisY = hasXAxisOnScreen ? axisY : (viewport.YMin > 0 ? subH - 1 : 0); for (int x = 0; x < subW; x++) { canvas.SetPixel(x, drawAxisY, ColorRgb.AxisLine, CanvasLayer.Axis); } // Y axis: x = 0 // If x = 0 is on-screen, draw at axisX. // If x = 0 is off-screen, draw a reference border axis line along the edge (left if XMin > 0, right if XMax < 0). bool hasYAxisOnScreen = viewport.MathXToSubpixel(0, subW, out int axisX); int drawAxisX = hasYAxisOnScreen ? axisX : (viewport.XMin > 0 ? 0 : subW - 1); for (int y = 0; y < subH; y++) { canvas.SetPixel(drawAxisX, y, ColorRgb.AxisLine, CanvasLayer.Axis); } } private static void RenderGridLines(BrailleCanvas canvas, Viewport viewport, double xStep, double yStep) { int subW = canvas.SubpixelWidth; int subH = canvas.SubpixelHeight; bool hasXAxisOnScreen = viewport.MathYToSubpixel(0, subH, out _); bool hasYAxisOnScreen = viewport.MathXToSubpixel(0, subW, out _); // Vertical grid lines double firstX = System.Math.Floor(viewport.XMin / xStep) * xStep; for (double x = firstX; x <= viewport.XMax + xStep * 0.5; x += xStep) { if (System.Math.Abs(x) < 1e-9 && hasYAxisOnScreen) continue; // Y axis handles x=0 if on screen if (viewport.MathXToSubpixel(x, subW, out int subX)) { for (int y = 0; y < subH; y += 4) { canvas.SetPixel(subX, y, ColorRgb.GridLine, CanvasLayer.Grid); } } } // Horizontal grid lines double firstY = System.Math.Floor(viewport.YMin / yStep) * yStep; for (double y = firstY; y <= viewport.YMax + yStep * 0.5; y += yStep) { if (System.Math.Abs(y) < 1e-9 && hasXAxisOnScreen) continue; // X axis handles y=0 if on screen if (viewport.MathYToSubpixel(y, subH, out int subY)) { for (int x = 0; x < subW; x += 4) { canvas.SetPixel(x, subY, ColorRgb.GridLine, CanvasLayer.Grid); } } } } private static void ComputeTickLabels( BrailleCanvas canvas, Viewport viewport, double xStep, double yStep, List ticks) { int cellW = canvas.CellWidth; int cellH = canvas.CellHeight; // Find cell row for X axis bool hasXAxis = viewport.MathYToScreen(0, cellH, out int axisCellY); int labelCellY; if (hasXAxis) { labelCellY = System.Math.Clamp(axisCellY + 1, 0, cellH - 1); } else { labelCellY = viewport.YMin > 0 ? cellH - 1 : 0; } bool hasYAxis = viewport.MathXToScreen(0, cellW, out int axisCellX); double firstX = System.Math.Floor(viewport.XMin / xStep) * xStep; for (double x = firstX; x <= viewport.XMax + xStep * 0.5; x += xStep) { if (System.Math.Abs(x) < 1e-9 && hasXAxis && hasYAxis) continue; if (viewport.MathXToScreen(x, cellW, out int cellX)) { string text = FormatNumber(x); int startCol = cellX - text.Length / 2; if (startCol >= 0 && startCol + text.Length < cellW) { ticks.Add(new AxisTick(startCol, labelCellY, text, true)); } } } // Find cell col for Y axis int labelCellX; if (hasYAxis) { labelCellX = System.Math.Clamp(axisCellX + 1, 0, cellW - 6); } else { labelCellX = viewport.XMin > 0 ? 1 : cellW - 7; } double firstY = System.Math.Floor(viewport.YMin / yStep) * yStep; for (double y = firstY; y <= viewport.YMax + yStep * 0.5; y += yStep) { if (System.Math.Abs(y) < 1e-9 && hasYAxis && hasXAxis) continue; if (viewport.MathYToScreen(y, cellH, out int cellY)) { string text = FormatNumber(y); if (cellY >= 0 && cellY < cellH && labelCellX + text.Length < cellW) { ticks.Add(new AxisTick(labelCellX, cellY, text, false)); } } } } private static void RenderFunction( BrailleCanvas canvas, Viewport viewport, GraphFunction fn, Func? paramLookup, double crosshairX, UserFunctionEvaluator? userFuncLookup) { switch (fn.Type) { case FunctionType.Cartesian: RenderCartesian(canvas, viewport, fn, paramLookup, crosshairX, userFuncLookup); break; case FunctionType.CartesianX: RenderCartesianX(canvas, viewport, fn, paramLookup, userFuncLookup); break; case FunctionType.Implicit: RenderImplicit(canvas, viewport, fn, paramLookup, userFuncLookup); break; case FunctionType.Parametric: RenderParametric(canvas, viewport, fn, paramLookup, userFuncLookup); break; case FunctionType.Polar: RenderPolar(canvas, viewport, fn, paramLookup, userFuncLookup); break; } } private static void RenderCartesian( BrailleCanvas canvas, Viewport viewport, GraphFunction fn, Func? paramLookup, double crosshairX, UserFunctionEvaluator? userFuncLookup) { if (fn.Evaluator == null) return; int subW = canvas.SubpixelWidth; int subH = canvas.SubpixelHeight; // Integral Shading if (fn.ShowIntegral) { double a = fn.IntegralA; double b = fn.IntegralB; double xStart = System.Math.Min(a, b); double xEnd = System.Math.Max(a, b); ColorRgb shadeColor = ColorRgb.Lerp(fn.Color, ColorRgb.DarkGray, 0.4); viewport.MathToSubpixel(0, 0, subW, subH, out _, out int axisY); for (int sx = 0; sx < subW; sx++) { viewport.SubpixelToMath(sx, 0, subW, subH, out double x, out _); if (x >= xStart && x <= xEnd) { double y = fn.Evaluator.Evaluate(x, paramLookup, userFuncLookup); if (!double.IsNaN(y) && !double.IsInfinity(y)) { if (viewport.MathToSubpixel(x, y, subW, subH, out _, out int curveY)) { canvas.DrawVerticalFill(sx, curveY, axisY, shadeColor); } } } } } // Plot main curve int? lastSx = null; int? lastSy = null; double lastY = double.NaN; for (int sx = 0; sx < subW; sx++) { viewport.SubpixelToMath(sx, 0, subW, subH, out double x, out _); double y = fn.Evaluator.Evaluate(x, paramLookup, userFuncLookup); if (double.IsNaN(y) || double.IsInfinity(y)) { lastSx = null; lastSy = null; lastY = double.NaN; continue; } viewport.MathToSubpixel(x, y, subW, subH, out _, out int sy); if (lastSx.HasValue && lastSy.HasValue) { // Discontinuity / Asymptote check (e.g. tan(x), 1/x) bool isAsymptote = !double.IsNaN(lastY) && (y * lastY < 0) && (System.Math.Abs(sy - lastSy.Value) > subH / 2); if (!isAsymptote) { canvas.DrawLine(lastSx.Value, lastSy.Value, sx, sy, fn.Color); } else { canvas.SetPixel(sx, sy, fn.Color); } } else { canvas.SetPixel(sx, sy, fn.Color); } lastSx = sx; lastSy = sy; lastY = y; } // Derivative Curve overlay if (fn.ShowDerivative) { int? prevDerivSx = null; int? prevDerivSy = null; ColorRgb derivColor = ColorRgb.Lerp(fn.Color, ColorRgb.Yellow, 0.5); for (int sx = 0; sx < subW; sx += 2) { viewport.SubpixelToMath(sx, 0, subW, subH, out double x, out _); double dy = Calculus.Derivative(t => fn.Evaluator.Evaluate(t, paramLookup, userFuncLookup), x); if (double.IsNaN(dy) || double.IsInfinity(dy)) { prevDerivSx = null; prevDerivSy = null; continue; } viewport.MathToSubpixel(x, dy, subW, subH, out _, out int sy); if (prevDerivSx.HasValue && prevDerivSy.HasValue) { if (System.Math.Abs(sy - prevDerivSy.Value) < subH / 2) { canvas.DrawLine(prevDerivSx.Value, prevDerivSy.Value, sx, sy, derivColor, CanvasLayer.Annotation); } } prevDerivSx = sx; prevDerivSy = sy; } } // Tangent Line overlay if (fn.ShowTangent) { var (slope, y0, lineFunc) = Calculus.TangentLine(t => fn.Evaluator.Evaluate(t, paramLookup, userFuncLookup), crosshairX); if (!double.IsNaN(slope) && !double.IsInfinity(slope)) { viewport.SubpixelToMath(0, 0, subW, subH, out double xLeft, out _); viewport.SubpixelToMath(subW - 1, 0, subW, subH, out double xRight, out _); double yLeft = lineFunc(xLeft); double yRight = lineFunc(xRight); viewport.MathToSubpixel(xLeft, yLeft, subW, subH, out int sx0, out int sy0); viewport.MathToSubpixel(xRight, yRight, subW, subH, out int sx1, out int sy1); canvas.DrawLine(sx0, sy0, sx1, sy1, ColorRgb.Yellow, CanvasLayer.Annotation); } } } private static void RenderCartesianX( BrailleCanvas canvas, Viewport viewport, GraphFunction fn, Func? paramLookup, UserFunctionEvaluator? userFuncLookup) { if (fn.Evaluator == null) return; int subW = canvas.SubpixelWidth; int subH = canvas.SubpixelHeight; int? lastSx = null; int? lastSy = null; double lastX = double.NaN; for (int sy = 0; sy < subH; sy++) { viewport.SubpixelToMath(0, sy, subW, subH, out _, out double y); double x = fn.Evaluator.EvaluateY(y, paramLookup, userFuncLookup); if (double.IsNaN(x) || double.IsInfinity(x)) { lastSx = null; lastSy = null; lastX = double.NaN; continue; } viewport.MathToSubpixel(x, y, subW, subH, out int sx, out _); if (lastSx.HasValue && lastSy.HasValue) { bool isAsymptote = !double.IsNaN(lastX) && (x * lastX < 0) && (System.Math.Abs(sx - lastSx.Value) > subW / 2); if (!isAsymptote) { canvas.DrawLine(lastSx.Value, lastSy.Value, sx, sy, fn.Color); } else { canvas.SetPixel(sx, sy, fn.Color); } } else { canvas.SetPixel(sx, sy, fn.Color); } lastSx = sx; lastSy = sy; lastX = x; } } private static void RenderImplicit( BrailleCanvas canvas, Viewport viewport, GraphFunction fn, Func? paramLookup, UserFunctionEvaluator? userFuncLookup) { if (fn.EvaluatorLhs == null || fn.EvaluatorRhs == null) return; int subW = canvas.SubpixelWidth; int subH = canvas.SubpixelHeight; bool lhsOnlyY = fn.EvaluatorLhs.ContainsVariable("y") && !fn.EvaluatorLhs.ContainsVariable("x"); bool rhsOnlyX = fn.EvaluatorRhs.ContainsVariable("x") && !fn.EvaluatorRhs.ContainsVariable("y"); bool lhsOnlyX = fn.EvaluatorLhs.ContainsVariable("x") && !fn.EvaluatorLhs.ContainsVariable("y"); bool rhsOnlyY = fn.EvaluatorRhs.ContainsVariable("y") && !fn.EvaluatorRhs.ContainsVariable("x"); // Fast path for f(y) = g(x) or g(x) = f(y): 1D precomputations double[]? precomputedLhsY = null; double[]? precomputedRhsX = null; double[]? precomputedLhsX = null; double[]? precomputedRhsY = null; if (lhsOnlyY && rhsOnlyX) { precomputedLhsY = new double[subH + 1]; for (int sy = 0; sy <= subH; sy++) { viewport.SubpixelToMath(0, sy, subW, subH, out _, out double y); precomputedLhsY[sy] = fn.EvaluatorLhs.EvaluateY(y, paramLookup, userFuncLookup); } precomputedRhsX = new double[subW + 1]; for (int sx = 0; sx <= subW; sx++) { viewport.SubpixelToMath(sx, 0, subW, subH, out double x, out _); precomputedRhsX[sx] = fn.EvaluatorRhs.Evaluate(x, paramLookup, userFuncLookup); } } else if (lhsOnlyX && rhsOnlyY) { precomputedLhsX = new double[subW + 1]; for (int sx = 0; sx <= subW; sx++) { viewport.SubpixelToMath(sx, 0, subW, subH, out double x, out _); precomputedLhsX[sx] = fn.EvaluatorLhs.Evaluate(x, paramLookup, userFuncLookup); } precomputedRhsY = new double[subH + 1]; for (int sy = 0; sy <= subH; sy++) { viewport.SubpixelToMath(0, sy, subW, subH, out _, out double y); precomputedRhsY[sy] = fn.EvaluatorRhs.EvaluateY(y, paramLookup, userFuncLookup); } } double EvalV(int sx, int sy) { if (precomputedLhsY != null && precomputedRhsX != null) { double l = precomputedLhsY[sy]; double r = precomputedRhsX[sx]; return l - r; } if (precomputedLhsX != null && precomputedRhsY != null) { double l = precomputedLhsX[sx]; double r = precomputedRhsY[sy]; return l - r; } viewport.SubpixelToMath(sx, sy, subW, subH, out double xVal, out double yVal); double lhs = fn.EvaluatorLhs.Evaluate(xVal, yVal, paramLookup, userFuncLookup); double rhs = fn.EvaluatorRhs.Evaluate(xVal, yVal, paramLookup, userFuncLookup); return lhs - rhs; } double[] prevRow = new double[subW + 1]; double[] currRow = new double[subW + 1]; for (int sx = 0; sx <= subW; sx++) { prevRow[sx] = EvalV(sx, 0); } for (int sy = 0; sy < subH; sy++) { for (int sx = 0; sx <= subW; sx++) { currRow[sx] = EvalV(sx, sy + 1); } for (int sx = 0; sx < subW; sx++) { double cTL = prevRow[sx]; double cTR = prevRow[sx + 1]; double cBL = currRow[sx]; double cBR = currRow[sx + 1]; if (double.IsNaN(cTL) || double.IsNaN(cTR) || double.IsNaN(cBL) || double.IsNaN(cBR) || double.IsInfinity(cTL) || double.IsInfinity(cTR) || double.IsInfinity(cBL) || double.IsInfinity(cBR)) { continue; } var crossings = new List<(int X, int Y)>(4); // Top edge if (cTL * cTR <= 0 && System.Math.Abs(cTL - cTR) < 1e5) { double t = System.Math.Abs(cTL) / (System.Math.Abs(cTL) + System.Math.Abs(cTR) + 1e-12); int px = (int)System.Math.Round(sx + t); crossings.Add((px, sy)); } // Bottom edge if (cBL * cBR <= 0 && System.Math.Abs(cBL - cBR) < 1e5) { double t = System.Math.Abs(cBL) / (System.Math.Abs(cBL) + System.Math.Abs(cBR) + 1e-12); int px = (int)System.Math.Round(sx + t); crossings.Add((px, sy + 1)); } // Left edge if (cTL * cBL <= 0 && System.Math.Abs(cTL - cBL) < 1e5) { double t = System.Math.Abs(cTL) / (System.Math.Abs(cTL) + System.Math.Abs(cBL) + 1e-12); int py = (int)System.Math.Round(sy + t); crossings.Add((sx, py)); } // Right edge if (cTR * cBR <= 0 && System.Math.Abs(cTR - cBR) < 1e5) { double t = System.Math.Abs(cTR) / (System.Math.Abs(cTR) + System.Math.Abs(cBR) + 1e-12); int py = (int)System.Math.Round(sy + t); crossings.Add((sx + 1, py)); } if (crossings.Count == 1) { canvas.SetPixel(crossings[0].X, crossings[0].Y, fn.Color); } else if (crossings.Count == 2) { canvas.DrawLine(crossings[0].X, crossings[0].Y, crossings[1].X, crossings[1].Y, fn.Color); } else if (crossings.Count > 2) { canvas.DrawLine(crossings[0].X, crossings[0].Y, crossings[1].X, crossings[1].Y, fn.Color); if (crossings.Count >= 4) { canvas.DrawLine(crossings[2].X, crossings[2].Y, crossings[3].X, crossings[3].Y, fn.Color); } } } (prevRow, currRow) = (currRow, prevRow); } } private static void RenderParametric( BrailleCanvas canvas, Viewport viewport, GraphFunction fn, Func? paramLookup, UserFunctionEvaluator? userFuncLookup) { if (fn.Evaluator == null || fn.EvaluatorY == null) return; int subW = canvas.SubpixelWidth; int subH = canvas.SubpixelHeight; int steps = 1000; double dt = (fn.TMax - fn.TMin) / steps; int? lastSx = null; int? lastSy = null; for (int i = 0; i <= steps; i++) { double t = fn.TMin + i * dt; double x = fn.Evaluator.EvaluateParametricX(t, paramLookup, userFuncLookup); double y = fn.EvaluatorY.EvaluateParametricY(t, paramLookup, userFuncLookup); if (double.IsNaN(x) || double.IsNaN(y) || double.IsInfinity(x) || double.IsInfinity(y)) { lastSx = null; lastSy = null; continue; } viewport.MathToSubpixel(x, y, subW, subH, out int sx, out int sy); if (lastSx.HasValue && lastSy.HasValue) { if (System.Math.Abs(sx - lastSx.Value) < subW / 3 && System.Math.Abs(sy - lastSy.Value) < subH / 3) { canvas.DrawLine(lastSx.Value, lastSy.Value, sx, sy, fn.Color); } } else { canvas.SetPixel(sx, sy, fn.Color); } lastSx = sx; lastSy = sy; } } private static void RenderPolar( BrailleCanvas canvas, Viewport viewport, GraphFunction fn, Func? paramLookup, UserFunctionEvaluator? userFuncLookup) { if (fn.Evaluator == null) return; int subW = canvas.SubpixelWidth; int subH = canvas.SubpixelHeight; int steps = 1000; double dTheta = (fn.ThetaMax - fn.ThetaMin) / steps; int? lastSx = null; int? lastSy = null; for (int i = 0; i <= steps; i++) { double theta = fn.ThetaMin + i * dTheta; double r = fn.Evaluator.EvaluatePolar(theta, paramLookup, userFuncLookup); if (double.IsNaN(r) || double.IsInfinity(r)) { lastSx = null; lastSy = null; continue; } double x = r * System.Math.Cos(theta); double y = r * System.Math.Sin(theta); viewport.MathToSubpixel(x, y, subW, subH, out int sx, out int sy); if (lastSx.HasValue && lastSy.HasValue) { if (System.Math.Abs(sx - lastSx.Value) < subW / 3 && System.Math.Abs(sy - lastSy.Value) < subH / 3) { canvas.DrawLine(lastSx.Value, lastSy.Value, sx, sy, fn.Color); } } else { canvas.SetPixel(sx, sy, fn.Color); } lastSx = sx; lastSy = sy; } } private static void RenderCrosshair(BrailleCanvas canvas, Viewport viewport, double cx, double cy) { int subW = canvas.SubpixelWidth; int subH = canvas.SubpixelHeight; if (viewport.MathToSubpixel(cx, cy, subW, subH, out int chX, out int chY)) { // Dashed horizontal line for (int x = 0; x < subW; x += 3) { canvas.SetPixel(x, chY, ColorRgb.Magenta, CanvasLayer.CrosshairGuide); } // Dashed vertical line for (int y = 0; y < subH; y += 3) { canvas.SetPixel(chX, y, ColorRgb.Magenta, CanvasLayer.CrosshairGuide); } // Central crosshair point canvas.SetPixel(chX, chY, ColorRgb.White, CanvasLayer.Crosshair); } } private static double CalculateNiceStep(double range, int maxTicks) { if (double.IsNaN(range) || double.IsInfinity(range) || range <= 1e-12) range = 10.0; if (maxTicks <= 0) maxTicks = 5; double rawStep = range / maxTicks; if (rawStep <= 1e-12) return 1.0; double power = System.Math.Floor(System.Math.Log10(rawStep)); double fraction = rawStep / System.Math.Pow(10, power); double niceFraction = fraction switch { < 1.5 => 1.0, < 3.0 => 2.0, < 7.0 => 5.0, _ => 10.0 }; return niceFraction * System.Math.Pow(10, power); } private static string FormatNumber(double val) { if (System.Math.Abs(val) < 1e-9) return "0"; if (System.Math.Abs(val) >= 1e5 || System.Math.Abs(val) <= 1e-4) return val.ToString("0.##e+0"); return val.ToString("0.##"); } }