//+-------------------------------------------------------------------+
//|                                                         Path.mqh  |
//|                              Copyright 2026, Sandro Begashvili    |
//|                   https://www.mql5.com/en/users/sandrobegashvil   |
//|                          Telegram: https://t.me/MrMQL5Developer   |
//|                    Cairo5 - 2D vector engine - PART 2 code        |
//|                                                                   |
//|  THE GEOMETRY LAYER.                                              |
//|                                                                   |
//|  A path is a recipe for an outline, written with the same verbs   |
//|  every vector system since PostScript has used:                   |
//|                                                                   |
//|      MoveTo   - lift the pen and put it down somewhere new        |
//|      LineTo   - drag the pen in a straight line                   |
//|      Close    - mark this contour as closed                       |
//|                                                                   |
//|  A path holds NO color, NO thickness and NO pixels. It is pure    |
//|  geometry - a description of an outline, nothing more. Turning it |
//|  into pixels is the rasteriser's job, and that is Part 3.         |
//|                                                                   |
//|  THE COORDINATE CONTRACT                                          |
//|                                                                   |
//|  Coordinates are assumed to be finite. Nothing here validates     |
//|  them on every call - a per-vertex check would tax the one loop   |
//|  the rasteriser runs most often, to catch a mistake that belongs  |
//|  to the caller. When the numbers arrive from an indicator, a      |
//|  division or a user input, call IsFinite() once on the finished   |
//|  path. A NaN that reaches the rasteriser is very hard to trace    |
//|  back to the arithmetic that produced it.                         |
//|                                                                   |
//|  WHAT THIS FILE DELIBERATELY DOES NOT CONTAIN                     |
//|                                                                   |
//|    * curves     - CurveTo and ArcTo arrive in Parts 6 and 7. When |
//|                   they do, they will FLATTEN their curve into     |
//|                   short straight segments and append them to the  |
//|                   very same arrays this file already manages. The |
//|                   storage below does not change.                  |
//|    * edges      - converting contours into scanline edges is the  |
//|                   first thing Part 3 does.                        |
//|    * drawing    - there is not one pixel written anywhere here.   |
//|  AddThickLine(). A line with width is not a line - it is a        |
//|  QUADRILATERAL, so it is something this file can already          |
//|  describe. The helper turns one segment plus a thickness into     |
//|  four corners. The engine gains strokes without gaining a         |
//|  stroker, and the rasterizer learns nothing new.                  |
//+-------------------------------------------------------------------+
#ifndef CAIRO5_PATH_MQH
#define CAIRO5_PATH_MQH

//--- FlattenCubic reads CairoFlattenTolerance
#include "Config.mqh"

//+-------------------------------------------------------------------+
//| SCairoPoint - one vertex.                                         |
//|                                                                   |
//| WHY DOUBLE AND NOT INT                                            |
//|                                                                   |
//| This is the single most consequential decision in the file.       |
//|                                                                   |
//| A rectangle whose left edge sits at x = 10.35 must cover 65% of   |
//| pixel column 10. If the coordinate is an int, that 0.35 is gone   |
//| before rendering even begins, and no rasteriser downstream can    |
//| recover it - the shape can only ever start exactly on a pixel     |
//| boundary.                                                         |
//|                                                                   |
//| Those fractional positions are what the anti-aliasing in Part 4   |
//| works with, and they are what allows an animation to move a       |
//| widget by a third of a pixel without it juddering. Integer        |
//| coordinates are precisely where CCanvas loses the ability to      |
//| produce a smooth edge.                                            |
//+-------------------------------------------------------------------+
struct SCairoPoint
  {
   double            x;
   double            y;
  };


//+-------------------------------------------------------------------+
//| SCairoEdge - one segment, pre-processed for scanline queries.     |
//|                                                                   |
//| The rasterizer asks exactly one question, millions of times:      |
//| "where does this segment cross the horizontal line at y?" So the  |
//| segment is stored in the form that answers it in one multiply and |
//| one add, rather than in the form it was written in.               |
//|                                                                   |
//| Every edge is stored TOP-DOWN, whichever way the original segment |
//| ran, so ytop is always the smaller y. The direction the segment   |
//| really ran is not lost - it is kept in dir, and that single       |
//| number is what the winding rule is made of.                       |
//+-------------------------------------------------------------------+
struct SCairoEdge
  {
   double            ytop;       // smaller y
   double            ybot;       // larger y
   double            xtop;       // x at ytop
   double            dxdy;       // slope: how far x moves per unit of y
   int               dir;        // +1 the original segment ran downward, -1 upward

   //--- x where this edge crosses the horizontal line at y.
   //--- One multiply and one add - which is the whole reason the
   //--- struct is laid out like this.
   double            XAt(const double y) const { return xtop + (y - ytop) * dxdy; }
  };

//+-------------------------------------------------------------------+
//| CCairoEdgeList - a growable array of edges, reused between fills. |
//|                                                                   |
//| The members are public and the class is deliberately dumb: it is  |
//| a buffer the rasterizer walks, not an abstraction. Clear() only   |
//| resets the count, so the memory survives to the next fill - the   |
//| same size / capacity split the path itself uses.                  |
//+-------------------------------------------------------------------+
class CCairoEdgeList
  {
public:
   SCairoEdge        m_edges[];
   int               m_count;

                     CCairoEdgeList();

   void              Clear();
   void              Reserve(const int capacity);
   void              Add(const double x0, const double y0,
                         const double x1, const double y1);
  };

//+-------------------------------------------------------------------+
//| Constructor                                                       |
//+-------------------------------------------------------------------+
CCairoEdgeList::CCairoEdgeList()
  {
   m_count = 0;
   ArrayResize(m_edges, 0);
  }

//+-------------------------------------------------------------------+
//| Reset the count. The allocation is kept on purpose.               |
//+-------------------------------------------------------------------+
void CCairoEdgeList::Clear()
  {
   m_count = 0;
  }

//+-------------------------------------------------------------------+
//| Ask for room for capacity edges before the first one arrives.     |
//|                                                                   |
//| The caller knows the answer in advance, so it can pay for one     |
//| allocation instead of a handful of growth steps. A refused resize |
//| is not fatal here: Add() checks the size on every append anyway,  |
//| so the list simply grows the slow way instead.                    |
//+-------------------------------------------------------------------+
void CCairoEdgeList::Reserve(const int capacity)
  {
   if(capacity > ArraySize(m_edges))
      ArrayResize(m_edges, capacity);
  }

//+-------------------------------------------------------------------+
//| Turn one segment into one edge.                                   |
//+-------------------------------------------------------------------+
void CCairoEdgeList::Add(const double x0, const double y0,
                         const double x1, const double y1)
  {
//--- a horizontal segment is crossed by no scanline, so it can
//--- never contribute a crossing. Dropping it here keeps the
//--- rasterizer's inner loop free of a special case.
   if(y0 == y1)
      return;

   const int i = m_count;

//--- grow in blocks of 64, not one slot at a time. A refused
//--- resize drops the edge instead of writing past the end.
   if(ArraySize(m_edges) < m_count + 1)
      if(ArrayResize(m_edges, m_count + 1, 64) < m_count + 1)
         return;

   m_count++;

   if(y0 < y1)
     {
      //--- the segment runs downward in screen space
      m_edges[i].dir  =  1;
      m_edges[i].ytop = y0;
      m_edges[i].ybot = y1;
      m_edges[i].xtop = x0;
      m_edges[i].dxdy = (x1 - x0) / (y1 - y0);
     }
   else
     {
      //--- the segment runs upward: store it flipped, and REMEMBER
      //--- the flip in dir - that memory is the winding number
      m_edges[i].dir  = -1;
      m_edges[i].ytop = y1;
      m_edges[i].ybot = y0;
      m_edges[i].xtop = x1;
      m_edges[i].dxdy = (x0 - x1) / (y0 - y1);
     }
  }

//+-------------------------------------------------------------------+
//| CCairoPath                                                        |
//|                                                                   |
//| STORAGE MODEL                                                     |
//|                                                                   |
//| One flat array holds the vertices of EVERY contour, back to back. |
//| A second, much smaller array records the index at which each      |
//| contour begins:                                                   |
//|                                                                   |
//|   m_points   [A0 A1 A2 A3][B0 B1 B2][C0 C1 C2 C3 C4]              |
//|   m_starts    0            4         7                            |
//|                                                                   |
//| So contour c runs from m_starts[c] up to m_starts[c+1], and the   |
//| last one runs to m_point_count. No nested arrays, no per-contour  |
//| objects, no allocation per contour - one growable array and an    |
//| index. Walking every vertex of a path is a single linear pass,    |
//| which is exactly what the rasteriser will want.                   |
//|                                                                   |
//| WHY MULTIPLE CONTOURS MATTER                                      |
//|                                                                   |
//| It is tempting to think one path = one shape. It is not, and the  |
//| difference is important:                                          |
//|                                                                   |
//|   * the letter "O" is two contours - the outside and the hole     |
//|   * a ring or a donut is two circles                              |
//|   * a border is an outline plus an inset copy of itself           |
//|   * an icon may be a dozen separate pieces                        |
//|                                                                   |
//| Each of those is ONE fill operation, not several. Getting the     |
//| storage right here is what makes holes possible in Part 5.        |
//|                                                                   |
//| OPEN AND CLOSED ARE DIFFERENT THINGS                              |
//|                                                                   |
//| A third array, one bool per contour, records whether the author   |
//| called Close(). That flag is NOT how a fill is closed - the       |
//| rasteriser in Part 3 joins the last vertex back to the first no   |
//| matter what, because an unclosed boundary has no inside. The flag |
//| records INTENT, which is a separate question and the one that     |
//| survives into everything after filling: a stroke needs it to      |
//| decide between a join and two end caps, an SVG importer carries   |
//| it, hit testing asks it. Reconstructing intent later by guessing  |
//| whether the first and last vertex happen to coincide is exactly   |
//| the kind of heuristic a geometry layer should never need.         |
//+-------------------------------------------------------------------+
class CCairoPath
  {
private:
   //--- THE SIZE / CAPACITY INVARIANT.
   //---
   //--- m_point_count is the number of VALID vertices. ArraySize( m_points )
   //--- is the CAPACITY, and it is always >= m_point_count - the tail beyond
   //--- the count is unwritten memory that a reserve left behind. The two
   //--- numbers differ on purpose, and the whole class depends on the
   //--- difference. Never walk a path with ArraySize(); always use
   //--- PointCount(), ContourCount() and the contour helpers.

   SCairoPoint       m_points[];       // vertices of every contour, back to back
   int               m_point_count;    // valid vertices, NOT ArraySize( m_points )
   int               m_starts[];       // index into m_points where each contour begins
   bool              m_closed[];       // did the author call Close() on contour c?
   int               m_contour_count;  // valid contours, NOT ArraySize( m_starts )
   double            m_cur_x;          // the "pen" position
   double            m_cur_y;
   bool              m_has_current;    // is there a pen position at all?
   bool              m_alloc_failed;   // sticky: some allocation was refused

   bool              AddPoint(const double x, const double y);

   //--- Part 6: the curve flattener, and the measurement it stops on
   double            DistanceToChord(const double px, const double py,
                                     const double ax, const double ay,
                                     const double bx, const double by);
   void              FlattenCubic(const double x0, const double y0,
                                  const double x1, const double y1,
                                  const double x2, const double y2,
                                  const double x3, const double y3,
                                  const int depth);
   //--- Part 7: how far apart two vertices of an arc may sit
   double            StepForRadius(const double r) const;

public:
                     CCairoPath();

   //--- LIFECYCLE
   //--- Clear() empties the path but keeps the memory it has already
   //--- been given; Release() hands that memory back. A path rebuilt
   //--- every frame wants the first, a path that is finished with wants
   //--- the second.

   void              Clear();
   void              Release();
   bool              IsEmpty() const;


   //--- HEALTH
   //--- IsValid()  - did every allocation this path asked for succeed?
   //--- IsFinite() - is every stored coordinate a real number?
   //--- Neither is checked automatically. Both are one call at the end
   //--- of building a path, which is where a caller can still do
   //--- something about the answer.

   bool              IsValid()  const { return !m_alloc_failed; }
   bool              IsFinite() const;

   //--- capacity: ask for the room up front when the count is known
   bool              ReservePoints(const int capacity);
   bool              ReserveContours(const int capacity);

   //--- the primitive verbs
   void              MoveTo(const double x, const double y);
   void              LineTo(const double x, const double y);
   void              Close();

   //--- Part 6: the curve verbs. Both start at the pen, both flatten
   //--- immediately into the vertex arrays above.
   void              CurveTo(const double x1, const double y1,
                             const double x2, const double y2,
                             const double x3, const double y3);
   void              QuadTo(const double cx, const double cy,
                            const double x,  const double y);
   //--- Part 7: a circular arc, in DEGREES, screen convention
   //--- (0 right, 90 down). It appends to the current contour, so it
   //--- composes with LineTo - which is how AddRoundRect is built.
   void              ArcTo(const double cx, const double cy, const double r,
                           const double deg_from, const double deg_to);
   //--- where is the pen right now, and is there one at all?
   double            CurrentX() const { return m_cur_x; }
   double            CurrentY() const { return m_cur_y; }
   bool              HasCurrentPoint() const { return m_has_current; }

   //--- shape helpers: pure path construction, no rasterising
   void              AddRect(const double x, const double y, const double w, const double h);
   void              AddTriangle(const double x0, const double y0,
                                 const double x1, const double y1,
                                 const double x2, const double y2);
   void              AddPolygon(const double &xs[], const double &ys[], const int n);
   void              AddPolyline(const double &xs[], const double &ys[], const int n);
   //--- Part 7: the round shapes. The four-radius overload is the real
   //--- one; the others are conveniences that call into it.
   void              AddRoundRect(const double x, const double y,
                                  const double w, const double h,
                                  const double r_tl, const double r_tr,
                                  const double r_br, const double r_bl);
   void              AddRoundRect(const double x, const double y,
                                  const double w, const double h, const double r);
   void              AddEllipse(const double cx, const double cy,
                                const double rx, const double ry);
   void              AddCircle(const double cx, const double cy, const double r);
   //--- Part 5: one segment of a stroke, as a filled quadrilateral
   void              AddThickLine(const double x0, const double y0,
                                  const double x1, const double y1,
                                  const double thickness);
   //--- INSPECTION
   //--- Reading a path back is not needed to DRAW it - the rasteriser
   //--- will walk the arrays directly. These accessors exist so that a
   //--- demo, a test or a debug overlay can show what geometry was
   //--- actually produced, which is the whole of this article's demo
   //--- and, later, the clearest way to understand curve flattening.
   //--- There are two ways to read a vertex, and the difference is
   //--- deliberate. GetPoint() and GetContourInfo() range-check and
   //--- return false on a bad index: use those when the index came from
   //--- anywhere but a loop you can see. PointX() and PointY() do NOT
   //--- check - they are the fast pair the rasteriser calls once per
   //--- vertex per scanline, and passing them an index outside
   //--- 0..PointCount()-1 is an out-of-range access, not a caught error.

   int               PointCount() const   { return m_point_count;   }
   int               ContourCount() const { return m_contour_count; }

   bool              GetPoint(const int i, SCairoPoint &pt) const;
   bool              GetContourInfo(const int c, int &start, int &length, bool &closed) const;
   bool              IsContourClosed(const int c) const;

   double            PointX(const int i) const { return m_points[i].x; }     // unchecked
   double            PointY(const int i) const { return m_points[i].y; }     // unchecked

   int               ContourStart(const int c) const;
   int               ContourLength(const int c) const;

   //--- THE BRIDGE TO THE RASTERIZER
   //--- The one method that reads the whole path and writes something
   //--- else. It produces edges into a list the caller owns and reuses,
   //--- which is why it takes the list by reference instead of
   //--- returning one.

   void              BuildEdges(CCairoEdgeList &out);
  };

//+-------------------------------------------------------------------+
//| Constructor                                                       |
//+-------------------------------------------------------------------+
CCairoPath::CCairoPath()
  {
   Clear();
  }

//+-------------------------------------------------------------------+
//| Reset to an empty path - but KEEP the memory.                     |
//|                                                                   |
//| Setting the counts to zero is the entire reset: every vertex and  |
//| every flag beyond the count is unreachable, so there is nothing   |
//| to erase. What survives is the allocation, and that is the point. |
//|                                                                   |
//| A dashboard that rebuilds its geometry on every tick calls this   |
//| thousands of times an hour. Freeing the arrays here would mean    |
//| the same memory is released and re-acquired on every one of those |
//| rebuilds, to end up at the same size it had a moment earlier.     |
//| Keeping it means the second frame, and every frame after it, adds |
//| its vertices without a single reallocation.                       |
//+-------------------------------------------------------------------+
void CCairoPath::Clear()
  {
   m_point_count   = 0;
   m_contour_count = 0;
   m_cur_x         = 0.0;
   m_cur_y         = 0.0;
   m_has_current   = false;
   m_alloc_failed  = false;
  }

//+-------------------------------------------------------------------+
//| Clear, and hand the memory back to the terminal.                  |
//|                                                                   |
//| The other half of the pair. Use it when a path is genuinely done  |
//| with - a one-off import, a cached shape being dropped - and the   |
//| memory is worth more elsewhere than the next rebuild is worth     |
//| here. If you are unsure which of the two you want, you want       |
//| Clear().                                                          |
//+-------------------------------------------------------------------+
void CCairoPath::Release()
  {
   Clear();
   ArrayResize(m_points, 0);
   ArrayResize(m_starts, 0);
   ArrayResize(m_closed, 0);
  }

//+-------------------------------------------------------------------+
//| True when nothing has been added yet.                             |
//+-------------------------------------------------------------------+
bool CCairoPath::IsEmpty() const
  {
   return (m_contour_count == 0);
  }

//+-------------------------------------------------------------------+
//| Append a vertex and make it the current pen position.             |
//|                                                                   |
//| THE RESERVE ARGUMENT MATTERS.                                     |
//|                                                                   |
//| ArrayResize's third parameter is a reserve: it allocates extra    |
//| room beyond what was asked for, so the next 63 appends are free.  |
//| Without it, adding N points reallocates and copies N times, which |
//| turns a curve with 400 vertices - perfectly ordinary once Part 6  |
//| arrives - into 400 array copies.                                  |
//|                                                                   |
//| AND SO DOES THE RETURN VALUE.                                     |
//|                                                                   |
//| ArrayResize can fail. It is rare, it is usually the last thing on |
//| a developer's mind, and the cost of ignoring it is writing past   |
//| the end of an array - which in a graphical EA will not announce   |
//| itself at the point of the mistake, but somewhere later and       |
//| stranger. So the failure is refused here rather than written      |
//| through, m_alloc_failed remembers it, and IsValid() reports it.   |
//|                                                                   |
//| The bool exists for exactly one caller: MoveTo, which has already |
//| opened a contour by the time it calls this and has to take that   |
//| back if the vertex never arrives. Everywhere else the sticky flag |
//| is the better answer - checking every append would bury the       |
//| geometry in error handling to detect a condition that has already |
//| been recorded.                                                    |
//+-------------------------------------------------------------------+
bool CCairoPath::AddPoint(const double x, const double y)
  {
   const int i = m_point_count;

   if(ArraySize(m_points) < i + 1)
      if(ArrayResize(m_points, i + 1, 64) < i + 1)
        {
         m_alloc_failed = true;     // out of memory - refuse, do not write
         return false;
        }

   m_points[i].x = x;
   m_points[i].y = y;
   m_point_count++;

   m_cur_x       = x;
   m_cur_y       = y;
   m_has_current = true;

   return true;
  }

//+-------------------------------------------------------------------+
//| MoveTo - begin a NEW contour at (x, y).                           |
//|                                                                   |
//| Think of it as lifting the pen off the paper and putting it down  |
//| somewhere else. Everything drawn after this call belongs to a new |
//| outline, independent of the previous one, until the next MoveTo.  |
//|                                                                   |
//| Recording the start index - and an open flag - is all that        |
//| "beginning a contour" actually means.                             |
//|                                                                   |
//| The rollback at the end is not defensive noise. The contour is    |
//| counted before its first vertex exists, so a refused allocation   |
//| would otherwise leave a contour of length zero in the middle of   |
//| the path: something every loop downstream would have to know to   |
//| skip. Undoing the count keeps the promise that a contour which    |
//| exists has at least one vertex.                                   |
//+-------------------------------------------------------------------+
void CCairoPath::MoveTo(const double x, const double y)
  {
   const int c = m_contour_count;

   if(ArraySize(m_starts) < c + 1)
      if(ArrayResize(m_starts, c + 1, 16) < c + 1)
        {
         m_alloc_failed = true;
         return;
        }

   if(ArraySize(m_closed) < c + 1)
      if(ArrayResize(m_closed, c + 1, 16) < c + 1)
        {
         m_alloc_failed = true;
         return;
        }

   m_starts[c] = m_point_count;
   m_closed[c] = false;
   m_contour_count++;

   if(!AddPoint(x, y))
      m_contour_count--;      // <- the reason AddPoint returns bool:
//---   never leave an empty contour behind
  }

//+-------------------------------------------------------------------+
//| LineTo - straight segment from the pen to (x, y).                 |
//|                                                                   |
//| Calling LineTo with no pen down is not an error; it simply opens  |
//| a contour at that point, which is what the caller almost          |
//| certainly meant. Being forgiving here removes a whole class of    |
//| "why is my path empty" questions, and it is not an invention:     |
//| Cairo's own cairo_line_to behaves as cairo_move_to when there is  |
//| no current point. Matching it is the compatible choice, not the   |
//| lenient one.                                                      |
//|                                                                   |
//| Note that "no pen down" is a real piece of state, not a guess     |
//| from the contour count. After Close() the pen is lifted, so a     |
//| LineTo following a Close begins a new contour instead of adding a |
//| vertex to a contour the author already declared finished.         |
//+-------------------------------------------------------------------+
void CCairoPath::LineTo(const double x, const double y)
  {
   if(!m_has_current)
      MoveTo(x, y);
   else
      AddPoint(x, y);
  }

//+------------------------------------------------------------------+
//| Perpendicular distance from a point to the chord a->b.           |
//|                                                                  |
//| This is the flatness measure the whole flattener rests on, and   |
//| it is nothing but the 2D cross product. The magnitude of the     |
//| cross product of a->b and a->p is the area of the parallelogram  |
//| those two vectors span; divide that area by the base length      |
//| |a->b| and what is left is the height - which is the             |
//| perpendicular distance we are after. No trigonometry, no special |
//| case for a vertical chord, and exactly one square root.          |
//|                                                                  |
//| The degenerate branch handles a curve whose endpoints coincide - |
//| a loop, where the chord is a point and there is no line to       |
//| measure against. It is not hypothetical: a closed shape built by |
//| a loop over an angle produces it every time the loop wraps.      |
//+------------------------------------------------------------------+
double CCairoPath::DistanceToChord(const double px, const double py,
                                   const double ax, const double ay,
                                   const double bx, const double by)
  {
   const double dx   = bx - ax;
   const double dy   = by - ay;
   const double len2 = dx * dx + dy * dy;

//--- degenerate chord (a == b): no line to measure against, so
//--- fall back to plain point-to-point distance. The test is on
//--- the SQUARED length, which keeps the square root out of the
//--- branch that is about to return early anyway.
   if(len2 < 1e-12)
     {
      const double ex = px - ax;
      const double ey = py - ay;

      return MathSqrt(ex * ex + ey * ey);
     }

   const double cross = (px - ax) * dy - (py - ay) * dx;

   return MathAbs(cross) / MathSqrt(len2);
  }

//+------------------------------------------------------------------+
//| Adaptive cubic Bezier flattening, by recursive midpoint          |
//| splitting - the de Casteljau algorithm.                          |
//|                                                                  |
//| THE IDEA                                                         |
//|                                                                  |
//| A cubic Bezier is four points: the endpoints P0 and P3 that the  |
//| curve passes through, and two control points P1 and P2 that it   |
//| is pulled towards but never reaches.                             |
//|                                                                  |
//| A useful property follows from the definition: the curve always  |
//| lies inside the convex hull of its four points. So if BOTH       |
//| control points sit very close to the straight chord P0->P3, the  |
//| hull is barely thicker than the chord and the curve has nowhere  |
//| else to be - we can emit the chord and be done.                  |
//|                                                                  |
//| If they do not, split the curve in half and ask the same         |
//| question of each half. Each split roughly quarters the           |
//| deviation, so the recursion is shallow: an ordinary curve is     |
//| finished in five or six levels.                                  |
//|                                                                  |
//| WHY DE CASTELJAU                                                 |
//|                                                                  |
//| Splitting at t = 0.5 could be done by evaluating the cubic       |
//| polynomial and solving for two new control polygons. De          |
//| Casteljau does it with nothing but MIDPOINTS: average adjacent   |
//| control points, then average those, and again. Six averages give |
//| the point on the curve AND the control points of both halves. No |
//| powers, no divisions, and it is numerically stable - which is    |
//| not a throwaway remark when the input is not yours.              |
//|                                                                  |
//| THE DEPTH CAP                                                    |
//|                                                                  |
//| A hard guard against input the flatness test can never satisfy:  |
//| a NaN coordinate, an infinity, a control point that arrived from |
//| a division by zero. 18 is unreachable for any sane curve, which  |
//| is what makes it a good cap - it never fires when it should not, |
//| and it always fires when it must. Without it the recursion does  |
//| not terminate, and in a terminal that means a chart that stops   |
//| responding and an EA you cannot remove.                          |
//+------------------------------------------------------------------+
void CCairoPath::FlattenCubic(const double x0, const double y0,
                              const double x1, const double y1,
                              const double x2, const double y2,
                              const double x3, const double y3,
                              const int depth)
  {
   const double d1 = DistanceToChord(x1, y1, x0, y0, x3, y3);
   const double d2 = DistanceToChord(x2, y2, x0, y0, x3, y3);

//--- Flat enough, or too deep: emit the chord and stop.
//---
//--- Only the END point is emitted. The start is already in the
//--- array - put there by the MoveTo that opened the contour, by
//--- the LineTo before this curve, or by the previous recursive
//--- call. Emitting both ends would duplicate every interior
//--- vertex: same picture, twice the edges.
   if(depth >= 18 || (d1 + d2) <= CairoFlattenTolerance)
     {
      AddPoint(x3, y3);
      return;
     }

//--- de Casteljau split at t = 0.5: every value here is a midpoint
   const double x01 = (x0  + x1) * 0.5, y01 = (y0  + y1) * 0.5;
   const double x12 = (x1  + x2) * 0.5, y12 = (y1  + y2) * 0.5;
   const double x23 = (x2  + x3) * 0.5, y23 = (y2  + y3) * 0.5;
   const double xa  = (x01 + x12) * 0.5, ya  = (y01 + y12) * 0.5;
   const double xb  = (x12 + x23) * 0.5, yb  = (y12 + y23) * 0.5;
   const double xm  = (xa  + xb) * 0.5, ym  = (ya  + yb) * 0.5;

//--- Left half first, then the right half. THE ORDER MATTERS:
//--- vertices are appended in traversal order, and a contour whose
//--- vertices arrive out of order is not the shape you drew - it
//--- is a self-intersecting one, which the fill rules of Part 5
//--- will shade in ways that are hard to diagnose from a picture.
   FlattenCubic(x0, y0, x01, y01, xa,  ya,  xm, ym, depth + 1);
   FlattenCubic(xm, ym, xb,  yb,  x23, y23, x3, y3, depth + 1);
  }

//+------------------------------------------------------------------+
//| CurveTo - a cubic Bezier from the pen, through the control       |
//| points (x1,y1) and (x2,y2), ending at (x3,y3).                   |
//|                                                                  |
//| This is the workhorse of vector graphics: SVG's C command,       |
//| PostScript's curveto, and every OpenType glyph outline reduce to |
//| this curve. Adding it is what lets the library consume geometry  |
//| that was authored somewhere else.                                |
//|                                                                  |
//| The START point is implicit - it is wherever the pen already is. |
//| That is why CCairoPath has tracked m_cur_x / m_cur_y since       |
//| Part 2, when it looked like a small convenience for LineTo.      |
//|                                                                  |
//| Note what this function does NOT do: it does not store a curve.  |
//| It flattens immediately, into the arrays MoveTo and LineTo have  |
//| always used, so the path stays one kind of object forever.       |
//|                                                                  |
//| With no pen down it opens a contour first, exactly as LineTo     |
//| does. Without that, the flattener would append vertices to a     |
//| contour that does not exist.                                     |
//+------------------------------------------------------------------+
void CCairoPath::CurveTo(const double x1, const double y1,
                         const double x2, const double y2,
                         const double x3, const double y3)
  {
   if(!m_has_current)
      MoveTo(m_cur_x, m_cur_y);

   FlattenCubic(m_cur_x, m_cur_y, x1, y1, x2, y2, x3, y3, 0);
  }

//+------------------------------------------------------------------+
//| QuadTo - a quadratic Bezier, with ONE control point.             |
//|                                                                  |
//| Rather than write a second flattener, the quadratic is RAISED to |
//| an equivalent cubic. The conversion is standard:                 |
//|                                                                  |
//|     C1 = P0 + 2/3 * (Q - P0)                                     |
//|     C2 = P2 + 2/3 * (Q - P2)                                     |
//|                                                                  |
//| Nothing is approximated. This is degree elevation, and it is     |
//| exact for Bezier curves: those two control points describe the   |
//| same curve as the original single one, point for point, at every |
//| value of t. The library therefore keeps ONE curve                |
//| implementation - one place for a bug to live instead of two.     |
//|                                                                  |
//| Quadratics matter because TrueType fonts use them exclusively,   |
//| so any future glyph work arrives through this function.          |
//+------------------------------------------------------------------+
void CCairoPath::QuadTo(const double cx, const double cy,
                        const double x,  const double y)
  {
   const double x1 = m_cur_x + 2.0 / 3.0 * (cx - m_cur_x);
   const double y1 = m_cur_y + 2.0 / 3.0 * (cy - m_cur_y);
   const double x2 = x       + 2.0 / 3.0 * (cx - x);
   const double y2 = y       + 2.0 / 3.0 * (cy - y);

   CurveTo(x1, y1, x2, y2, x, y);
  }
//+------------------------------------------------------------------+
//| StepForRadius - the angular step, in radians, that keeps an arc  |
//| within CairoFlattenTolerance of the true circle.                 |
//|                                                                  |
//| Part 6 flattened curves by RECURSIVE SUBDIVISION, because for a  |
//| general Bezier there is no closed form for "how many segments do |
//| I need". For a CIRCULAR arc there is one, so we use it: a line of|
//| trigonometry replaces the whole recursion.                       |
//|                                                                  |
//| THE DERIVATION                                                   |
//|                                                                  |
//| The SAGITTA is the height of the bulge between a chord and the   |
//| arc it cuts off. For an arc spanning angle da on a circle of     |
//| radius r:                                                        |
//|                                                                  |
//|     h = r * ( 1 - cos( da / 2 ) )                                |
//|                                                                  |
//| That h is exactly the error we are trying to bound. Set it to the|
//| tolerance and solve for the angle:                               |
//|                                                                  |
//|     tol = r * ( 1 - cos( da / 2 ) )                              |
//|     cos( da / 2 ) = 1 - tol / r                                  |
//|     da = 2 * acos( 1 - tol / r )                                 |
//|                                                                  |
//| The practical consequence is the one that matters: a 4-pixel     |
//| corner radius gets a handful of segments, a 300-pixel circle gets|
//| many, and NEITHER NUMBER WAS GUESSED. Every arc in the library is|
//| as smooth as the tolerance demands, at any size.                 |
//+------------------------------------------------------------------+
double CCairoPath::StepForRadius(const double r) const
  {
   double ratio = CairoFlattenTolerance / r;

//--- a tolerance larger than the radius means one segment is
//--- already more accurate than we asked for
   if(ratio > 1.0)
      ratio = 1.0;

   double step = 2.0 * MathArccos(1.0 - ratio);

//--- guard against a step so small the segment count explodes -
//--- this happens for an absurdly tiny tolerance on a huge radius
   if(step <= 1e-4)
      step = 0.25;

   return step;
  }

//+------------------------------------------------------------------+
//| ArcTo - a circular arc, appended as straight segments.           |
//|                                                                  |
//| ANGLES ARE IN DEGREES, and the convention is the SCREEN one:     |
//|                                                                  |
//|       0   points right  (+x)                                     |
//|      90   points DOWN   (+y)                                     |
//|     180   points left                                            |
//|     270   points up                                              |
//|                                                                  |
//| The 90-means-down part surprises people. It follows from y       |
//| growing downward in a pixel buffer, and it is worth internalizing|
//| because it makes the rounded-rectangle corners below read        |
//| naturally: sweeping from -90 to 0 draws the top-right quarter,   |
//| which is exactly the corner you want there.                      |
//|                                                                  |
//| This appends to the CURRENT contour rather than starting a new   |
//| one, so an arc composes with LineTo - which is precisely how     |
//| AddRoundRect is built.                                           |
//+------------------------------------------------------------------+
void CCairoPath::ArcTo(const double cx, const double cy, const double r,
                       const double deg_from, const double deg_to)
  {
//--- a zero-radius corner is just the corner point itself. This is
//--- not an error case - it is how AddRoundRect draws a square
//--- corner without a special branch.
   if(r <= 0.0)
     {
      LineTo(cx, cy);
      return;
     }

   const double a0   = deg_from * M_PI / 180.0;
   const double a1   = deg_to   * M_PI / 180.0;
   const double step = StepForRadius(r);

   int n = (int)MathCeil(MathAbs(a1 - a0) / step);

   if(n < 1)
      n = 1;

   ReservePoints(m_point_count + n + 1);     // the count is known here

//--- THE START VERTEX. The loop below begins at i = 1, so it never
//--- emits the point at a0 - it assumes the pen is already there.
//--- That holds for AddRoundRect, where a LineTo has just walked
//--- the pen to the corner, and it is false everywhere else. A pie
//--- slice calling MoveTo( center ) then ArcTo() would silently
//--- lose its first vertex, so every wedge would start one segment
//--- late and the whole chart would appear rotated.
//---
//--- Three cases, which is what Cairo's own arc() does:
//---   no pen down       - the arc opens a new contour
//---   pen already at a0 - nothing to add
//---   pen somewhere else- join to the arc with a straight line
   const double sx = cx + r * MathCos(a0);
   const double sy = cy + r * MathSin(a0);

   if(!m_has_current)
      MoveTo(sx, sy);
   else
      if(MathAbs(m_cur_x - sx) > 1e-9 ||
         MathAbs(m_cur_y - sy) > 1e-9)
         LineTo(sx, sy);

   for(int i = 1; i <= n; i++)
     {
      const double a = a0 + (a1 - a0) * i / n;

      LineTo(cx + r * MathCos(a), cy + r * MathSin(a));
     }
  }

//+-------------------------------------------------------------------+
//| Close the current contour.                                        |
//|                                                                   |
//| It stores no vertex, and that is worth being precise about,       |
//| because "adds nothing to the array" and "does nothing" are not    |
//| the same statement.                                               |
//|                                                                   |
//| The closing SEGMENT is never stored, by anyone. When Part 3 turns |
//| contours into edges it joins the last vertex back to the first    |
//| unconditionally, because a fill needs a boundary that closes -    |
//| an open outline has no inside to fill. So no geometry is missing  |
//| here and none needs adding.                                       |
//|                                                                   |
//| What this function records is the author's INTENT, which the fill |
//| rule cannot tell us and must not be confused with. A polyline     |
//| that happens to end where it started is not a closed contour; a   |
//| triangle whose three vertices are far apart is. The difference is |
//| invisible in the vertex array and decides real behaviour later:   |
//| whether a stroke draws a join or two end caps at that vertex,     |
//| what an SVG exporter writes, what hit testing answers. Recovering |
//| it afterwards would mean guessing, and a geometry layer that      |
//| guesses is a geometry layer that is wrong occasionally.           |
//|                                                                   |
//| Following Cairo, the pen also returns to the start of the contour |
//| and is lifted: the contour is finished, so the next LineTo starts |
//| a new one rather than reopening this.                             |
//+-------------------------------------------------------------------+
void CCairoPath::Close()
  {
   if(m_contour_count == 0)
      return;

   const int c = m_contour_count - 1;
   m_closed[c] = true;             // record the intent - this is the whole point

//--- Cairo semantics: the pen returns to where this contour began.
//--- The contour is finished, so the next LineTo opens a new one.
   const int s = m_starts[c];
   if(s < m_point_count)
     {
      m_cur_x = m_points[s].x;
      m_cur_y = m_points[s].y;
     }
   m_has_current = false;
  }

//+-------------------------------------------------------------------+
//| Axis-aligned rectangle.                                           |
//|                                                                   |
//| Note that the library's very first "shape" is four lines of       |
//| arithmetic and no special support anywhere else. That is the      |
//| pattern every shape follows to the end of the series: a helper    |
//| emits vertices, and nothing downstream learns a new case.         |
//|                                                                   |
//| The vertex order - top-left, top-right, bottom-right, bottom-left |
//| - is the same rotational direction every helper in this library   |
//| uses. That matters in Part 5, where the non-zero fill rule reads  |
//| the RELATIVE direction of two contours: a hole has to be wound    |
//| against the outline that contains it. Emitting vertices in a      |
//| stable order is what makes that relationship something a caller   |
//| controls rather than discovers. Note that the library never       |
//| re-winds what it is given - AddPolygon stores the order it        |
//| receives, and it is the caller's to decide.                       |
//+-------------------------------------------------------------------+
void CCairoPath::AddRect(const double x, const double y, const double w, const double h)
  {
   MoveTo(x,     y);
   LineTo(x + w, y);
   LineTo(x + w, y + h);
   LineTo(x,     y + h);
   Close();
  }

//+-------------------------------------------------------------------+
//| Triangle from three arbitrary points.                             |
//+-------------------------------------------------------------------+
void CCairoPath::AddTriangle(const double x0, const double y0,
                             const double x1, const double y1,
                             const double x2, const double y2)
  {
   MoveTo(x0, y0);
   LineTo(x1, y1);
   LineTo(x2, y2);
   Close();
  }

//+-------------------------------------------------------------------+
//| Arbitrary CLOSED polygon from parallel x / y arrays.              |
//|                                                                   |
//| This is the escape hatch, and it is more powerful than it looks:  |
//| a star, a gear, a chevron, an arrow, a price chart's filled area, |
//| a hexagon - anything whose vertices you can compute, you can      |
//| describe. It is also, quietly, all a circle ever is. Part 7 will  |
//| simply compute the vertices for you.                              |
//|                                                                   |
//| The n < 3 guard belongs to this helper and not to the path model. |
//| A polygon is a shape with an inside, and two vertices enclose no  |
//| area, so there is nothing here to build. That is not a claim that |
//| paths must be closed - AddPolyline below stores exactly the same  |
//| vertices without closing them, and a two-point contour is a       |
//| perfectly legal path. The two helpers differ in one line, and     |
//| that line is the whole distinction.                               |
//+-------------------------------------------------------------------+
void CCairoPath::AddPolygon(const double &xs[], const double &ys[], const int n)
  {
//--- a FILLED polygon needs area; use AddPolyline for open shapes
   if(n < 3)
      return;

   if(ArraySize(xs) < n || ArraySize(ys) < n)         // fewer points than promised
      return;

   ReservePoints(m_point_count + n);                  // the count is known: ask once

   MoveTo(xs[0], ys[0]);

   for(int i = 1; i < n; i++)
      LineTo(xs[i], ys[i]);

   Close();
  }

//+-------------------------------------------------------------------+
//| Arbitrary OPEN polyline from parallel x / y arrays.               |
//|                                                                   |
//| The same vertices as AddPolygon, minus the Close(). An indicator  |
//| line, an equity curve, a zig-zag, the outline of a channel - none |
//| of these are shapes with an inside, and saying so is the point of |
//| having both helpers rather than one.                              |
//|                                                                   |
//| Two vertices are enough: a single segment is a legitimate path.   |
//+-------------------------------------------------------------------+
void CCairoPath::AddPolyline(const double &xs[], const double &ys[], const int n)
  {
//--- one point is not a line
   if(n < 2)
      return;

   if(ArraySize(xs) < n || ArraySize(ys) < n)
      return;

   ReservePoints(m_point_count + n);

   MoveTo(xs[0], ys[0]);

   for(int i = 1; i < n; i++)
      LineTo(xs[i], ys[i]);

//--- deliberately no Close(): this contour stays open, and the path
//--- now remembers that instead of leaving it to be guessed
  }
//+------------------------------------------------------------------+
//| AddRoundRect - a rectangle with an INDEPENDENT radius per corner.|
//|                                                                  |
//| One function covers most of an interface, because the four radii |
//| are what distinguish the shapes from one another:                |
//|                                                                  |
//|     card         r, r, r, r      all four rounded                |
//|     tab          r, r, 0, 0      rounded on top only             |
//|     pill         h/2 everywhere  a capsule                       |
//|     chat bubble  r, r, r, 0      one square corner, at the       |
//|                                  speaker                         |
//|     side panel   r, 0, 0, r      rounded down one side           |
//|     ticket       0, r, 0, r      notched diagonally              |
//|                                                                  |
//| The corner ORDER is top-left, top-right, bottom-right, bottom-   |
//| left - the same order CSS uses for border-radius, so a design    |
//| spec translates without rearranging anything.                    |
//|                                                                  |
//| THE CLAMP                                                        |
//|                                                                  |
//| Every radius is limited to half the SHORTER side. Without that, a|
//| radius larger than the box makes the corner arcs overshoot and   |
//| the outline self-intersect - and the non-zero rule then fills a  |
//| bow-tie, which is a baffling thing to see and a hard one to trace|
//| back to a number in a caller.                                    |
//|                                                                  |
//| With the clamp, an over-large radius degrades into a capsule.    |
//| That is not damage limitation, it is a FEATURE: passing a        |
//| deliberately huge radius is the idiomatic way to ask for a pill  |
//| without having to know the height.                               |
//|                                                                  |
//| Note there is no special case for a zero radius. ArcTo already   |
//| treats r = 0 as "just go to the corner point", so a square corner|
//| falls out of the same code path.                                 |
//+------------------------------------------------------------------+
void CCairoPath::AddRoundRect(const double x, const double y,
                              const double w, const double h,
                              const double r_tl, const double r_tr,
                              const double r_br, const double r_bl)
  {
   const double max_r = MathMin(w, h) * 0.5;

   double tl = r_tl, tr = r_tr, br = r_br, bl = r_bl;

//--- a negative radius is meaningless; treat it as square
   if(tl < 0.0)
      tl = 0.0;
   if(tr < 0.0)
      tr = 0.0;
   if(br < 0.0)
      br = 0.0;
   if(bl < 0.0)
      bl = 0.0;

   if(tl > max_r)
      tl = max_r;
   if(tr > max_r)
      tr = max_r;
   if(br > max_r)
      br = max_r;
   if(bl > max_r)
      bl = max_r;

//--- Start just after the top-left corner, then walk the outline:
//--- straight edge, quarter arc, straight edge, quarter arc, and
//--- round. The winding direction matches AddRect and every other
//--- helper, for the reasons Part 5 demonstrated.
   MoveTo(x + tl, y);

   LineTo(x + w - tr, y);
   ArcTo(x + w - tr, y + tr, tr, -90.0, 0.0);           // top-right

   LineTo(x + w, y + h - br);
   ArcTo(x + w - br, y + h - br, br, 0.0, 90.0);        // bottom-right

   LineTo(x + bl, y + h);
   ArcTo(x + bl, y + h - bl, bl, 90.0, 180.0);          // bottom-left

   LineTo(x, y + tl);
   ArcTo(x + tl, y + tl, tl, 180.0, 270.0);             // top-left

   Close();
  }

//+------------------------------------------------------------------+
//| The same radius on all four corners - the common case.           |
//+------------------------------------------------------------------+
void CCairoPath::AddRoundRect(const double x, const double y,
                              const double w, const double h,
                              const double r)
  {
   AddRoundRect(x, y, w, h, r, r, r, r);
  }

//+------------------------------------------------------------------+
//| AddEllipse.                                                      |
//|                                                                  |
//| The segment count comes from StepForRadius applied to the LARGER |
//| radius, which is the conservative choice: the tighter end of an  |
//| ellipse is the part that needs the segments, and sizing for the  |
//| larger radius guarantees enough of them everywhere.              |
//|                                                                  |
//| So a 6-pixel dot and a 400-pixel disc are each as smooth as they |
//| need to be, and no smoother. Same principle as Part 6's adaptive |
//| flattening, arrived at by formula instead of by recursion.       |
//+------------------------------------------------------------------+
void CCairoPath::AddEllipse(const double cx, const double cy,
                            const double rx, const double ry)
  {
   const double r    = MathMax(rx, ry);
   const double step = StepForRadius(r);

   int n = (int)MathCeil(2.0 * M_PI / step);

//--- never let a tiny ellipse collapse into a triangle: below
//--- about eight sides the eye reads it as a polygon, however
//--- correct the tolerance calculation was
   if(n < 8)
      n = 8;

   ReservePoints(m_point_count + n);          // the count is known here

   MoveTo(cx + rx, cy);

//--- stop at n-1: the final vertex would coincide with the first,
//--- and BuildEdges closes the contour for us anyway
   for(int i = 1; i < n; i++)
     {
      const double a = 2.0 * M_PI * i / n;

      LineTo(cx + rx * MathCos(a), cy + ry * MathSin(a));
     }

   Close();
  }

//+------------------------------------------------------------------+
//| AddCircle - an ellipse with equal radii.                         |
//|                                                                  |
//| Four articles of demos have been faking this with hand-computed  |
//| polygons. It turns out the fake was the real thing all along: a  |
//| circle IS a polygon, and the only question ever worth asking was |
//| how many sides to give it.                                       |
//+------------------------------------------------------------------+
void CCairoPath::AddCircle(const double cx, const double cy,
                           const double r)
  {
   AddEllipse(cx, cy, r, r);
  }
//+------------------------------------------------------------------+
//| AddThickLine - one segment of a stroke, as a closed quad.        |
//|                                                                  |
//| The engine has no stroker and is not going to get one. A line    |
//| with width IS a shape, so we build it out of the only thing the  |
//| rasterizer understands: a filled contour.                        |
//|                                                                  |
//| The normal of a direction (dx, dy) is (-dy, dx) - the same       |
//| vector turned ninety degrees. Make it one unit long, scale it by |
//| half the thickness, and push each endpoint both ways. That is    |
//| four corners.                                                    |
//|                                                                  |
//|       p0 + n  *-------------------------*  p1 + n                |
//|               |                         |                        |
//|         p0 ---+-------------------------+--- p1                  |
//|               |                         |                        |
//|       p0 - n  *-------------------------*  p1 - n                |
//|                                                                  |
//| The four corners are emitted in a CONSISTENT rotational order,   |
//| and that is not cosmetic. Every quad of a polyline must be wound |
//| the same way. If one of them is wound backwards, the overlap at  |
//| the joint sums to zero under the non-zero rule, and the stroke   |
//| gets a hole at that corner. The demo shows that failure on       |
//| purpose.                                                         |
//+------------------------------------------------------------------+
void CCairoPath::AddThickLine(const double x0, const double y0,
                              const double x1, const double y1,
                              const double thickness)
  {
   const double dx  = x1 - x0;
   const double dy  = y1 - y0;
   const double len = MathSqrt(dx * dx + dy * dy);

//--- a zero-length segment has no direction, so it has no normal
//--- and no quad. Returning is correct; dividing is not.
   if(len < 1e-9)
      return;

//--- the quad is four vertices in one new contour
   ReservePoints(m_point_count + 4);

//--- unit normal, scaled to half the thickness
   const double nx = -dy / len * (thickness * 0.5);
   const double ny =  dx / len * (thickness * 0.5);

   MoveTo(x0 + nx, y0 + ny);
   LineTo(x0 - nx, y0 - ny);
   LineTo(x1 - nx, y1 - ny);
   LineTo(x1 + nx, y1 + ny);
   Close();
  }

//+-------------------------------------------------------------------+
//| Index of the first vertex of contour c.                           |
//+-------------------------------------------------------------------+
int CCairoPath::ContourStart(const int c) const
  {
   if(c < 0 || c >= m_contour_count)
      return 0;

   return m_starts[c];
  }

//+-------------------------------------------------------------------+
//| Number of vertices in contour c.                                  |
//|                                                                   |
//| The last contour runs to the end of the point array; every other  |
//| one runs up to where the next contour begins. This is the only    |
//| slightly subtle consequence of the flat storage, and it is worth  |
//| the trade.                                                        |
//+-------------------------------------------------------------------+
int CCairoPath::ContourLength(const int c) const
  {
   if(c < 0 || c >= m_contour_count)
      return 0;

   const int start = m_starts[c];
   const int end   = (c + 1 < m_contour_count) ? m_starts[c + 1] : m_point_count;

   return end - start;
  }
//+-------------------------------------------------------------------+
//| Ask for room for `capacity` vertices in total.                    |
//|                                                                   |
//| AddPoint already grows in blocks of 64, so this is not about      |
//| avoiding reallocation altogether - it is about not doing it at    |
//| all when the answer is known in advance. A flattened curve, a     |
//| circle of 96 segments, a glyph outline, an imported SVG: in every |
//| one of those the vertex count is computed before the first vertex |
//| is stored, and one allocation of the right size beats six that    |
//| grow into it.                                                     |
//|                                                                   |
//| Note what "capacity" means here: this raises ArraySize above      |
//| m_point_count without adding a single valid vertex. PointCount()  |
//| does not change. That is the size / capacity invariant at the top |
//| of the class doing its job.                                       |
//+-------------------------------------------------------------------+
bool CCairoPath::ReservePoints(const int capacity)
  {
   if(capacity <= ArraySize(m_points))
      return true;

   if(ArrayResize(m_points, capacity) < capacity)
     {
      m_alloc_failed = true;
      return false;
     }

   return true;
  }

//+-------------------------------------------------------------------+
//| The same, for the two per-contour arrays.                         |
//|                                                                   |
//| Both are grown, and both are tested: m_starts and m_closed are    |
//| indexed by the same contour number, so a path in which one is     |
//| larger than the other is a path waiting to read a flag that was   |
//| never written.                                                    |
//+-------------------------------------------------------------------+
bool CCairoPath::ReserveContours(const int capacity)
  {
   if(capacity <= ArraySize(m_starts) && capacity <= ArraySize(m_closed))
      return true;

   if(ArrayResize(m_starts, capacity) < capacity)
     {
      m_alloc_failed = true;
      return false;
     }

   if(ArrayResize(m_closed, capacity) < capacity)
     {
      m_alloc_failed = true;
      return false;
     }

   return true;
  }

//+-------------------------------------------------------------------+
//| Did the author call Close() on this contour?                      |
//|                                                                   |
//| An out-of-range contour answers "not closed" rather than raising: |
//| the honest answer about a contour that does not exist.            |
//+-------------------------------------------------------------------+
bool CCairoPath::IsContourClosed(const int c) const
  {
   if(c < 0 || c >= m_contour_count)
      return false;

   return m_closed[c];
  }

//+-------------------------------------------------------------------+
//| Read one vertex, safely.                                          |
//|                                                                   |
//| The checked counterpart to PointX / PointY. It costs a comparison |
//| and it cannot go wrong, which is the right trade everywhere       |
//| except the rasteriser's inner loop.                               |
//+-------------------------------------------------------------------+
bool CCairoPath::GetPoint(const int i, SCairoPoint &pt) const
  {
   if(i < 0 || i >= m_point_count)
      return false;

   pt = m_points[i];
   return true;
  }

//+-------------------------------------------------------------------+
//| Everything about one contour, in a single checked call.           |
//|                                                                   |
//| Walking a path means asking three questions per contour - where   |
//| does it start, how long is it, was it closed - and getting them   |
//| individually invites the fourth mistake of asking about a contour |
//| that is not there. One call, one range check, three answers.      |
//+-------------------------------------------------------------------+
bool CCairoPath::GetContourInfo(const int c, int &start, int &length, bool &closed) const
  {
   if(c < 0 || c >= m_contour_count)
      return false;

   start  = ContourStart(c);
   length = ContourLength(c);
   closed = m_closed[c];

   return true;
  }

//+-------------------------------------------------------------------+
//| Is every stored coordinate a real number?                         |
//|                                                                   |
//| The one place the coordinate contract can be checked cheaply: one |
//| linear pass, on demand, on a finished path. Worth calling when    |
//| the vertices came from indicator buffers or from arithmetic that  |
//| can divide by zero - a NaN found here is a bug with an address,   |
//| while the same NaN found by the rasteriser is a blank panel with  |
//| no explanation.                                                   |
//+-------------------------------------------------------------------+
bool CCairoPath::IsFinite() const
  {
   for(int i = 0; i < m_point_count; i++)
      if(!MathIsValidNumber(m_points[i].x) ||
         !MathIsValidNumber(m_points[i].y))
         return false;

   return true;
  }

//+-------------------------------------------------------------------+
//| BuildEdges - turn every contour into edges.                       |
//|                                                                   |
//| EVERY CONTOUR IS CLOSED HERE, WHATEVER THE AUTHOR ASKED FOR.      |
//|                                                                   |
//| The modulo on the index wraps the last vertex of a contour back   |
//| to its first, so the closing segment nobody stored is produced    |
//| right here. It is produced for open contours too, and that is     |
//| not a contradiction of the closed flag. A fill needs a boundary   |
//| that closes, because an outline with a gap has no inside, so      |
//| filling an open contour can only mean filling the shape it would  |
//| be if it were closed.                                             |
//|                                                                   |
//| The two answers live side by side and both are correct. m_closed  |
//| says what the author wrote, and a stroke will read it in a later  |
//| part to choose between a joint and two end caps. This loop says   |
//| what a fill has to do, and that is not a matter of opinion.       |
//| After it returns, nothing downstream can tell an open contour     |
//| from a closed one - which is exactly why the flag had to be       |
//| recorded before this point instead of guessed after it.           |
//|                                                                   |
//| This function is also the last thing in the pipeline that knows   |
//| about contours. What leaves it is one flat list of segments with  |
//| no grouping at all.                                               |
//+-------------------------------------------------------------------+
void CCairoPath::BuildEdges(CCairoEdgeList &out)
  {
   out.Clear();

//--- a path that was refused memory is not geometry we can trust,
//--- and half a shape on screen is worse than no shape at all
   if(!IsValid())
      return;

//--- each contour emits exactly as many edges as it has vertices,
//--- so the total is known before the loop starts
   out.Reserve(m_point_count);

   for(int c = 0; c < m_contour_count; c++)
     {
      const int start = m_starts[c];
      const int count = ContourLength(c);

      //--- one vertex encloses no area, so it produces no edges
      if(count < 2)
         continue;

      for(int i = 0; i < count; i++)
        {
         const int a = start + i;
         const int b = start + ((i + 1) % count);       // wrap = auto-close

         out.Add(m_points[a].x, m_points[a].y,
                 m_points[b].x, m_points[b].y);
        }
     }
  }

#endif // CAIRO5_PATH_MQH
