% tkz-grapheur-lua.tex
% Copyright 2026 Cédric Pierquet
% Released under the LaTeX Project Public License v1.3c or later, see http://www.latex-project.org/lppl.txt
% macros base [lua] de tkz-grapheur

%====COURBES IMPLICITES
\newlength\pflthickimpl
\tikzset{pflcourbeimplicit/.style={only marks,mark=*}}

\defKV[GraphiqueTikzImplicite]{%
  CoeffPasAuto=\def\pflcoeffpasimpl{#1},step stretch=\def\pflcoeffpasimpl{#1},%
  Pas=\def\pflpasimpl{#1},step=\def\pflpasimpl{#1},%
  Couleur=\def\pflcouleurbimpl{#1},color=\def\pflcouleurbimpl{#1},%
  Epaisseur=\setlength\pflthickimpl{#1},thick=\setlength\pflthickimpl{#1},%
  Precision=\def\pflprecisiimpl{#1},prec=\def\pflprecisiimpl{#1},%
  Tolerance=\def\pfltoleranceimplic{#1},tolerance=\def\pfltoleranceimplic{#1},%
  xa=\def\pflimplxa{#1},%
  xb=\def\pflimplxb{#1},%
  ya=\def\pflimplya{#1},%
  yb=\def\pflimplyb{#1}%
}
\setKVdefault[GraphiqueTikzImplicite]{%
  CoeffPasAuto=1,step stretch=1,%
  Pas=auto,step=auto,%
  Couleur=black,color=black,%
  Epaisseur=1.05pt,thick=1.05pt,%
  Precision=8,precision=8,%
  Tolerance=1e-10,tolerance=1e-10,%
  lua=true,%
  xa={},xb={},ya={},yb={}%
}

\NewDocumentCommand\TracerCourbeImplicite{ O{} m }{%with jfbu part of code for xint version !
  % #1 = clés (Pas, Couleur, etc)
  % #2 = expression f(x,y) (= 0 implicite)
  \restoreKV[GraphiqueTikzImplicite]%
  \setKV[GraphiqueTikzImplicite]{#1}%
  % résolution des bornes (défaut = fenêtre)
  \IfStrEq{\pflimplxa}{}{\xdef\pflimplxa{\pflxmin}}{}%
  \IfStrEq{\pflimplxb}{}{\xdef\pflimplxb{\pflxmax}}{}%
  \IfStrEq{\pflimplya}{}{\xdef\pflimplya{\pflymin}}{}%
  \IfStrEq{\pflimplyb}{}{\xdef\pflimplyb{\pflymax}}{}%
  \ifboolKV[GraphiqueTikzImplicite]{lua}%
  {%
    \ifluatex
    \IfStrEq{\pflpasimpl}{auto}%
    {%
      \pgfmathsetmacro{\pfl@pasx}{\pgfmath@tonumber{\pflthickimpl} * 0.5 * (\pflcoeffpasimpl) / \pgfmath@tonumber{\pgf@xx}}%
      \pgfmathsetmacro{\pfl@pasy}{\pgfmath@tonumber{\pflthickimpl} * 0.5 * (\pflcoeffpasimpl) / \pgfmath@tonumber{\pgf@yy}}%
    }%
    {%
      \def\pfl@pasx{\pflpasimpl}%
      \def\pfl@pasy{\pflpasimpl}%
    }%
    \begin{scope}
        \clip (\pflxmin,\pflymin) rectangle (\pflxmax,\pflymax);
        \directlua{pfl.marching_squares("\luaescapestring{#2}",\pflimplxa,\pflimplxb,\pflimplya,\pflimplyb,\pfl@pasx,\pfl@pasy,\pfltoleranceimplic,"\luaescapestring{\pflcouleurbimpl}","\the\pflthickimpl")}%
    \end{scope}%
    \else
      \PackageWarning{tkz-grapheur}{.: LuaLaTeX not detected, \TracerCourbeImplicite\space with [lua=false] key only available :.}
    \fi
  }%
  {%
  % open a scope limiting group
  \begingroup
  % configure xint to work with less digits
  \xintSetDigits*{\pflprecisiimpl}%
  % définition fonction xint à 2 variables
  \xintdeffloatfunc pflimplicitefct(x,y) = #2 ;%
  %calcul auto du pas
  \IfStrEq{\pflpasimpl}{auto}%
  {%
    \pgfmathsetmacro{\pflpasximplcalc}{\pgfmath@tonumber{\pflthickimpl} * \pflcoeffpasimpl * 1.414 / \pgfmath@tonumber{\pgf@xx}}%
    \pgfmathsetmacro{\pflpasyimplcalc}{\pgfmath@tonumber{\pflthickimpl} * \pflcoeffpasimpl * 1.414 / \pgfmath@tonumber{\pgf@yy}}%
  }%
  {%
    \def\pflpasximplcalc{\pflpasimpl}%
    \def\pflpasyimplcalc{\pflpasimpl}%
  }%
  \def\tmplisteptsh{}%
  \def\tmplisteptsv{}%
  \def\tmplisteptsp{}%
  % double boucle marching squares
  \edef\tmpxcoords{\xintfloateval{\pflxmin..[\pflpasximplcalc]..\pflxmax}}%
  \edef\tmpycoords{\xintfloateval{\pflymin..[\pflpasyimplcalc]..\pflymax}}%
  % attention ensemble de définition ??...
  \def\tmpj{0}%
  % precompute values of function on left vertical border
  \xintFor ##2 in {\tmpycoords}\do{%
    \expandafter\edef\csname tmp_value_\tmpj\endcsname{\xintfloateval{pflimplicitefct(\pflxmin,##2)}}%
    \edef\tmpj{\the\numexpr\tmpj+1}%
    \xintifForLast{% one more
      \expandafter\edef\csname tmp_value_\tmpj\endcsname{\xintfloateval{pflimplicitefct(\pflxmin,##2+\pflpasyimplcalc)}}%
    }{}%
  }%
  \xintFor ##1 in {\tmpxcoords}\do{%
    \edef\tmpC{\csname tmp_value_0\endcsname}%
    \def\tmpj{0}%
    \xintFor ##2 in {\tmpycoords}\do{%
      % évaluer les 3 coins et préparer en même temps la prochaine colonne pré-calculée
      \let\tmpA\tmpC
      \edef\tmpB{\xintfloateval{pflimplicitefct(##1+\pflpasximplcalc,##2)}}%
      % mettre à jour pour la prochaine fois, oui c'est rusé
      \expandafter\let\csname tmp_value_\tmpj\endcsname\tmpB
      \edef\tmpj{\the\numexpr\tmpj+1}%
      % là on est encore avec la colonne en cours, déjà calculée
      \edef\tmpC{\csname tmp_value_\tmpj\endcsname}%
      % changement de signe horizontal
      \xintifboolexpr{sgn(\tmpA)*sgn(\tmpB) < 0}%
        {%
          \xdef\tmplisteptsh{\tmplisteptsh (\xintfloateval{##1-(\tmpA)*\pflpasximplcalc/(\tmpB-\tmpA)},##2)}%
        }{}%
      % changement de signe vertical
      \xintifboolexpr{sgn(\tmpA)*sgn(\tmpC) < 0}%
        {%
          \xdef\tmplisteptsv{\tmplisteptsv (##1,\xintfloateval{##2-(\tmpA)*\pflpasyimplcalc/(\tmpC-\tmpA)})}%
        }{}%
      % si pas de changement de signe détecté → test zéro exact
      \xintifboolexpr{(sgn(\tmpA)*sgn(\tmpB) >= 0) && (sgn(\tmpA)*sgn(\tmpC) >= 0) && (abs(\tmpA) < \pfltoleranceimplic)}%
        {%
          \xdef\tmplisteptsp{\tmplisteptsp (##1,##2)}%
        }{}%
      % le dernier coup il faut en calculer un de plus
      \xintifForLast{%
        \expandafter\edef\csname tmp_value_\tmpj\endcsname{\xintfloateval{pflimplicitefct(##1+\pflpasximplcalc,##2+\pflpasyimplcalc)}}%
      }{}%
    }%
  }%
  \begin{scope}
    \clip (\pflxmin,\pflymin) rectangle (\pflxmax,\pflymax) ;
    \IfEq{\tmplisteptsp}{}{}%
      {%
        \draw[color=\pflcouleurbimpl] plot[pflcourbeimplicit] coordinates {\tmplisteptsp} ;%
      }%
    \IfEq{\tmplisteptsh}{}{}%
      {%
        \draw[color=\pflcouleurbimpl] plot[pflcourbeimplicit] coordinates {\tmplisteptsh} ;%
      }%
    \IfEq{\tmplisteptsv}{}{}%
      {%
        \draw[color=\pflcouleurbimpl] plot[pflcourbeimplicit] coordinates {\tmplisteptsv} ;%
      }%
  \end{scope}%
  \endgroup%
  }%
}
\NewCommandCopy\PlotImplicitCurve\TracerCourbeImplicite

\defKV[GraphiqueTikzNiveau]{%
  Couleur=\def\pflniveaucouleur{#1},%
  Couleurs=\def\pflniveaucouleurs{#1},%
  Pas=\def\pflniveaupas{#1},%
  Epaisseur=\setlength\pflthickimpl{#1}%
}
\setKVdefault[GraphiqueTikzNiveau]{%
  Couleur=black,%
  Couleurs={},%
  Pas=auto,%
  Epaisseur=1.05pt%
}

% \NewDocumentCommand\TracerLignesNiveau{ O{} m m }{%
  % % #1 = clés
  % % #2 = expression f(x,y)
  % \restoreKV[GraphiqueTikzNiveau]%
  % \setKV[GraphiqueTikzNiveau]{#1}%
  % % Boucle sur les valeurs
  % \foreach \elt [count=\i from 1] in {#3}{%
    % \IfStrEq{\pflniveaucouleurs}{}%
      % {%
        % \edef\pflcoulcourante{\pflniveaucouleur}%
      % }%
      % {%
        % \setsepchar{,}%
        % \readlist*\pfllistecouleurs{\pflniveaucouleurs}%
        % %Couleur cyclique si moins de couleurs que de niveaux
        % \pgfmathtruncatemacro{\pflcolidx}{mod(\i-1,\pfllistecouleurslen)+1}%
        % \itemtomacro\pfllistecouleurs[\pflcolidx]{\pflcoulcourante}%
      % }%
    % \TracerCourbeImplicite[lua,Couleur=\pflcoulcourante,Pas=\pflniveaupas,Epaisseur=\pflthickimpl]{#2 - (\elt)}%
  % }
% }
% \NewCommandCopy\PlotLevelCurves\TracerLignesNiveau

\NewDocumentCommand\TracerLignesNiveau{ O{} m m }{%
  % #1 = clés
  % #2 = expression f(x,y)
  % #3 = liste des valeurs k
  \restoreKV[GraphiqueTikzNiveau]%
  \setKV[GraphiqueTikzNiveau]{#1}%
  % calcul du pas
  \IfStrEq{\pflniveaupas}{auto}{%
    \pgfmathsetmacro{\pfl@pasx}{\pgfmath@tonumber{\pflthickimpl}*0.5/\pgfmath@tonumber{\pgf@xx}}%
    \pgfmathsetmacro{\pfl@pasy}{\pgfmath@tonumber{\pflthickimpl}*0.5/\pgfmath@tonumber{\pgf@yy}}%
  }{%
    \pgfmathsetmacro{\pfl@pasx}{\pflniveaupas}%
    \pgfmathsetmacro{\pfl@pasy}{\pflniveaupas}%
  }%
  % Appel Lua unique → grille calculée une seule fois !
  \directlua{
    pfl._niveau_pts = pfl.level_curves(
      "\luaescapestring{#2}",
      "\luaescapestring{#3}",
      \pflxmin, \pflxmax, \pflymin, \pflymax,
      \pfl@pasx, \pfl@pasy
    )
  }%
  % Boucle tracé uniquement
  \foreach \elt [count=\i from 1] in {#3}{%
    \IfStrEq{\pflniveaucouleurs}{}%
      {\edef\pflcoulcourante{\pflniveaucouleur}}%
      {%
        \setsepchar{,}%
        \readlist*\pfllistecouleurs{\pflniveaucouleurs}%
        \itemcycltomacro\pfllistecouleurs[\i]{\pflcoulcourante}%
		%\pgfmathtruncatemacro{\pflcolidx}{mod(\i-1,\pfllistecouleurslen)+1}%
        %\itemtomacro\pfllistecouleurs[\pflcolidx]{\pflcoulcourante}%
      }%
    \begin{scope}
      \clip (\pflxmin,\pflymin) rectangle (\pflxmax,\pflymax);
      \directlua{pfl.draw_level(\i,"\luaescapestring{\pflcoulcourante}","\the\pflthickimpl")}%
    \end{scope}%
  }%
}%
\NewCommandCopy\PlotLevelCurves\TracerLignesNiveau

\ifluatex
\RequirePackage{luacode}
% \begin{luacode*}
% pfl = pfl or {}

% function pfl.expr_to_func(expr_str)
    % -- Traduction expression LaTeX → Lua
	% -- texio.write_nl("=== expr reçue : " .. expr_str)
    % local e = expr_str
    % e = e:gsub("%^",    "^")
    % e = e:gsub("sin%(", "math.sin(")
    % e = e:gsub("cos%(", "math.cos(")
    % e = e:gsub("tan%(", "math.tan(")
    % e = e:gsub("exp%(", "math.exp(")
    % e = e:gsub("sqrt%(","math.sqrt(")
    % e = e:gsub("log%(", "math.log(")
    % e = e:gsub("abs%(", "math.abs(")
    % e = e:gsub("pi",    tostring(math.pi))
    % e = e:gsub("%*%*",  "^")
    % -- Compilation dynamique
	% -- texio.write_nl("=== expr traduite : " .. e)
    % local fstr = "local x,y = ...; return " .. e
	% -- texio.write_nl("=== fstr : " .. fstr)
    % local f, err = load(fstr)
    % if not f then
        % texio.write_nl("! pfl.expr_to_func : " .. tostring(err))
        % return nil
    % end
    % return f
% end

% function pfl.marching_squares(expr_str, xmin, xmax, ymin, ymax, pasx, pasy, eps)
    % eps = eps or 1e-12
    % local f = pfl.expr_to_func(expr_str)
    % if not f then return "" end

    % local ni = math.floor((xmax - xmin) / pasx)
    % local nj = math.floor((ymax - ymin) / pasy)

    % -- Phase 1 : tableau complet F[i][j]
    % local F = {}
    % local xs = {}
    % local ys = {}
    % for i = 0, ni do
        % xs[i] = xmin + i * pasx
        % F[i]  = {}
    % end
    % for j = 0, nj do
        % ys[j] = ymin + j * pasy
    % end
    % for i = 0, ni do
        % for j = 0, nj do
            % F[i][j] = f(xs[i], ys[j])
        % end
    % end

    % -- Phase 2 : marching squares
    % local pts = {}
    % for i = 0, ni - 1 do
        % for j = 0, nj - 1 do
            % local A = F[i  ][j  ]
            % local B = F[i+1][j  ]
            % local C = F[i  ][j+1]
            % local D = F[i+1][j+1]
            % local xi  = xs[i]
            % local xip = xs[i+1]
            % local yj  = ys[j]
            % local yjp = ys[j+1]
            % -- Arête A→B
            % if A * B < 0 then
                % pts[#pts+1] = string.format("(%.3f,%.3g)",
                    % xi - A * pasx / (B - A), yj)
            % end
            % -- Arête A→C
            % if A * C < 0 then
                % pts[#pts+1] = string.format("(%.3f,%.3g)",
                    % xi, yj - A * pasy / (C - A))
            % end
            % -- Arête C→D
            % -- if C * D < 0 then
            % --    pts[#pts+1] = string.format("(%.6f,%.6g)",
            % --        xi - C * pasx / (D - C), yjp)
            % -- end
            % -- Arête B→D
            % -- if B * D < 0 then
            % --     pts[#pts+1] = string.format("(%.6f,%.6g)",
            % --         xip, yj - B * pasy / (D - B))
            % -- end
            % -- Zéro exact
            % if A*B >= 0 and A*C >= 0 and math.abs(A) < eps then
                % pts[#pts+1] = string.format("(%.6f,%.6g)", xi, yj)
            % end
        % end
    % end
    % local result = table.concat(pts, " ")
    % if result == "" then
        % return string.format("(%.6f,%.6f)", xmin - 1, ymin - 1)
    % end
    % return result
% end
% \end{luacode*}
\begin{luacode*}
pfl = pfl or {}

------------------------------------------------------------------------
-- Translate a LaTeX-style expression string to a Lua function f(x,y)
------------------------------------------------------------------------
function pfl.expr_to_func(expr_str)
    local e = expr_str
    e = e:gsub("%^",    "^")
    e = e:gsub("sin%(", "math.sin(")
    e = e:gsub("cos%(", "math.cos(")
    e = e:gsub("tan%(", "math.tan(")
    e = e:gsub("exp%(", "math.exp(")
    e = e:gsub("sqrt%(","math.sqrt(")
    e = e:gsub("log%(", "math.log(")
    e = e:gsub("ln%(",  "math.log(")
    e = e:gsub("abs%(", "math.abs(")
    e = e:gsub("pi",    tostring(math.pi))
    e = e:gsub("%*%*",  "^")
    local fstr = "local x,y = ...; return " .. e
    local f, err = load(fstr)
    if not f then
        texio.write_nl("! pfl.expr_to_func : " .. tostring(err))
        return nil
    end
    return f
end

------------------------------------------------------------------------
-- Safe evaluation: returns math.huge for NaN, Inf or errors
------------------------------------------------------------------------
local function safe_eval(f, x, y)
    local ok, v = pcall(f, x, y)
    if not ok then return math.huge end
    if v ~= v then return math.huge end           -- NaN test
    if math.abs(v) == math.huge then return math.huge end
    return v
end

------------------------------------------------------------------------
-- Format a list of {x,y} pairs as a TikZ path string  "(x1,y1) -- ..."
------------------------------------------------------------------------
local function path_str(pts)
    local s = {}
    for _, p in ipairs(pts) do
        s[#s+1] = string.format("(%.4f,%.4f)", p[1], p[2])
    end
    return table.concat(s, " -- ")
end

------------------------------------------------------------------------
-- Core marching-squares engine
-- Returns a list of polylines; each polyline is a list of {x,y} pairs.
--
-- Improvements over the previous 2-edge version:
--   * All 4 edges of every cell are checked (not just bottom and left).
--   * Each shared edge is computed exactly once via a cache.
--   * Discontinuities / poles are rejected with a midpoint check:
--     if safe_eval at the edge midpoint returns math.huge (Inf/NaN),
--     or if |f(mid)| ≫ max(|f(A)|, |f(B)|), the crossing is spurious.
--   * Saddle cells (4 crossings) are disambiguated by the sign of f at
--     the cell centre.
--   * Segments are chained into connected polylines via a walk that
--     follows shared edge-keys; open ends are visited first, then loops.
------------------------------------------------------------------------
local function ms_core(f, xmin, xmax, ymin, ymax, pasx, pasy)

    local ni = math.floor((xmax - xmin) / pasx)
    local nj = math.floor((ymax - ymin) / pasy)

    -- Phase 1 — evaluate F on every grid node -------------------------
    local F  = {}
    local xs = {}
    local ys = {}
    for i = 0, ni do xs[i] = xmin + i * pasx;  F[i] = {} end
    for j = 0, nj do ys[j] = ymin + j * pasy end
    for i = 0, ni do
        for j = 0, nj do
            F[i][j] = safe_eval(f, xs[i], ys[j])
        end
    end

    -- Phase 2 — edge-crossing cache ------------------------------------
    -- hc[i][j] : crossing on horizontal edge (i,j)→(i+1,j), or nil
    -- vc[i][j] : crossing on vertical edge   (i,j)→(i,j+1), or nil
    --
    -- Discontinuity check: a pole/asymptote makes f blow up between two
    -- grid points that have opposite signs.  We detect this by evaluating
    -- the midpoint of the candidate edge:
    --   • if safe_eval returns math.huge → clear pole, reject.
    --   • monotonicity test: vm (at midpoint) must lie between v1 and v2.
    --     For a genuine zero crossing the function is roughly monotone, so
    --     (vm-v1)*(v2-vm) >= 0.  A pole/asymptote makes the function jump
    --     so vm ends up outside [v1,v2] → (vm-v1)*(v2-vm) < 0 → reject.

    local function edge_cross(v1, v2, x1, y1, x2, y2)
        if v1 == math.huge or v2 == math.huge then return nil end
        if v1 * v2 >= 0 then return nil end
        local xm = (x1 + x2) * 0.5
        local ym = (y1 + y2) * 0.5
        local vm = safe_eval(f, xm, ym)
        if vm == math.huge then return nil end
        -- reject if vm is not between v1 and v2 (non-monotone = discontinuity)
        if (vm - v1) * (v2 - vm) < 0 then return nil end
        local t = v1 / (v1 - v2)
        return { x1 + t * (x2 - x1),  y1 + t * (y2 - y1) }
    end

    local hc = {}
    local vc = {}
    for i = 0, ni do hc[i] = {}; vc[i] = {} end

    for i = 0, ni - 1 do
        for j = 0, nj do
            hc[i][j] = edge_cross(F[i][j], F[i+1][j],
                                   xs[i], ys[j], xs[i+1], ys[j])
        end
    end
    for i = 0, ni do
        for j = 0, nj - 1 do
            vc[i][j] = edge_cross(F[i][j], F[i][j+1],
                                   xs[i], ys[j], xs[i], ys[j+1])
        end
    end

    -- Phase 3 — build one or two segments per cell --------------------
    -- Each segment: { p1, p2, ek1, ek2 }
    --   p1, p2  : {x,y} tables (shared references from the edge cache)
    --   ek1,ek2 : string keys identifying the edge each endpoint is on
    -- edge_segs[ek] = list of segment indices that share that edge point.

    local segments  = {}
    local edge_segs = {}

    local function ek_h(i, j)  return "h:" .. i .. ":" .. j  end
    local function ek_v(i, j)  return "v:" .. i .. ":" .. j  end

    local function add_seg(p1, p2, ek1, ek2)
        if not p1 or not p2 then return end
        local idx = #segments + 1
        segments[idx] = { p1, p2, ek1, ek2 }
        edge_segs[ek1] = edge_segs[ek1] or {}
        table.insert(edge_segs[ek1], idx)
        edge_segs[ek2] = edge_segs[ek2] or {}
        table.insert(edge_segs[ek2], idx)
    end

    for i = 0, ni - 1 do
        for j = 0, nj - 1 do
            -- crossings on the four edges of cell (i,j)
            --   pb = bottom SW→SE,  pt = top NW→NE
            --   pl = left  SW→NW,   pr = right SE→NE
            local pb = hc[i][j];      local pt = hc[i][j+1]
            local pl = vc[i][j];      local pr = vc[i+1][j]

            local ekb = ek_h(i,   j  )
            local ekt = ek_h(i,   j+1)
            local ekl = ek_v(i,   j  )
            local ekr = ek_v(i+1, j  )

            -- collect present crossings in a fixed order
            local cross = {}
            if pb then cross[#cross+1] = { pb, ekb } end   -- [1] bottom
            if pt then cross[#cross+1] = { pt, ekt } end   -- [2] top
            if pl then cross[#cross+1] = { pl, ekl } end   -- [3] left
            if pr then cross[#cross+1] = { pr, ekr } end   -- [4] right

            local n = #cross
            if n == 2 then
                add_seg(cross[1][1], cross[2][1], cross[1][2], cross[2][2])

            elseif n == 4 then
                -- Saddle disambiguation: sign of f at the cell centre
                -- decides which pairs of crossings form connected arcs.
                --
                -- Convention (cross order: bottom, top, left, right):
                --   centre same sign as SW corner A → pair bottom↔left,  top↔right
                --   centre opposite to SW corner A  → pair bottom↔right, top↔left
                local cx = (xs[i] + xs[i+1]) * 0.5
                local cy = (ys[j] + ys[j+1]) * 0.5
                local fc = safe_eval(f, cx, cy)
                local fA = F[i][j]
                if fc ~= math.huge and fA ~= math.huge and fc * fA >= 0 then
                    add_seg(cross[1][1], cross[3][1], cross[1][2], cross[3][2])
                    add_seg(cross[2][1], cross[4][1], cross[2][2], cross[4][2])
                else
                    add_seg(cross[1][1], cross[4][1], cross[1][2], cross[4][2])
                    add_seg(cross[2][1], cross[3][1], cross[2][2], cross[3][2])
                end
            end
            -- n == 0 : empty cell, nothing to do
            -- n == 1,3 : tangency / rounding artefact, skip
        end
    end

    -- Phase 4 — link segments into connected polylines ----------------
    -- Two segments that share an edge-key have geometrically adjacent
    -- endpoints (same point from the cache).  We walk from one segment
    -- to the next by following these shared keys.
    --
    -- Strategy: visit free endpoints first (edge-keys used by exactly
    -- one segment, i.e. boundary or discontinuity ends), then handle
    -- any remaining closed loops.

    local visited   = {}
    local polylines = {}

    local function next_seg(ek, cur_idx)
        for _, s in ipairs(edge_segs[ek] or {}) do
            if s ~= cur_idx then return s end
        end
    end

    local function walk(start_idx, entry_ek)
        if visited[start_idx] then return end
        local path    = {}
        local cur_idx = start_idx
        local cur_in  = entry_ek
        visited[cur_idx] = true

        -- entry point (the endpoint on cur_in of the starting segment)
        local seg = segments[cur_idx]
        path[1] = (seg[3] == cur_in) and seg[1] or seg[2]

        while true do
            seg = segments[cur_idx]
            local exit_pt, exit_ek
            if seg[3] == cur_in then
                exit_pt = seg[2];  exit_ek = seg[4]
            else
                exit_pt = seg[1];  exit_ek = seg[3]
            end
            path[#path+1] = exit_pt

            local nxt = next_seg(exit_ek, cur_idx)
            if not nxt or visited[nxt] then break end
            visited[nxt] = true
            cur_idx = nxt
            cur_in  = exit_ek
            -- exit_pt is the shared edge point: it was already appended,
            -- so the next iteration only appends the far end of nxt.
        end

        if #path >= 2 then
            polylines[#polylines+1] = path
        end
    end

    -- free endpoints first
    for ek, segs in pairs(edge_segs) do
        if #segs == 1 then walk(segs[1], ek) end
    end
    -- closed loops
    for idx = 1, #segments do
        if not visited[idx] then walk(idx, segments[idx][3]) end
    end

    return polylines
end

------------------------------------------------------------------------
-- Draw implicit curve F(x,y)=0
-- Called via \directlua inside a \clip scope; outputs \draw commands.
------------------------------------------------------------------------
function pfl.marching_squares(expr_str, xmin, xmax, ymin, ymax,
                               pasx, pasy, eps, color, lw)
    color = color or "black"
    lw    = lw    or "0.4pt"

    local f = pfl.expr_to_func(expr_str)
    if not f then return end

    local polylines = ms_core(f, xmin, xmax, ymin, ymax, pasx, pasy)

    for _, pts in ipairs(polylines) do
        tex.sprint(string.format(
            "\\draw[color=%s,line width=%s] %s;",
            color, lw, path_str(pts)))
    end
end

------------------------------------------------------------------------
-- Compute level curves F(x,y)=k for a list of k values.
-- Stores results in pfl._niveau_pts (table indexed by level index).
-- The grid is evaluated only once; each level shifts by -k.
------------------------------------------------------------------------
function pfl.level_curves(expr_str, valeurs_str,
                           xmin, xmax, ymin, ymax, pasx, pasy, eps)
    local f = pfl.expr_to_func(expr_str)
    if not f then pfl._niveau_pts = {}; return {} end

    local valeurs = {}
    for k in valeurs_str:gmatch("[^,]+") do
        valeurs[#valeurs+1] = tonumber(k)
    end

    pfl._niveau_pts = {}
    for _, k in ipairs(valeurs) do
        local fk = function(x, y) return f(x, y) - k end
        local polylines = ms_core(fk, xmin, xmax, ymin, ymax, pasx, pasy)
        pfl._niveau_pts[#pfl._niveau_pts+1] = polylines
    end
    return pfl._niveau_pts
end

------------------------------------------------------------------------
-- Draw one pre-computed level curve (called from \directlua in \foreach)
------------------------------------------------------------------------
function pfl.draw_level(idx, color, lw)
    color = color or "black"
    lw    = lw    or "0.4pt"
    local polylines = pfl._niveau_pts and pfl._niveau_pts[idx]
    if not polylines or #polylines == 0 then return end
    for _, pts in ipairs(polylines) do
        tex.sprint(string.format(
            "\\draw[color=%s,line width=%s] %s;",
            color, lw, path_str(pts)))
    end
end
\end{luacode*}
\fi

\endinput