preview
Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 10): Transforms and the Graphics Context

Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 10): Transforms and the Graphics Context

MetaTrader 5 — Integration |
762 0
Sandro Begashvili
Sandro Begashvili

Contents


Introduction

After nine parts the engine is complete as a set of parts. It flattens curves, sweeps scanlines, computes coverage, blends premultiplied colors, fills under either winding rule, paints with solids and gradients, and stops at a clip that can be a rectangle or any path at all.

What it is not yet is comfortable to use.

Here is a button, drawn with everything the library has:

CCairoPath   path;
CCairoClip   clip;
CCairoRasterizer ras;

clip.Reset(surface.Width(), surface.Height());

path.Clear();
path.AddRoundRect(x + 0, y + 0, w, h, 6);
ras.Fill(path, 0xFF1F6FEB, surface.m_px,
         surface.Width(), surface.Height(), CAIRO_NONZERO,
         GetPointer(clip));

Every call needs the buffer, the width and the height. Every coordinate is written as x + something, because the caller is drawing in screen pixels and the button does not live at the origin. If the same button has to appear in four places, the x + and y + are repeated in every line of its geometry, and if it has to appear rotated, there is no way to write it at all.

Two things are missing, and they are the two things a 2D library of this kind generally ends up with. The first is a transform — a rule that converts the coordinates a caller writes into the pixels the rasterizer draws, so that a widget can be written once at the origin and placed anywhere. The second is a context — one object that remembers the transform, the clip, the source color and the fill rule, and that can push a copy of all four aside and get them back.

This part builds both. No pixel-level code changes: the rasterizer, the paints, the clip and the surface are untouched. Most of what follows is bookkeeping that used to live in the caller, moved to where it belongs — with one genuine change of meaning underneath it, which is that a stored vertex stops being the number the caller wrote and becomes the pixel it lands on.

Color.mqh      Part 1    the ARGB color type
Config.mqh     Part 4    the two quality dials
Surface.mqh    Part 1    a pixel buffer bound to one chart object
Paint.mqh      Part 8    the color source, and the two gradients
Clip.mqh       Part 9    where drawing is allowed to land
Raster.mqh     Parts 3-9 the scanline fill
Matrix.mqh     Part 10   six numbers, user space to device     <- new today
Path.mqh       Parts 2-9 the geometry layer
               Part 10   + the current transform               <- changed
Context.mqh    Part 10   the object an application talks to    <- new today

Two files are new and one is changed. Raster.mqh, Clip.mqh, Paint.mqh, Color.mqh, Config.mqh and Surface.mqh are not touched at all. That is not a proof of anything by itself — a badly placed feature can be small and a well placed one can be large — but it is the result you would predict if the transform belongs where this part puts it, and it is worth checking against the prediction rather than only asserting it.


Six numbers

A 2D affine transform is a rule for turning one point into another. It can translate, scale, rotate and skew, in any combination, and it always maps straight lines to straight lines and parallel lines to parallel lines. That last property is why it is the transform drawing APIs settle on: a transformed polygon is still a polygon, so nothing downstream has to change.

Six numbers describe it, and they are laid out the same way in SVG, PostScript, Cairo and HTML Canvas:

Figure 1. Where the two basis vectors and the origin land.

Reading the figure from the left: a and b are where the vector (1, 0) ends up, c and d are where (0, 1) ends up, and e and f are where the origin ends up. Everything else follows from those three answers, because an affine map is completely determined by what it does to the origin and to the two basis vectors.

Here is the whole header's declaration:

//+-------------------------------------------------------------------+
//|                                                       Matrix.mqh  |
//+-------------------------------------------------------------------+
#ifndef CAIRO5_MATRIX_MQH
#define CAIRO5_MATRIX_MQH

//+-------------------------------------------------------------------+
//| SCairoMatrix                                                      |
//+-------------------------------------------------------------------+
struct SCairoMatrix
  {
   double            a, b, c, d, e, f;

   //--- construction
   void              Identity();
   void              Set(const double ma, const double mb, const double mc,
              const double md, const double me, const double mf);
   void              CopyFrom(const SCairoMatrix &m);

   //--- composition. Each one APPENDS, so the newest call is the one
   //--- applied to the geometry first.
   void              Translate(const double tx, const double ty);
   void              Scale(const double sx, const double sy);
   void              Rotate(const double degrees);
   void              Skew(const double deg_x, const double deg_y);
   void              Multiply(const SCairoMatrix &m);
   void              PreMultiply(const SCairoMatrix &m);

   //--- queries
   double            Determinant() const;
   bool              IsIdentity() const;
   bool              IsInvertible() const;
   bool              Invert();
   double            ScaleFactor() const;

   //--- application
   void              Apply(const double x, const double y,
                double &out_x, double &out_y) const;
   void              ApplyDistance(const double dx, const double dy,
                        double &out_x, double &out_y) const;
  };

It is a struct rather than a class for two reasons. The constraint is MQL5's: a class object cannot be returned by value, and the builder functions at the end of the file return matrices while the graphics state holds one per saved level, by value. That alone could have been worked around — an out parameter, which this very file uses for Apply, would have done it. The design argument is the one that settles it: a matrix is six doubles that own no memory, copying it is free and correct, and value semantics are what the state stack wants. The language made the decision easy rather than making it for us.

Applying one

//+-------------------------------------------------------------------+
//| Transform a POINT: rotation, scale, shear and translation.        |
//+-------------------------------------------------------------------+
void SCairoMatrix::Apply(const double x, const double y,
                         double &out_x, double &out_y) const
  {
   out_x = a * x + c * y + e;
   out_y = b * x + d * y + f;
  }

This function runs once per vertex, so its cost dominates the feature. Per point it performs four multiplications and four additions (see the two lines above).

The one exception is Transform(): it applies a matrix to already-stored vertices by rewriting m_points in place. It is the right tool for geometry authored once and then placed forever — an icon, a glyph — and it carries a constraint the compiler will not enforce. It moves the stored points and leaves the pen and the contour origin where they were, so it belongs on a finished path. Baking a transform into a path that still has an open contour and then calling ClosePath() would close it to an origin the transform never touched.

The second application function is the one that is easy to forget:

//+-------------------------------------------------------------------+
//| Transform a DISTANCE: everything except the translation.          |
//+-------------------------------------------------------------------+
void SCairoMatrix::ApplyDistance(const double dx, const double dy,
                                 double &out_x, double &out_y) const
  {
   out_x = a * dx + c * dy;
   out_y = b * dx + d * dy;
  }

The translation is dropped. The distinction matters more than it looks: a line width, a radius and a direction vector are all distances, not positions. Translating a radius is meaningless — a radius of 5 under a translation of 100 is still a radius of 5 — and feeding one through Apply instead of ApplyDistance is the classic transform bug in every graphics codebase that has ever had one.

Composing them

//+-------------------------------------------------------------------+
//| Multiply function                                                 |
//| this = this * m                                                   |
//+-------------------------------------------------------------------+
void SCairoMatrix::Multiply(const SCairoMatrix &m)
  {
   const double na = a * m.a + c * m.b;
   const double nb = b * m.a + d * m.b;
   const double nc = a * m.c + c * m.d;
   const double nd = b * m.c + d * m.d;
   const double ne = a * m.e + c * m.f + e;
   const double nf = b * m.e + d * m.f + f;

   Set(na, nb, nc, nd, ne, nf);
  }

This is this = this * m. A point is transformed by m first and by the old this second. That ordering is the one thing in this file that is easy to get backwards, and it has a consequence worth stating as a rule:

The last call is the one closest to the geometry.

Figure 2. The same two calls, swapped, and where each lands.

In the left panel the code translates and then rotates. A point written afterwards is rotated first and translated second — so the shape stays at the translated position and spins around it. In the right panel the same two calls are swapped: now the point is translated first, into a coordinate system that is already rotated, so the shape swings away on an arc. The two results are not near each other, and the figure prints the origin and tip of each so the difference is a number rather than an impression.

This is the convention of every drawing API that has one, and it is what makes nesting work: a widget translates to its own corner, and everything drawn afterwards is relative to that corner.

Translate is written out longhand rather than built as a matrix and multiplied:

//+-------------------------------------------------------------------+
//| Append a translation.                                             |
//+-------------------------------------------------------------------+
void SCairoMatrix::Translate(const double tx, const double ty)
  {
   e += a * tx + c * ty;
   f += b * tx + d * ty;
  }

It is the most common call in the library, and the general form would be four multiplications by 1 or 0 and two additions of zero.

How much does this matrix magnify a length?

One query deserves its own section, because the obvious answer to it is wrong.

The flattener needs to know how much the transform stretches things. A curve written in user coordinates and then scaled up by 4 has to be subdivided four times as finely, or the facets that were invisible at 1x become visible at 4x. So SCairoMatrix has to answer: what is the largest factor by which this matrix can stretch any length?

The obvious candidate is the longer of the two columns — the lengths of the images of (1, 0) and (0, 1). Those are magnifications the matrix genuinely achieves, which makes them a lower bound, not an upper one. A shear defeats them:

a = 1  c = 1      the columns, and what they measure
b = 0  d = 1

    (1,0) -> (1,0)     length 1.000
    (0,1) -> (1,1)     length 1.414   <- the longer column

    the worst direction is neither of those:
    it is stretched by           1.618

The real answer is the larger singular value of the 2x2 part, and in two dimensions it needs no iteration at all — the two singular values solve a quadratic whose coefficients are the Frobenius norm and the determinant:

//+-------------------------------------------------------------------+
//| The most this matrix can magnify a length.                        |
//+-------------------------------------------------------------------+
double SCairoMatrix::ScaleFactor() const
  {
   const double frob = a * a + b * b + c * c + d * d;
   const double det  = a * d - b * c;

//--- zero for a rotation, and rounding can make it a very small
//--- negative instead of a very small positive
   double disc = frob * frob - 4.0 * det * det;

   if(disc < 0.0)
      disc = 0.0;

   const double s = MathSqrt((frob + MathSqrt(disc)) * 0.5);

//--- a degenerate matrix must not hand back zero, because the
//--- caller is about to divide by this
   if(!(s > 1e-12))
      return 1e-12;

   return s;
  }

Two asymmetries in this pair are worth stating, because neither is visible from reading one of them. And the result is floored rather than allowed to be zero, because the only caller divides by it.

It agrees with the longer column whenever the two columns are perpendicular — every rotation, every axis-aligned scale, every combination of the two — which is why a simpler formula is right about everything an interface normally does, and silently wrong about the one case where someone shears.


The path learns to write through a matrix

Now the matrix has to reach the geometry. There is exactly one place to put it.

Every vertex in this library — from MoveTo, from LineTo, from the Bézier flattener, from the arc stepper, from every shape helper written since Part 2 — enters through one function:

bool CCairoPath::AddPoint(const double x, const double y)

So that is where the transform goes, and nowhere else.

The new members: three for the transform, two for the contour start

   //--- PART 10: the transform every vertex passes through on its way
   //--- into the array above, and the length magnification it applies.
   //--- The scale is cached because the flattener divides the tolerance
   //--- by it once per curve rather than recomputing two square roots
   //--- every time it asks.
   SCairoMatrix      m_ctm;            // current transform, identity by default
   bool              m_has_ctm;        // false while it IS the identity
   double            m_ctm_scale;      // m_ctm.ScaleFactor()
   //--- PART 10: where the contour currently being built started,
   //--- kept in USER coordinates. m_points[] holds device coordinates
   //--- once a transform is installed, so Close() cannot take the pen
   //--- from it.
   double            m_open_ux;
   double            m_open_uy;

The first three fields carry the transform. The last two, m_open_ux and m_open_uy, are not part of the transform itself: they keep the start of the current contour in user coordinates, recorded by MoveTo, so that Close() can put the pen back at the start of the contour once m_points[] holds device coordinates.

m_has_ctm provides a fast path for identity transforms, avoiding unnecessary matrix arithmetic for each vertex. m_ctm_scale caches the result of ScaleFactor() for use by the curve flattener. Both choices are intended to reduce repeated calculations, but their actual performance benefit has not been measured. Maintaining and reinstalling the transform also has a cost, so no net speedup is claimed without benchmarking.

The public face of it

   //--- PART 10: THE TRANSFORM
   //--- SetTransform() installs a matrix that every later vertex passes
   //--- through. It does NOT touch what is already stored, so a path
   //--- can be built in two coordinate systems if that is what the
   //--- caller wants - and more usefully, a widget can set its own
   //--- placement once and then draw in its own coordinates.
   //---
   //--- Transform() is the other direction: it bakes a matrix into the
   //--- vertices that are already there.

   void              SetTransform(const SCairoMatrix &m);
   void              ClearTransform();
   bool              HasTransform() const { return m_has_ctm; }
   void              GetTransform(SCairoMatrix &out) const
     {               out.CopyFrom(m_ctm); }
   void              Transform(const SCairoMatrix &m);

Two of those do similar-sounding things and must not be confused. SetTransform installs a matrix that every later vertex passes through; it does not touch what is already stored. Transform bakes a matrix into the vertices that are already there, and changes the path.

The first is for placement that varies per frame — set it, draw, set it again, draw again, and the same geometry lands twice in two places. The second is for geometry authored once in its own space and then placed forever: an icon, a glyph, a logo imported from a file.

//+-------------------------------------------------------------------+
//| Install the transform every later vertex passes through.          |
//|                                                                   |
//| Vertices already stored are NOT touched. That is deliberate: the  |
//| transform describes where the geometry written from now on        |
//| belongs, not where the path as a whole sits. Use Transform()      |
//| below for the other meaning.                                      |
//+-------------------------------------------------------------------+
void CCairoPath::SetTransform(const SCairoMatrix &m)
  {
   m_ctm.CopyFrom(m);

   m_has_ctm   = !m_ctm.IsIdentity();
   m_ctm_scale = m_ctm.ScaleFactor();
  }
//+-------------------------------------------------------------------+
//| Bake a transform into the vertices already stored.                |
//+-------------------------------------------------------------------+
void CCairoPath::Transform(const SCairoMatrix &m)
  {
   for(int i = 0; i < m_point_count; i++)
     {
      double nx, ny;

      m.Apply(m_points[i].x, m_points[i].y, nx, ny);

      m_points[i].x = nx;
      m_points[i].y = ny;
     }
  }

Transform leaves the pen where it is. The pen holds user coordinates and this function is about the device-space result; moving it would make the caller's next LineTo land somewhere nobody asked for.

The one line that does the work

//+-------------------------------------------------------------------+
//| Append a vertex and make it the current pen position.             |
//+-------------------------------------------------------------------+
bool CCairoPath::AddPoint(const double x, const double y)
  {
//--- PART 10. EVERY vertex in the library arrives here - MoveTo,
//--- LineTo, the curve flattener and every shape helper - which is
//--- why the transform is applied at this one point and nowhere
//--- else. Stored coordinates are therefore always in the space the
//--- rasterizer draws in, and nothing downstream had to learn what
//--- a matrix is.
   double px = x;
   double py = y;

   if(m_has_ctm)
      m_ctm.Apply(x, y, px, py);

   const int i = m_point_count;

and further down, the stored values become the transformed ones while the pen keeps the originals:

   m_points[i].x = px;
   m_points[i].y = py;
   m_point_count++;

//--- the pen stays in USER coordinates, because that is the space
//--- the caller's next LineTo is written in
   m_cur_x       = x;
   m_cur_y       = y;
   m_has_current = true;

   return true;
  }

That split is worth dwelling on, because it is the only subtle thing in the file. The stored point is in device space, because that is the space the rasterizer works in and the space Bounds() and Contains() from Part 9 should answer in. The pen is in user space, because the next call the caller writes will be in user coordinates and a relative operation like ArcTo's implicit line has to start from where the caller thinks it is.

Clear() resets it

//--- PART 10: a reused path starts in its own coordinates again.
//--- Leaving a transform installed across a Clear() would make the
//--- next shape inherit the last widget's placement, which is the
//--- kind of bug that only shows up on the second frame.
   m_ctm.Identity();

   m_has_ctm   = false;
   m_ctm_scale = 1.0;
   m_open_ux   = 0.0;
   m_open_uy   = 0.0;
  }

A path that is cleared and rebuilt every frame is the normal case in this library. If the transform survived the clear, the first frame would be correct and every frame after it would draw the second widget where the first one was.

The tolerance follows the scale

Two functions change one word each. The curve flattener:

   if(depth >= 18 || (d1 + d2) <= UserTolerance())

and the arc stepper:

   double ratio = UserTolerance() / r;

The existing recursion depth limit of 18 is a defensive safeguard against excessive curve subdivision, not a precision target. In extreme cases, subdivision may stop at this limit before the requested tolerance is reached.

Both used to read CairoFlattenTolerance directly. Here is the new function:

//+-------------------------------------------------------------------+
//| The flattening tolerance, in the coordinates the caller writes.   |
//+-------------------------------------------------------------------+
double CCairoPath::UserTolerance() const
  {
   if(!m_has_ctm)
      return CairoFlattenTolerance;

   return (CairoFlattenTolerance / m_ctm_scale);
  }

CairoFlattenTolerance is measured in pixels — it is the largest deviation from the true curve anyone should be able to see. The flattener works in the coordinates the caller writes. Those are the same space only while the transform is the identity.

Figure 3. The same curve at three scales, measured.

The figure runs the library's own subdivision test three times. On the left, scale 1 and tolerance 0.3: sixteen segments, worst deviation 0.30 pixels, which is the quality the series has been producing since Part 6. In the middle, the same sixteen segments scaled up by 4 — the deviation is scaled with them, to 1.20 pixels, and the curve is measurably worse than it was. On the right, the tolerance divided by the scale first: thirty-two segments, and the deviation is back to 0.30 pixels on screen.

Scaled down, the same arithmetic works the other way and saves the segments nobody could have seen.


The context

With a transform in the path, the last piece is the object that owns one.

CCairoContext is the API an application actually uses. Everything underneath it is a component that is good at one job and knows nothing about the others, which is precisely why every part of this series has been short — and precisely why using the library has been verbose.

The state

//+-------------------------------------------------------------------+
//|                                                      Context.mqh  |
//+-------------------------------------------------------------------+
#ifndef CAIRO5_CONTEXT_MQH
#define CAIRO5_CONTEXT_MQH

#include "Config.mqh"
#include "Color.mqh"
#include "Matrix.mqh"
#include "Path.mqh"
#include "Paint.mqh"
#include "Clip.mqh"
#include "Raster.mqh"
#include "Surface.mqh"

//--- how deep Save() may nest. Bounded so that a missing Restore() in
//--- a loop fails loudly at a known depth instead of growing until the
//--- terminal runs out of memory.
#define CAIRO_MAX_STATE_DEPTH   32

//+-------------------------------------------------------------------+
//| SCairoState - everything Save() keeps a copy of.                  |
//+-------------------------------------------------------------------+
struct SCairoState
  {
   SCairoMatrix      ctm;              // user space -> device space
   ENUM_CAIRO_FILLRULE rule;
   uint              src_color;        // the source, when it is a flat color
   bool              use_color;        // false when a paint object is in use
   CCairoPaint       *src_paint;        // the source, when it is a paint
   // object. Borrowed, never owned.

   //--- NOTE the member name. `color` is a built-in type in MQL5 and
   //--- cannot be used as an identifier, which is the kind of thing
   //--- that is obvious only once the compiler has said so.
  };

Five fields, and the rule for what belongs here is absolute: anything a setter on the context changes has to be in this struct, or Restore() hands back a state that is only mostly the old one. A context that restores four things out of five is worse than one that restores nothing, because the bug it produces appears two widgets later and looks like someone else's fault.

The comment about src_paint being borrowed is load-bearing. The context never deletes it; a gradient belongs to whoever made it, and a context that destroyed a caller's paint on Restore() would be unusable.

One MQL5 note: the member is called src_color, not color, because color is a built-in type name in MQL5 and cannot be used as an identifier. That is the kind of thing that is obvious the moment the compiler says so and invisible until then.

The class

//+-------------------------------------------------------------------+
//| SCairoState - everything Save() keeps a copy of.                  |
//+-------------------------------------------------------------------+
struct SCairoState
  {
   SCairoMatrix      ctm;              // user space -> device space
   ENUM_CAIRO_FILLRULE rule;
   uint              src_color;        // the source, when it is a flat color
   bool              use_color;        // false when a paint object is in use
   CCairoPaint       *src_paint;        // the source, when it is a paint
   // object. Borrowed, never owned.

   //--- NOTE the member name. `color` is a built-in type in MQL5 and
   //--- cannot be used as an identifier, which is the kind of thing
   //--- that is obvious only once the compiler has said so.
  };

//+-------------------------------------------------------------------+
//| CCairoContext                                                     |
//+-------------------------------------------------------------------+
class CCairoContext
  {
private:
   //--- where the pixels go
   CCairoSurface     *m_surface;

   //--- the machinery, owned and reused
   CCairoRasterizer  m_ras;

   //--- the current path
   CCairoPath        m_path;

   //--- the solid paint the flat-color source is poured into. The
   //--- paint-object source lives in the state instead, so that Save()
   //--- and Restore() cover it.
   CCairoSolidPaint  m_solid;

   //--- the state, and the stack of saved copies
   SCairoState       m_state;
   SCairoState       m_stack[CAIRO_MAX_STATE_DEPTH];
   int               m_depth;

   //--- the clip, and one saved copy per state level
   CCairoClip        m_clip;
   CCairoClip        *m_clip_stack[CAIRO_MAX_STATE_DEPTH];

   //--- where drawing currently lands. NOT const: CCairoSurface's own
   //--- accessors are not const either, and this file does not get to
   //--- change a header that shipped in Part 1.
   int               TargetWidth();
   int               TargetHeight();

   //--- the one place that knows which buffer is current
   void              FillInto(CCairoPath &path, CCairoPaint *paint,
                              const ENUM_CAIRO_FILLRULE rule);
   CCairoPaint       *ActiveSource();

public:
                     CCairoContext();
                    ~CCairoContext();

   //--- TARGET

   bool              SetTarget(CCairoSurface *surface);
   int               Width()  { return TargetWidth();  }
   int               Height() { return TargetHeight(); }

   //--- paint every pixel of the target, ignoring the clip. This is
   //--- how a frame begins.
   void              ClearAll(const uint argb = CAIRO_TRANSPARENT);

   //--- STATE

   bool              Save();
   bool              Restore();
   int               Depth() const { return m_depth; }
   void              ResetState();

   //--- TRANSFORM

   void              Translate(const double tx, const double ty);
   void              Scale(const double sx, const double sy);
   void              Rotate(const double degrees);
   void              Transform(const SCairoMatrix &m);
   void              SetMatrix(const SCairoMatrix &m);
   void              IdentityMatrix();
   void              GetMatrix(SCairoMatrix &out) const
     {               out.CopyFrom(m_state.ctm); }

   //--- user space -> device space, for a caller that needs to know
   //--- where something landed: a hit test, a tooltip anchor
   void              UserToDevice(const double x, const double y,
                                  double &dx, double &dy) const;
   bool              DeviceToUser(const double x, const double y,
                                  double &ux, double &uy) const;

   //--- SOURCE

   void              SetSourceColor(const uint argb);
   void              SetSource(CCairoPaint *paint);
   void              SetFillRule(const ENUM_CAIRO_FILLRULE rule)
     { m_state.rule = rule; }
   ENUM_CAIRO_FILLRULE FillRule() const { return m_state.rule; }

   //--- PATH BUILDING - every one of these writes through the current
   //--- transform, so the caller draws in its own coordinates.

   void              NewPath();
   void              MoveTo(const double x, const double y);
   void              LineTo(const double x, const double y);
   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);
   void              ArcTo(const double cx, const double cy, const double r,
                           const double deg_from, const double deg_to);
   void              ClosePath();

   void              Rect(const double x, const double y,
                          const double w, const double h);
   void              RoundRect(const double x, const double y,
                               const double w, const double h,
                               const double r);
   void              RoundRect(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              Circle(const double cx, const double cy, const double r);
   void              Ellipse(const double cx, const double cy,
                             const double rx, const double ry);
   void              Polygon(const double &xs[], const double &ys[],
                             const int n);
   void              Polyline(const double &xs[], const double &ys[],
                              const int n);

   //--- the path itself, for a caller that wants to measure or hit-test
   //--- what it just built
   CCairoPath        *Path() { return GetPointer(m_path); }
   SCairoRect        PathBounds() const { return m_path.Bounds(); }
   bool              InPath(const double device_x,
                            const double device_y) const;

   //--- DRAWING

   void              Fill();
   void              FillPreserve();

   //--- CLIPPING

   void              ClipRect(const double x, const double y,
                              const double w, const double h);
   void              Clip();
   void              ClipPreserve();
   void              ResetClip();
   bool              ClipIsEmpty() const { return m_clip.IsEmpty(); }
   CCairoClip        *ClipObject() { return GetPointer(m_clip); }

   //--- ACCESS TO THE COMPONENTS, for anything the context does not
   //--- wrap. The library is not trying to hide its own parts.

   CCairoRasterizer  *Rasterizer() { return GetPointer(m_ras); }
  };

The context owns the rasterizer, the path and the clip, so a frame of drawing stops allocating once the program has reached its deepest Save and its largest piece of geometry — the same bargain every part of this library has made. Not literally after the first frame: the clip stack below grows lazily, so a frame that nests one level deeper than any before it still pays for one object, once.

Note what is not in the state: the path. A path survives Save and Restore, because a caller that builds geometry and then wraps a Save around the filling of it should not find the geometry gone. Cairo makes the same choice, for the same reason.

Save and restore

Figure 4. What Save() copies aside and Restore() puts back.
//+-------------------------------------------------------------------+
//| Save the state, and a copy of the clip.                           |
//|                                                                   |
//| The clip copy is the expensive half, and it is only expensive     |
//| when a path clip is in force: a rectangular clip is four numbers. |
//+-------------------------------------------------------------------+
bool CCairoContext::Save()
  {
   if(m_depth >= CAIRO_MAX_STATE_DEPTH)
      return false;

   m_stack[m_depth] = m_state;

   if(m_clip_stack[m_depth] == NULL)
      m_clip_stack[m_depth] = new CCairoClip();

   if(m_clip_stack[m_depth] == NULL)
      return false;

   if(!m_clip_stack[m_depth].CopyFrom(GetPointer(m_clip)))
      return false;

   m_depth++;

   return true;
  }

Pushing the state is a single struct assignment, because SCairoState is plain values and one borrowed pointer and MQL5 copies all of those by member. The clip is the one piece of state too large to live in the struct — it may own a byte-per-pixel mask — so it is saved alongside, in a stack of its own.

The clip copies are allocated lazily and then kept. A context that nested four deep once holds four clip objects for the rest of its life. That is the trade this library makes everywhere: memory that has been needed once is assumed to be needed again, and the alternative is an allocation inside a drawing loop.

The depth is bounded at 32 so that a missing Restore() inside a loop fails loudly at a known depth instead of growing until the terminal runs out of memory.

Two asymmetries in this pair are worth stating. Save() checks whether the clip copy succeeds and increments the stack depth only after a successful copy. If the copy fails, an unused stack slot may contain a stale state, but the active state and depth remain unchanged. Restore() decrements the depth and restores the saved state, then checks whether the saved clip can be copied back. If CopyFrom() fails, Restore() sets the current clip to an empty region and returns false. The operation is therefore not fully atomic on failure: the non-clip state has already been restored, while the clip is placed in a safe, non-drawing state.

And one hazard that belongs to the source rather than to the stack. src_paint is a borrowed pointer; the context does not own the paint and does not copy it. Save copies the pointer into the stack, so a paint that is destroyed while a saved level still refers to it leaves a dangling pointer that Restore will hand back. Keep the paint alive while any saved state references it, or switch back to a solid color with SetSourceColor before the paint goes out of scope.

//+-------------------------------------------------------------------+
//| Put back the state and the clip saved by the matching Save().     |
//+-------------------------------------------------------------------+
bool CCairoContext::Restore()
  {
   if(m_depth <= 0)
      return false;

   m_depth--;

   m_state = m_stack[m_depth];

   bool ok = true;

   if(m_clip_stack[m_depth] != NULL)
      ok = m_clip.CopyFrom(m_clip_stack[m_depth]);

//--- a clip that could not be copied back must not leave the
//--- current one in force: allow nothing, and report it
   if(!ok)
      m_clip.SetEmpty();

//--- the solid paint holds a copy of what just changed under it
   if(m_state.use_color)
      m_solid.SetColor(m_state.src_color);

   return ok;
  }

The last three lines are the kind of thing a state machine always needs and never advertises. m_solid is a component holding a copy of a value that lives in the state; when the state changes under it, it has to be told.

The one place that knows where the pixels are

//+-------------------------------------------------------------------+
//| THE ONE PLACE THAT KNOWS WHICH BUFFER IS CURRENT.                 |
//+-------------------------------------------------------------------+
void CCairoContext::FillInto(CCairoPath &path, CCairoPaint *paint,
                             const ENUM_CAIRO_FILLRULE rule)
  {
   if(paint == NULL || m_surface == NULL)
      return;

   m_ras.Fill(path, paint, m_surface.m_px,
              m_surface.Width(), m_surface.Height(), rule,
              GetPointer(m_clip));
  }

MQL5 has no pointer-to-array type, so a context cannot hold "the pixels" as one thing — it has to ask the object that owns them. Confining that to a single private method is what keeps the target from leaking into every drawing operation, and later parts add a second kind of target without touching anything else in the file.

The source

//+-------------------------------------------------------------------+
//| The source paint, whichever kind it is.                           |
//+-------------------------------------------------------------------+
CCairoPaint *CCairoContext::ActiveSource()
  {
   if(!m_state.use_color)
      return m_state.src_paint;

   m_solid.SetColor(m_state.src_color);

   return GetPointer(m_solid);
  }

Two kinds of source, one return type. The flat color is poured into a member CCairoSolidPaint so that the rasterizer only ever sees a paint, exactly as Part 8 arranged it — and SetSource(NULL) is not an error, it means "go back to the color source".

The transform, forwarded

//+-------------------------------------------------------------------+
//| TRANSFORM                                                         |
//+-------------------------------------------------------------------+
void CCairoContext::Translate(const double tx, const double ty)
  {
   m_state.ctm.Translate(tx, ty);
  }

Five of these, all one line. They are worth having anyway, because ctx.Translate(x, y) is what the caller wants to write and m_state.ctm.Translate(x, y) is a private member.

The two conversions are the interesting half:

//+-------------------------------------------------------------------+
//| Where does this user-space point land on the screen?              |
//+-------------------------------------------------------------------+
void CCairoContext::UserToDevice(const double x, const double y,
                                 double &dx, double &dy) const
  {
   m_state.ctm.Apply(x, y, dx, dy);
  }

//+-------------------------------------------------------------------+
//| And back again - which is how a mouse position is turned into the |
//| coordinates a widget was drawn in.                                |
//+-------------------------------------------------------------------+
bool CCairoContext::DeviceToUser(const double x, const double y,
                                 double &ux, double &uy) const
  {
   SCairoMatrix inv;

   inv.CopyFrom(m_state.ctm);

   if(!inv.Invert())
      return false;

   inv.Apply(x, y, ux, uy);

   return true;
  }

DeviceToUser is how a mouse position becomes the coordinates a widget was drawn in. It returns bool because not every matrix can be inverted — scale by zero and the whole plane collapses onto a line, after which "where did this pixel come from" has no single answer. The caller finds out rather than receiving a number that means nothing.

Path building

//+-------------------------------------------------------------------+
//| Lift the pen and put it down somewhere else.                      |
//+-------------------------------------------------------------------+
void CCairoContext::MoveTo(const double x, const double y)
  {
   m_path.SetTransform(m_state.ctm);
   m_path.MoveTo(x, y);
  }

Every path verb looks like this: install the current transform, then forward. Installing it on every verb rather than once per path is deliberate. The transform can change between two LineTo calls, and the second one has to land where the caller's coordinates say it does at that moment — which is what makes a loop that translates between segments behave the way it reads.

SetTransform is cheap in the common case: a CopyFrom, an IsIdentity test and a ScaleFactor. The one place it is not free is a long path built under a transform, where ScaleFactor's two square roots are paid per verb. If that ever matters, the fix is to compare against the installed matrix first; it has not mattered yet, and an optimization with no measurement behind it is a guess.

Drawing, and clipping in user coordinates

//+-------------------------------------------------------------------+
//| DRAWING - fill the current path and keep it.                      |
//+-------------------------------------------------------------------+
void CCairoContext::FillPreserve()
  {
   FillInto(m_path, ActiveSource(), m_state.rule);
  }

//+-------------------------------------------------------------------+
//| Fill it and start a new one, which is what a caller wants nine    |
//| times out of ten.                                                 |
//+-------------------------------------------------------------------+
void CCairoContext::Fill()
  {
   FillPreserve();
   NewPath();
  }

The clip gets one piece of real logic:

//+-------------------------------------------------------------------+
//| Narrow the clip to a rectangle, in user coordinates.              |
//+-------------------------------------------------------------------+
void CCairoContext::ClipRect(const double x, const double y,
                             const double w, const double h)
  {
   const bool axis_aligned = (MathAbs(m_state.ctm.b) < 1e-9 &&
                              MathAbs(m_state.ctm.c) < 1e-9);

   if(axis_aligned)
     {
      double x0, y0, x1, y1;

      m_state.ctm.Apply(x,     y,     x0, y0);
      m_state.ctm.Apply(x + w, y + h, x1, y1);

      SCairoRect r = CairoRect(MathMin(x0, x1), MathMin(y0, y1),
                               MathAbs(x1 - x0), MathAbs(y1 - y0));

      m_clip.IntersectRect(r);
      return;
     }

//--- rotated or sheared: the rectangle is a quadrilateral, and a
//--- quadrilateral clip is a path clip. It is built in a path of its
//--- own rather than in m_path, so that a caller who was half-way
//--- through building geometry does not lose it.
   CCairoPath quad;

   quad.SetTransform(m_state.ctm);
   quad.AddRect(x, y, w, h);

   m_ras.ClipToPath(quad, m_clip, CAIRO_NONZERO);
  }

A rectangle in user coordinates stays axis-aligned in device coordinates only while b and c are zero — that is, while there is no rotation and no shear. Rotate it and it is still a rectangle in every geometric sense; what it has stopped being is a rectangle Part 9's clip can hold, because that clip stores four numbers and assumes the edges run along the axes. Rather than being silently wrong — clipping to the bounding box of the rotated rectangle, which is what a careless implementation does — the call routes itself through the path clip and pays for a mask.

Two things about that test deserve to be said plainly rather than discovered. The 1e-9 it compares against is an absolute tolerance, so it answers correctly for the coordinate ranges an interface works in and would need to be relative to the matrix scale before it could be trusted on arbitrarily large ones. And it inspects b and c only: a matrix with a or d at zero passes the test and collapses the rectangle to a line, which the path clip downstream handles as an empty region rather than as an error.

The common case still costs nothing: two Apply calls and an intersection of four doubles.

The scratch path is a local CCairoPath rather than the context's own, because the caller may have been half-way through building geometry when it asked for a clip, and losing it would be a surprise.


The demo

Demo10_Context.mq5 is seven panels, and every one of them is drawing code that could not have been written before today.

Figure 5. Seven panels, one chart object, on a live chart.

Panel A calls one function four times:

//+-------------------------------------------------------------------+
//| THE WHOLE POINT OF PANEL A.                                       |
//+-------------------------------------------------------------------+
void Arrow(const uint argb)
  {
   g_ctx.MoveTo(0.0, -5.0);
   g_ctx.LineTo(40.0, -5.0);
   g_ctx.LineTo(40.0, -14.0);
   g_ctx.LineTo(60.0,  0.0);
   g_ctx.LineTo(40.0,  14.0);
   g_ctx.LineTo(40.0,  5.0);
   g_ctx.LineTo(0.0,  5.0);
   g_ctx.ClosePath();

   g_ctx.SetSourceColor(argb);
   g_ctx.Fill();
  }

Arrow takes no position, no angle and no size. All three are in the transform by the time it is called, and the same seven verbs land in five different places. Each call is wrapped in Save/Restore, without which the second arrow would start where the first one's transform left off.

Panel B nests four levels deep. Branch() draws a star, then recurses twice with a rotation, a translation and a scale between — and the panel prints the save depth before and after:

//--- the stack is exactly where it was. If this ever prints two
//--- different numbers, some helper forgot a Restore().
   PrintFormat("Cairo5 Part 10, panel B: depth %d before, %d after",
               before, g_ctx.Depth());

If those two numbers ever differ, something between them did not put the stack back: a helper that forgot its Restore() is much the likeliest cause, but an early return past one, a Save() refused at the depth limit, or a deliberate change of state would print the same mismatch. The value of the line is not that it names the bug — it is that an invariant nobody checks is an invariant that quietly stops holding.

Panel C draws the same badge at 1x, 2x and 3.5x. The corner radius, the inset border and the star inside all scale together, because they are all written in badge coordinates — and the rounded corners get more segments rather than bigger facets, which is UserTolerance() doing its job.

Panel D draws nine upright bars and rotates the group. The bar loop writes Rect(x, -h, 18, h) and knows nothing about the rotation at all.

Panel E is the point of the whole part: DrawCard() draws a card at the origin, every time, and the caller decides where the origin is. The same function then draws the card once more rotated and scaled, which it survives because nothing in it assumed an upright pixel grid.

Panel F calls ClipRect twice with identical arguments — once unrotated, once under a rotation — and the stripes are cut along a slanted edge in the second case. An amber line drawn across the panel afterwards shows the clip was released by Restore().

Figure 6. The same panel, cropped close enough to read.

The whole panel is still one chart object. The captions are OBJ_LABEL annotations for the article and switch off with an input.


Project structure

The engine is nine headers now, and the demo is the only .mq5:

MQL5/
├── Include/
│   └── CairoG2D/
│       ├── Color.mqh          // the ARGB color type and blending
│       ├── Config.mqh         // CairoAaSamples, CairoFlattenTolerance
│       ├── Surface.mqh        // pixel buffer bound to one chart object
│       ├── Clip.mqh           // CCairoClip — the rectangle, the mask, the coverage
│       ├── Path.mqh           // the path and the edges, bounds, contains
│       ├── Paint.mqh          // the color source, solid and gradient
│       ├── Raster.mqh         // the coverage fill and the fill rule
│       ├── Context.mqh        // CCairoContext — the object an application talks to
│       ├── Matrix.mqh         // SCairoMatrix — the six-number affine transform
│       └── DemoTheme.mqh      // the demos' shared palette - NOT library code
└── Experts/
    └── CairoG2D/
        └── Article 10/
            └── Demo10_Context.mq5   // seven panels: transforms, nesting, scale, rotation, a self-placing widget, clipping, the round trip

The include order inside Context.mqh lists Matrix.mqh before Path.mqh, and it is worth saying that this is a reading convenience rather than a requirement: every header in the library carries its own guard and includes what it needs, Path.mqh includes Matrix.mqh itself, and the file would compile in any order. The list is written bottom-up so that a reader meets each type before the one built on it.

# File Directory  Contents
1 Color.mqh MQL5/Include/CairoG2D ARGB color, CairoLerp, compositing
2 Config.mqh MQL5/Include/CairoG2D the two quality dials
3 Surface.mqh MQL5/Include/CairoG2D pixel buffer to chart bitmap
4 Matrix.mqh MQL5/Include/CairoG2D SCairoMatrix — the six-number affine transform
5 Path.mqh MQL5/Include/CairoG2D the geometry layer + the current transform
6 Paint.mqh MQL5/Include/CairoG2D CCairoPaint, the gradients, CCairoFillStyle
7 Clip.mqh MQL5/Include/CairoG2D CCairoClip — the rectangle, the mask, the coverage
8 Raster.mqh MQL5/Include/CairoG2D the scanline fill, unchanged today
9 Context.mqh MQL5/Include/CairoG2D CCairoContext — the object an application talks to
10 DemoTheme.mqh MQL5/Include/CairoG2D the shared light palette — not library code
11 Demo10_Context.mq5 MQL5/Experts/CairoG2D/Article 10/ seven panels: transforms, nesting, scale, rotation, a self-placing widget, clipping, the round trip
12  Cairo Style Library - Part 10.zip   archive containing all the attached files and their paths relative to the terminal's root folder.


The caller stops doing the bookkeeping

The button that opened this article is now this:

ctx.Save();
ctx.Translate(x, y);
ctx.RoundRect(0, 0, w, h, 6);
ctx.SetSourceColor(0xFF1F6FEB);
ctx.Fill();
ctx.Restore();

No buffer, no width, no height, no clip object, no x + on every coordinate. The geometry is written where the widget lives, which is at its own origin, and the placement is one line that the widget never sees.

Underneath, the two new files are small. Matrix.mqh is six numbers and the arithmetic that composes them, with one genuinely interesting function in it — ScaleFactor, where the obvious answer is a lower bound and the right answer is a quadratic. Context.mqh is a struct, a stack, and a lot of one-line forwarding, with exactly two pieces of real logic: the clip that notices when a rectangle is not a rectangle, and the private method that knows where the pixels are.

Path.mqh gained five members, five public methods, one if in AddPoint, and a divisor in the two places that ask how finely to subdivide. Nothing else in the library changed at all. Be precise about what that buys: CCairoRasterizer, CCairoClip, the paints and CCairoSurface never had to learn what a matrix is, because the vertices reach them already in device space. The transform is not invisible everywhere — CCairoContext knows about it in every verb it forwards and in ClipRect, and the path now stores device coordinates while its pen holds user ones. What the single insertion point bought is that the knowledge stops at the context and the path, instead of being spread across six files.

What is still missing is visible in the demo's own helper code. Every border in Demo10_Context.mq5 is drawn as four thin rectangles, because the library can fill an outline and cannot yet stroke one — no line width, no caps, no joins, no dashes. That is the next part, and the context already has the one thing a stroker needs from it: ScaleFactor(), so that a line width written in user units can become a width in pixels.


The project is supported on MQL5 Algo Forge. Each part of this series has its own release, frozen at exactly the code that part explains, so whichever article you are reading, its release is the one to download.

Part 10 is here: https://forge.mql5.io/SandroBegashvil/CairoG2D/releases/tag/part-10

Attached files |
Color.mqh (11.21 KB)
Config.mqh (5.34 KB)
Clip.mqh (24.19 KB)
Matrix.mqh (18.2 KB)
Paint.mqh (31.28 KB)
Path.mqh (88.52 KB)
Raster.mqh (29.39 KB)
Surface.mqh (12.96 KB)
Context.mqh (32.35 KB)
DemoTheme.mqh (8.77 KB)
Demo10_Context.mq5 (20.59 KB)
Does the Terminal Run the Model You Trained? ONNX Contract and Golden-File Checks in MQL5 Does the Terminal Run the Model You Trained? ONNX Contract and Golden-File Checks in MQL5
An EA can detect a wrong ONNX model in OnInit, before its first prediction, instead of failing or returning other probabilities in OnTick. COnnxContract checks the model's signature, features, class labels, and SHA-256 hash against a contract file. COnnxParity compares the terminal's probabilities with onnxruntime on a golden file of reference rows, and a Python tool builds both files from your data. The tool also audits the EA's prediction log, because a golden pass covers only its own rows.
Change Point Detection for Financial Time Series in MQL5 Change Point Detection for Financial Time Series in MQL5
Financial markets can shift between regimes, so detecting when the statistical behavior of returns changes is valuable for analysis. An MQL5 change point detector segments historical returns into periods with different mean and volatility using optimal partitioning with PELT pruning and a BIC-style default penalty. A sensitivity scan tests robustness by showing which detected breaks persist as settings vary.
Neural Networks in Trading: Mesh Approximation of Event Streams as a Tool for Analyzing Price Patterns (EEMFlow) Neural Networks in Trading: Mesh Approximation of Event Streams as a Tool for Analyzing Price Patterns (EEMFlow)
The article provides an overview of the architecture of the EEMFlow framework, which is designed to work with event streams. Particular attention is paid to adaptive and multi-level modules, which enable flexible handling of both global and local changes. The framework's architecture preserves key information, minimizes the impact of noise, and efficiently generates features for further analysis, making EEMFlow a promising tool for forecasting financial market dynamics.
Building a Volume Profile Aggregator from Tick Data in MQL5 Building a Volume Profile Aggregator from Tick Data in MQL5
The article presents an MQL5 volume profile built with O(1)-per-tick binning, replacing O(n×m) nested comparisons by direct index arithmetic on a preallocated, tick-size-aligned bin grid. An EA-driven pipeline resolves the session, loads ticks with retries and pre-sizing, aggregates, computes POC/VA, and renders bars in the chart's right margin. A test script verifies arithmetic on controlled datasets.