Routing: where graph theory takes over
Once local stitch geometry exists, the compiler must decide how to traverse it. This is where embroidery begins to look unmistakably like operations research.
8.1 Required edges and optional travel
Represent a line-based design as a graph
where:
- \(V\) contains endpoints, junctions, crossings, and candidate entry or exit points;
- \(E_R\) contains required edges that must be sewn;
- \(E_T\) contains optional travel edges, jumps, or hidden routes.
Each edge can have a cost vector rather than one scalar:
The scalar cost used by an optimizer depends on the current production policy.
8.2 Euler trails
If every required edge should be sewn exactly once, seek an Euler trail.
For a connected undirected graph:
- an Euler circuit exists if every vertex has even degree;
- an open Euler trail exists if exactly two vertices have odd degree;
- otherwise some edges must be repeated or the path must be interrupted.
This gives a clean explanation for a familiar digitizing fact: a line drawing with many odd-degree junctions cannot be sewn in one uninterrupted pass without retracing, jumping, or trimming.
8.3 The Chinese Postman Problem
If every edge must be covered at least once and repeated sewing is allowed, the minimum-cost closed traversal is a Chinese Postman Problem. In the undirected case, odd-degree vertices can be paired through minimum-cost matching so that duplicated paths make the graph Eulerian.1
Embroidery variants are often harder because:
- only some edges are required;
- retracing has a visual cost;
- direction can change cost;
- the path may have different start and end locations;
- jumps and trims are alternatives;
- future layers may hide some travel;
- precedence constraints restrict traversal order.
That moves the problem toward rural, windy, directed, open, and prize-collecting postman variants.
8.4 Redwork and deliberate edge multiplicity
Some embroidery styles intentionally sew every line twice so the path returns while preserving an even-looking line. This can be modeled by assigning required multiplicity \(m_e=2\) to each edge. Ink/Stitch’s redwork routing tool describes the same practical requirement: every path is used exactly twice.2
The graph is then Eulerian by construction if every doubled edge is treated as distinct. The artistic question becomes how to order the two traversals and whether tiny deviations are desirable to avoid exact penetration overlap.
8.5 Object-level routing
Filled objects are not single points. Each object \(i\) may have candidate entry and exit states
Choosing an object order and one state per object resembles a generalized traveling-salesperson problem. The transition cost from state \(r\) of object \(i\) to state \(s\) of object \(j\) can be
The nearest next object is not necessarily best. Its exit may lead badly into the following object, or sewing it now may violate overlap order.
8.6 Precedence-constrained scheduling
Let \(i\prec j\) mean object \(i\) must be completed before object \(j\). A schedule \(\pi\) is valid only if it is a topological ordering of the precedence DAG.
The objective might be
subject to all precedence edges.
This is a setup-cost scheduling problem intertwined with routing. Exact mixed-integer methods are possible for small designs; larger designs usually need decomposition and heuristics.
8.7 Color scheduling
Grouping all objects of one color reduces changes, but overlap can require returning to a color later. For example, a dark shape may need to appear both below and above a light shape.
Model color as a setup state. A simple cost is
A more realistic model distinguishes:
- automatic needle switches;
- manual thread changes;
- stops with no color change;
- same-color blocks separated by required trims;
- machine-specific needle assignment limits.
Color optimization must operate above the file-format layer. A backend may encode a stop by abusing a color-change command, but that target workaround should not contaminate the semantic schedule.3
8.8 Hidden travel is time-dependent geometry
A travel stitch can be acceptable if a later region covers it. Let \(V_t(x)\) be the predicted visibility of point \(x\) after step \(t\). The visibility cost of a travel curve \(\gamma\) made at time \(t\) is approximately
This turns route planning into a spatiotemporal problem. A route that is expensive now may become free if it lies under an object that is guaranteed to be sewn later.
The planner should therefore know:
- future coverage regions;
- whether the travel color can show through;
- whether extra thread beneath a region causes bulk;
- whether the travel crosses an exposed opening;
- whether the future layer is certain or optional.
8.9 A practical routing strategy
A production compiler rarely solves one giant exact problem. A useful hierarchical approach is:
- build and validate the precedence DAG;
- divide the graph into color-compatible or phase-compatible batches;
- route line networks inside each object with Euler or postman methods where applicable;
- generate several entry and exit candidates for each object;
- choose an initial topological order greedily using transition cost and mechanical risk;
- improve it with local swaps, 2-opt-style moves, or dynamic programming that preserves precedence;
- reconsider hidden travel and trim decisions after the order is known;
- validate the final machine state transitions.
This approach is not globally optimal, but it is explainable, debuggable, and fast enough for interactive use.
8.10 When to use exact optimization
Exact solvers are valuable when:
- a line-art graph is small;
- color changes are unusually expensive;
- an appliqué workflow has strict ordering;
- a production run justifies longer compile time;
- a heuristic result is used as a warm start;
- the solver can prove that no better route exists within the model.
For large artistic designs, the model mismatch usually dominates the optimization gap. A mathematically optimal route under a crude visibility model can be worse than a slightly longer route chosen by a good heuristic.
Material mechanics: the fabric gets a vote
A pixel does not pull on its neighbor. A stitch does.
9.1 Fabric as an anisotropic sheet
Let \(u(x)\) be the displacement of a point in the fabric. The deformation gradient is
A continuum model uses an energy
where \(a_{\text{warp}}\) and \(a_{\text{weft}}\) are material directions and \(\eta\) contains material parameters.
Real cloth is nonlinear and anisotropic. Its response depends on yarn structure, shear, contact, and friction. Yarn-level simulation makes this explicit, while shell models homogenize the behavior into an effective material.45
9.2 A simplified thread model
A stitch can be approximated as a tensioned constraint between penetrations. For a segment with deformed length \(\ell_i(u)\) and effective rest length \(\ell_i^0\), one simple tension-only energy is
This is deliberately simplified. Real lockstitch behavior includes top and bobbin thread interlock, friction through the substrate, bending around penetrations, tension history, and contact between layers.
The equilibrium is
Even this simplified formulation explains why direction, density, and sequence matter: they change the directions and locations of imposed tension.
9.3 Pull and push
Pull commonly describes contraction across a satin column or fill direction. Push describes apparent extension or displacement near the ends or along the direction of sewing. These are practical names for a coupled deformation, not separate universal physical laws.
For a satin column with target width \(w_{\text{target}}\) and predicted inward displacement \(\delta_L\), \(\delta_R\) at the rails, a basic compensation is
For a symmetric model,
Ink/Stitch describes pull compensation operationally as expanding satin penetrations outward because the stitched column tends to sew narrower than the drawn column.6
A spatially varying boundary compensation is better:
There is no universal constant that can replace this function.
9.4 Shared-edge overlap
Suppose region \(A\) is sewn before region \(B\), and \(B\) should visually meet \(A\) along boundary \(\Gamma\). A registration margin can be implemented by expanding the hidden edge of \(A\) or \(B\):
near \(\Gamma\) only.
The choice depends on layer order and visual semantics. Expanding both regions everywhere wastes thread and increases stiffness. Use a boundary-labeled overlap operation rather than a blind global offset.
9.5 Density changes stiffness
More thread does not only darken the region. It creates a composite structure. Stitch direction and density can alter effective stretch and stiffness. DIGISEW demonstrates the deliberate use of anisotropic embroidery to control variable stretch in textiles.7
The local material after stitching can be modeled with an effective constitutive parameter
This creates a feedback loop: the stitch plan changes the material, and the changed material affects later stitches.
9.6 Underlay as mechanical preconditioning
Underlay can:
- restrain local shear;
- flatten pile or texture;
- distribute top-thread load;
- establish an edge that supports satin rails;
- change friction and apparent thickness;
- alter how later stitches pull.
A mechanics-aware compiler should simulate or estimate layers in order, updating the local substrate state after each one.
9.7 Puckering as instability and mismatch
Puckering can arise from several mechanisms:
- excessive thread tension relative to fabric support;
- compression accumulated across dense rows;
- insufficient or inappropriate stabilization;
- directional imbalance;
- poor hooping;
- sequence-dependent concentration of load;
- thermal or moisture effects in some materials.
A crude risk proxy can combine local thread length per area, direction imbalance, and unsupported fabric span:
This is a warning model, not a physical law. Its value comes from calibration against actual stitch-outs.
9.8 Calibration is part of compilation
The most practical mechanics model is often empirical. Create test swatches over a parameter space such as
Measure outputs such as:
Fit a model
using regression, splines, random forests, Gaussian processes, or another interpretable surrogate. Store uncertainty as well as the mean prediction.
A simple linear model might be
The doubled angle appears again because material response is often symmetric under a \(180^\circ\) reversal.
9.9 Robust optimization
Because the setup varies, optimize expected quality and sensitivity:
A production system may prefer a slightly less perfect nominal result that remains acceptable across fabric lots and tension variation.
9.10 Embroidery can be structure, not decoration
Research on shape-changing textiles, anisotropic stitching, and machine-embroidered metamaterials shows that stitch layout can control deformation, stiffness, folding, and mechanical behavior.8910 This widens the compiler’s job. In some applications, the desired output is not an image but a mechanical response.
Then the target specification may include
and appearance becomes only one objective among several.
Appearance and perception
Embroidery is not colored ink. Direction changes how thread catches light, overlap creates relief, and stitch rhythm becomes texture.
10.1 Directional reflectance
A thread segment has a tangent \(t\), local surface normal \(n\), and material response. A simplified radiance model is
The reflectance function \(f_r\) depends strongly on fiber and thread direction. This is why equal-color regions with different stitch angles can look like different shades under the same light.
Directionality-aware embroidery research explicitly treats color and direction as coupled appearance channels.11 Earlier graphics work also modeled and rendered thread geometry to reproduce embroidery appearance.12
10.2 A preview should render thread, not just lines
A useful preview approximates:
- thread width and cross-section;
- segment tangent;
- layer order and occlusion;
- shadows between adjacent stitches;
- anisotropic highlights;
- fabric deformation or at least compensated geometry;
- the difference between stitches and jumps;
- penetrations and tie sequences at high zoom.
A flat polyline preview is valuable for debugging routing but poor for judging final sheen and coverage.
10.3 Color matching
Thread colors form a discrete palette. Let \(c_t(x)\) be a target color and \(c_j\) be thread color \(j\). A simple assignment is
where \(\Delta E_{00}\) is the CIEDE2000 perceptual color difference.
But embroidery color also depends on:
- underlying fabric;
- stitch direction and lighting;
- thread sheen;
- coverage and gaps;
- overlap order;
- neighboring colors;
- mixed or interleaved thread patterns.
For color blending, an empirical swatch model is safer than linear RGB mixing:
Then choose a mixture by minimizing measured perceptual error plus production cost.
10.4 Texture as a communication channel
Texture can communicate:
- surface form;
- motion;
- material identity;
- foreground and background separation;
- tactile category;
- visual emphasis.
A texture assignment problem can be written as a labeling objective. Let region \(i\) receive texture label \(z_i\). Then
where \(U_i\) measures how well a texture suits a region and \(P_{ij}\) penalizes adjacent regions that are too similar or mechanically incompatible.
Machine-embroidered tactile graphics research uses optimization to assign distinguishable patterns to regions, illustrating that “best stitch” can be defined by human recognition rather than visual pixel similarity.13
10.5 Salience and controlled simplification
Not every detail deserves equal thread. Define a salience field \(w(x)\) based on edges, semantic importance, user annotations, or viewing scale. Allocate stitch budget where it matters:
Or use a rate-distortion view:
This frames simplification as a controlled trade rather than an arbitrary cleanup pass.
Machine semantics and target lowering
A stitch file is executable code for physical hardware. Treat it with the same care as any other backend target.
11.1 A target-neutral command set
A useful machine command IR can include:
| Command | Meaning |
|---|---|
STITCH(q) | move to \(q\) while forming a stitch |
JUMP(q) | move to \(q\) without forming a normal stitch |
TRIM | cut or release the current thread, if supported |
COLOR_CHANGE | switch thread color or request operator action |
NEEDLE_SET(k) | select needle or thread position \(k\) |
STOP | pause for an external operation |
END | terminate the program |
Open-source embroidery libraries such as pyembroidery use a similar command vocabulary and support multiple commercial formats.14
The semantic IR should be richer than the least capable format. Backends can lower, emulate, warn, or fail depending on capability.
11.2 Thread attachment state
Track at least these states:
- detached: thread has been trimmed or is not secured;
- attaching: tack or lock sequence is being formed;
- attached: ordinary sewing can proceed;
- securing: a lock sequence is being formed before a transition;
- paused: machine awaits an external action.
A jump from a detached state is harmless. A stitch from a detached state may require a tack sequence. A trim from an already detached state may be redundant or unsupported.
Tack and lock stitches should be explicit semantic operations or annotated generated stitches. Ink/Stitch documents them as short securing sequences around color changes, trims, and qualifying jumps.15
11.3 Capability matrices
Different formats and machines differ in:
- coordinate resolution and range;
- absolute versus relative movement representation;
- explicit trim support;
- jump semantics;
- color and needle metadata;
- hoop metadata;
- stitch-count limits;
- stop or sequin commands;
- thread palettes;
- header and checksum requirements.
Represent this as data:
MachineProfile
workArea
coordinateResolution
maxEncodedDelta
supportedCommands
trimBehavior
colorChangeBehavior
needleCount
speedModel
formatBackends
Do not scatter target checks throughout geometry code. The backend should declare capabilities, and earlier passes should query a stable interface.
11.4 Lowering is allowed to be lossy—but never silently
Examples:
- a true trim may become a machine-specific jump pattern;
- a stop may be encoded as a synthetic color change;
- a long movement may be split into several encoded deltas;
- thread metadata may be mapped to the nearest supported palette entry;
- unsupported commands may require operator instructions.
Every semantic downgrade should produce a diagnostic or export report.
11.5 Relative encoding and delta limits
Many machine formats encode relative motion:
If a delta exceeds the target range, split it:
with each component representable.
The inserted movements must preserve semantics. A long jump can be split into jumps. A long stitch split into several stitches changes the physical result and should have been handled earlier by the stitch-planning pass.
11.6 Time estimation
A first-order estimate is
Here \(f_{\text{eff}}\) is an effective stitch rate, not necessarily the selected maximum speed. Short stitches, sharp turns, frame acceleration, and machine control can reduce actual throughput.
A calibrated machine profile can fit
11.7 Round-trip testing
For each backend:
- encode the machine IR;
- decode it with an independent or reference parser where possible;
- compare command semantics and positions;
- verify bounds, color blocks, and termination;
- render the decoded result, not only the pre-encoded plan;
- test on hardware with small canonical patterns.
Binary equality is not the goal when formats normalize metadata. Semantic equality is.
One objective function is not enough
A weighted sum is convenient, but it can hide unacceptable trade-offs. A compiler should combine constraints, lexicographic priorities, and Pareto exploration.
12.1 A fuller loss
For path set \(P\), order \(\pi\), and machine program \(Q\), one possible model is
This is still incomplete, but it shows the layers of the problem.
12.2 Lexicographic optimization
A useful priority order is:
- machine validity and safety;
- physical sewability;
- required layer and workflow semantics;
- perceptual quality;
- robustness;
- production efficiency.
Lexicographic optimization prevents the system from trading a hard machine failure for a tiny visual improvement because of poorly scaled weights.
12.3 Pareto fronts
Some objectives genuinely conflict. Let
A solution is Pareto-optimal if no objective can improve without worsening another. A user-facing slider between density fidelity and directional fidelity, as demonstrated in directionality-aware embroidery research, is a practical way to expose a slice of that Pareto front.11
12.4 Discrete and continuous variables
The optimization is hybrid.
Discrete variables include:
- stitch primitive choice;
- region decomposition;
- layer order;
- thread color;
- underlay type;
- trim versus travel;
- object entry and exit state.
Continuous variables include:
- stitch coordinates;
- spacing;
- direction angle;
- compensation offset;
- streamline position;
- path smoothing parameters.
Trying to optimize them all simultaneously is usually impractical. Alternate or stage the solves.
12.5 Useful solver families
| Subproblem | Useful methods |
|---|---|
| Boolean geometry and offsets | arrangement algorithms, polygon clipping, signed-distance methods |
| Direction smoothing | sparse least squares, nonlinear optimization, harmonic methods |
| Scalar potential | Poisson or screened-Poisson solve |
| Streamline placement | greedy seeding, repulsion, constrained optimization |
| Running-stitch routing | Euler traversal, matching, shortest paths, postman algorithms |
| Object scheduling | dynamic programming, MILP, greedy insertion, local search |
| Color selection | discrete labeling, assignment, graph cuts for suitable models |
| Compensation fitting | regression, Gaussian process, calibrated lookup table |
| Global refinement | L-BFGS, sequential quadratic programming, simulated annealing |
12.6 Why decomposition is a feature
The physical model is approximate, the artistic loss is subjective, and many decisions are categorical. A transparent multi-pass compiler is often better than a black-box global optimizer because it can:
- explain why a choice was made;
- preserve user edits;
- rerun only affected passes;
- attach diagnostics to the responsible representation;
- offer meaningful overrides;
- cache expensive calculations;
- remain deterministic.
References
References and further reading
The following sources are a practical starting point rather than an exhaustive bibliography. The embroidery-specific literature is relatively small, so adjacent work in computational fabrication, direction-field design, cloth mechanics, and graph routing is essential.
For the central embroidery-path problem, begin with Liu et al. on direction-aware streamlines and Tian et al. on spiral paths. For the mathematical machinery behind fields, continue with direction-field and vector-field processing references. For the material side, the cloth-modeling and computational-embroidery papers show why geometry alone is not enough. For real implementation semantics, inspect the official Ink/Stitch documentation and pyembroidery source.
Margaret Ellen Seehorn, Gene S.-H. Kim, Aashaka Desai, Megan Hofmann, and Jennifer Mankoff, “Enhancing Access to High Quality Tangible Information through Machine Embroidered Tactile Graphics,” Proceedings of the ACM Symposium on Computational Fabrication (SCF ’22), Article 23, 2022. https://doi.org/10.1145/3559400.3565586
Gabriel Cirio, Jorge López-Moreno, David Miraut, and Miguel A. Otaduy, “Yarn-Level Simulation of Woven Cloth,” ACM Transactions on Graphics 33, no. 6, Article 207, 2014. https://doi.org/10.1145/2661229.2661279
Georg Sperl, Rosa M. Sánchez-Banderas, Manwen Li, Chris Wojtan, and Miguel A. Otaduy, “Estimation of Yarn-Level Simulation Models for Production Fabrics,” ACM Transactions on Graphics 41, no. 4, Article 65, 2022. https://doi.org/10.1145/3528223.3530167
Qiming Tian, Yupin Luo, and Dongcheng Hu, “Spiral-Fashion Embroidery Path Generation in Embroidery CAD Systems,” Computer-Aided Design 38, no. 2, pp. 125–133, 2006. https://doi.org/10.1016/j.cad.2005.08.004
Zhenyuan Liu, Michal Piovarči, Christian Hafner, Raphaël Charrondière, and Bernd Bickel, “Directionality-Aware Design of Embroidery Patterns,” Computer Graphics Forum 42, no. 2, pp. 397–409, 2023. https://doi.org/10.1111/cgf.14770
Xiangjia Chen, Guoxin Fang, Wei-Hsin Liao, and Charlie C. L. Wang, “Field-Based Toolpath Generation for 3D Printing Continuous Fibre Reinforced Thermoplastic Composites,” Additive Manufacturing 49, Article 102470, 2022. https://doi.org/10.1016/j.addma.2021.102470
Kate S. Glazko, Alexandra A. Portnova-Fahreeva, Arun Mankoff-Dey, Afroditi Psarra, and Jennifer Mankoff, “Shaping Lace: Machine Embroidered Metamaterials,” Proceedings of the 9th ACM Symposium on Computational Fabrication (SCF ’24), 2024. https://doi.org/10.1145/3639473.3665792
Ink/Stitch, “Tatami Stitch (Fill Stitch),” official documentation. https://inkstitch.org/docs/stitches/fill-stitch/
Fernando de Goes, Mathieu Desbrun, and Yiying Tong, “Vector Field Processing on Triangle Meshes,” ACM SIGGRAPH 2016 Course Notes, 2016; and Felix Knöppel, Keenan Crane, Ulrich Pinkall, and Peter Schröder, “Globally Optimal Direction Fields,” ACM Transactions on Graphics 32, no. 4, Article 59, 2013. Course notes; direction-field paper
Jack Edmonds and Ellis L. Johnson, “Matching, Euler Tours and the Chinese Postman,” Mathematical Programming 5, pp. 88–124, 1973. https://doi.org/10.1007/BF01580113
Ink/Stitch, “Tools: Stroke—Redwork,” official documentation. The tool’s routing goal is to traverse every path exactly twice. https://inkstitch.org/docs/stroke-tools/
Ink/Stitch, “Commands,” official documentation. https://inkstitch.org/docs/commands/
Huamin Wang, James F. O’Brien, and Ravi Ramamoorthi, “Data-Driven Elastic Models for Cloth: Modeling and Measurement,” ACM Transactions on Graphics 30, no. 4, Article 71, 2011. https://doi.org/10.1145/2010324.1964966
Ink/Stitch, “Satin Column,” official documentation. https://inkstitch.org/docs/stitches/satin-column/
Abhinit Sati, Ioannis Karamouzas, and Victor B. Zordan, “DIGISEW: Anisotropic Stitching for Variable Stretch in Textiles,” Proceedings of the ACM Symposium on Computational Fabrication (SCF ’21), Article 3, 2021. https://doi.org/10.1145/3485114.3485121
Yu Jiang, Narjes Pourjafarian, Alice Haynes, and Jürgen Steimle, “Embrogami: Shape-Changing Textiles with Machine Embroidery,” Proceedings of the 37th Annual ACM Symposium on User Interface Software and Technology (UIST ’24), 2024. https://doi.org/10.1145/3654777.3676431
Ayesha Nabila, Hua Ma, and Junichi Yamaoka, “4D Embroidery: Implementing Parametric Structures in Textiles for Sculptural Embroidery,” UbiComp/ISWC ’22 Adjunct, pp. 88–90, 2022. https://doi.org/10.1145/3544793.3560358
Xinling Chen, Michael McCool, Asanobu Kitamoto, and Stephen Mann, “Embroidery Modeling and Rendering,” Proceedings of Graphics Interface 2012, pp. 131–139, 2012. https://doi.org/10.5555/2305276.2305299
EmbroidePy, “pyembroidery,” an open-source Python library for reading and writing embroidery formats. https://github.com/EmbroidePy/pyembroidery
Ink/Stitch, “Tack and Lock Stitches,” official documentation. https://inkstitch.org/docs/stitches/lock-stitches/