Export, Result & Plot

TonCut Desktop has three output paths: SaveFile exports the source data (pieces and stock), the result callbacks save an optimization result, and the plot callbacks drive a cutting device. Source data and results use different objects and different coordinate rules; this page covers both.

Export surfaces

CallbackReceivesEnabled by
SaveFileThe live IFormats and ISheetsYour filters
SaveResultOne ISolutionSheet
BatchSaveResultThe whole ISolution and a file or folder /
Plot / BatchPlotOne ISolutionSheet / the whole ISolution /
SavePlot / BatchSavePlotOne sheet / the whole solution, plus a file or folder / /

Which button calls which method, how aPath is chosen, and how IsSaved is used are described under Features and host commands. Any result or plot save flag makes a valid PlotterInfo mandatory.

The collections and solution objects passed to these callbacks are valid only during the call. SaveFile receives the live data: read it, do not modify it, and do not keep it.

CSV exporter pattern

The SDK CSV starter writes the schema its importer reads (SDK/manuals/csv-schema.md):

RecordType,ProjectTitle,MaterialTitle,MaterialKind,MaterialWidth,MaterialThickness,Length,Width,Quantity,Identifier,Description
  1. Write one FORMAT row per IFormat and one SHEET row per ISheet.
  2. Convert every length from hundredths of a millimeter to millimeters (divide by cLengthMultiplier).
  3. Write 0 as the material width of anything that is not a 1D material.
  4. Write ISheet.Quantity unchanged: it is a signed Integer. The importer reads a missing, invalid, or zero quantity as 1.
  5. Save as UTF-8 with BOM and CRLF line endings.

SaveFile

// BuildCsvLine, CsvHeaderLine, and MaterialKindToText come from the SDK's
// examples/delphi/CsvImportExport/uCsvCommon.pas.
function UnitsToMillimeters(aValue: Cardinal): string;
begin
  Result := IntToStr((UInt64(aValue) + cLengthMultiplier div 2) div cLengthMultiplier);
end;

function MaterialWidthText(const aMaterial: IMaterial): string;
begin
  if aMaterial.Kind = mk1D then
    Result := UnitsToMillimeters(aMaterial.Width)
  else
    Result := '0';
end;

function TCsvImportExportPlugin.SaveFile(aWindow: THandle; const aFileName: WideString;
  const aFormats: IFormats; const aSheets: ISheets): TTcpResult;
var
  lines: TStringList;
  piece: IFormat;
  sheet: ISheet;
  projectTitle: string;
  i: Integer;
begin
  lines := TStringList.Create;
  try
    try
      lines.Add(CsvHeaderLine());

      for i := 0 to aFormats.Count - 1 do
      begin
        piece := aFormats[i];
        if piece.Material = nil then
          Continue;
        projectTitle := '';
        if piece.Project <> nil then
          projectTitle := piece.Project.Title;
        lines.Add(BuildCsvLine([
          'FORMAT', projectTitle, piece.Material.Title,
          MaterialKindToText(piece.Material.Kind),
          MaterialWidthText(piece.Material),
          UnitsToMillimeters(piece.Material.Thickness),
          UnitsToMillimeters(piece.Length), UnitsToMillimeters(piece.Width),
          IntToStr(piece.Quantity), piece.Identifier, piece.Description
        ]));
      end;

      for i := 0 to aSheets.Count - 1 do
      begin
        sheet := aSheets[i];
        if sheet.Material = nil then
          Continue;
        lines.Add(BuildCsvLine([
          'SHEET', '', sheet.Material.Title,
          MaterialKindToText(sheet.Material.Kind),
          MaterialWidthText(sheet.Material),
          UnitsToMillimeters(sheet.Material.Thickness),
          UnitsToMillimeters(sheet.Length), UnitsToMillimeters(sheet.Width),
          IntToStr(sheet.Quantity), sheet.Identifier, sheet.Description
        ]));
      end;

      lines.SaveToFile(aFileName, TEncoding.UTF8); // UTF-8 with BOM, CRLF
      Result := cprOK;
    except
      Result := cprFailed; // TonCut shows "Error writing file"
    end;
  finally
    lines.Free;
  end;
end;

In a C# plugin the native shim reads the TonCut objects and passes plain CsvRowRecord values to managed code, which only encodes and writes them.

Walking a solution

A result is a tree. Every length and position in it is an integer in hundredths of a millimeter.

  • ISolution: Count is the number of distinct layouts, not the number of sheets.
  • ISolutionSheet (one layout): Sheet is the stock sheet it is cut from, and Quantity is how many identical sheets are cut with this layout. The sheet's waste fields (TechnologicalWasteField, EdgingWasteField, KerfWasteField) are for one sheet; the same fields on ISolution are totals that already include every Quantity.
  • SolutionFormats (ISolutionFormat): each placed piece of one sheet, listed once. The number of pieces produced is the entry count times Quantity.
  • SolutionWastes (ISolutionWaste): all waste regions of one sheet, reusable or not. The API does not say which ones are reusable.
  • SolutionCuts (ISolutionCut): the cuts of one sheet, already in the output frame. TonCut fills them only before a save or plot callback.
ValueMeaning
ISolutionFormat.X, YThe minimum-X, minimum-Y corner of the piece's bounding box, in the native sheet frame.
Piece footprintIFormat.TotalLength along X by IFormat.TotalWidth along Y, swapped when Rotation is an odd quarter turn (900 or 2700). Shaped pieces and free rotation use the bounding box of the rotated outline.
ISolutionFormat.RotationTRotation, in tenths of a degree: cRotation90 = 900.
ISolutionFormat.MirroredWhether the piece is placed mirrored.
ISolutionWaste.X, Y, Length, WidthNative sheet frame; Length runs along X and Width along Y.
ISolutionWaste.FieldArea as TField, in (0.01 mm)² (divide by cFieldMultiplier for mm²).
ISolutionSheet.RotationWhole degrees, only 0, 90, 180, or 270.
CalcCutsInfo(var Count; var Length)For one sheet: the number and total length (0.01 mm, as Double) of the original, non-optimized cuts. Count can differ from SolutionCuts.Count. Requires the sheet material's Device.
ISolution.CalcCutsInfoByMaterialThe same for every sheet of one material, already multiplied by Quantity.
CalcRecycledField(aMin, aMin)Sum, as TField, of the non-shaped reusable waste. Both parameters are ignored.

Walk the solution

// uses System.SysUtils, System.Classes, System.Math, uICommon, uIFormat,
//   uISolution, uISolutionSheet, uISolutionFormat, uISolutionWaste;
procedure ListSolution(const aSolution: ISolution; aLines: TStrings);
var
  s, i, x0, y0, x1, y1, footprintX, footprintY: Integer;
  layout: ISolutionSheet;
  placed: ISolutionFormat;
  waste: ISolutionWaste;
  quarterTurns: Integer;
begin
  for s := 0 to aSolution.Count - 1 do
  begin
    layout := aSolution[s];
    aLines.Add(Format('Layout %d: cut %d sheet(s) of %s', [s + 1, layout.Quantity,
      layout.Sheet.Description]));

    for i := 0 to layout.SolutionFormats.Count - 1 do
    begin
      placed := layout.SolutionFormats[i];
      // Rectangular footprint; odd quarter turns swap length and width.
      quarterTurns := placed.Rotation div cRotation90;
      footprintX := placed.Format.TotalLength;
      footprintY := placed.Format.TotalWidth;
      if Odd(quarterTurns) then
      begin
        footprintX := placed.Format.TotalWidth;
        footprintY := placed.Format.TotalLength;
      end;

      // Two opposite corners, mapped from the native to the output frame.
      x0 := placed.X;
      y0 := placed.Y;
      x1 := x0 + footprintX;
      y1 := y0 + footprintY;
      layout.CalcPoint(x0, y0);
      layout.CalcPoint(x1, y1);

      aLines.Add(Format('  %s x%d at (%.2f, %.2f)-(%.2f, %.2f) mm, %.1f deg', [
        placed.Format.Description, layout.Quantity,
        Min(x0, x1) / cLengthMultiplier, Min(y0, y1) / cLengthMultiplier,
        Max(x0, x1) / cLengthMultiplier, Max(y0, y1) / cLengthMultiplier,
        placed.Rotation * cRotationUnit]));
    end;

    for i := 0 to layout.SolutionWastes.Count - 1 do
    begin
      waste := layout.SolutionWastes[i];
      aLines.Add(Format('  waste %.2f x %.2f mm at native (%.2f, %.2f), %.0f mm2', [
        waste.Length / cLengthMultiplier, waste.Width / cLengthMultiplier,
        waste.X / cLengthMultiplier, waste.Y / cLengthMultiplier,
        waste.Field / cFieldMultiplier]));
    end;
  end;
end;

Coordinate frames

Two frames are involved, and both use hundredths of a millimeter:

  • Native sheet frame. Origin at the sheet's corner (0, 0), X along ISheet.Length, Y along ISheet.Width, before any sheet or plotter rotation and mirroring. ISolutionFormat.X/Y and every ISolutionWaste coordinate use it.
  • Effective output frame. The frame of the saved or plotted output: the sheet rotation and mirror applied, then the plotter's DefaultRotation, DefaultMirror, and axis directions. SolutionCuts are already in this frame.

Which plotter info defines the output frame. In the Save results dialog, the frame of SolutionCuts and of CalcPoint for every page is built from the saving plugin's own PlotterInfo: its AxisX, AxisY, DefaultRotation, and DefaultMirror. When the plugin advertises a result save flag and the sheet's material has a device, TonCut composes the device's own transformation first and the plugin's on top of it, keeping the plugin's axes (observed in code). Changing those four values in your PlotterInfo therefore rotates or mirrors every result your plugin writes; keep them stable across releases.

The ISolutionSheet helpers convert between them. None of them scales: units in are units out.

HelperWhat it does
CalcPoint(var X, Y: Integer), CalcPointF(var X, Y: Double)Native frame to output frame. Use them for piece and waste coordinates.
UnCalcPoint, UnCalcPointFThe inverse: output frame to native frame.
GetOriginPoint(var X, Y)The native-frame point that maps to the output origin; the same as UnCalcPoint(0, 0).
GetDirection(var X, Y)+1 or -1 per output axis.
GetEffectiveModificator(var Rotation, Mirror)The effective rotation and mirror applied to the sheet.
CalcEffectiveLayout(var Length, Width, MarginLeft, MarginTop, MarginRight, MarginBottom)The sheet's length and width (swapped for 90° and 270°) and the sheet's edging (trim) per side, rotated and mirrored into the output frame. The four values are the sheet edging, not material margins, despite the parameter names. It raises an error when the effective angle is not a quarter turn.

Never pass SolutionCuts through CalcPoint or CalcPointF. They are already transformed; transforming them again rotates or mirrors them a second time.

PLT output

An HPGL/PLT writer takes the cuts as they are and only scales them. HPGL uses 40 plotter units per millimeter, and TonCut uses 100 units per millimeter, so the factor is 40 / cLengthMultiplier = 0.4 plotter units per TonCut unit. For another plotter, use its units per millimeter divided by cLengthMultiplier.

SolutionCuts as HPGL

const
  cHpglUnitsPerMm = 40;

function ExportSolutionSheetAsPlt(const aSolutionSheet: ISolutionSheet;
  aCommands: TStrings): Boolean;
var
  scale: Double;
  cuts: ISolutionCuts;
  cut: ISolutionCut;
  i: Integer;

  function P(aValue: Integer): Integer;
  begin
    Result := Round(aValue * scale);
  end;

begin
  scale := cHpglUnitsPerMm / cLengthMultiplier; // 0.4
  cuts := aSolutionSheet.SolutionCuts;           // already in the output frame
  aCommands.Clear;
  aCommands.Add('IN;');
  aCommands.Add('PA;');

  for i := 0 to cuts.Count - 1 do
  begin
    cut := cuts[i];
    aCommands.Add(Format('PU%d,%d;', [P(cut.PosX), P(cut.PosY)]));
    case cut.Kind of
      ckLine:
        aCommands.Add(Format('PD%d,%d;', [P(cut.TarX), P(cut.TarY)]));
      ckCurve:
        aCommands.Add(Format('BZ%d,%d,%d,%d,%d,%d;', [
          P(cut.PosXp), P(cut.PosYp), P(cut.TarXp), P(cut.TarYp),
          P(cut.TarX), P(cut.TarY)]));
    end;
  end;

  aCommands.Add('PU;');
  aCommands.Add('SP0;');
  Result := True;
end;

The C# managed library has no solution interface or PLT writer: in a C# plugin the native shim owns SaveResult and this conversion.

Plot surfaces

Plot, BatchPlot, SavePlot, and BatchSavePlot receive the same solution objects as the result callbacks, with the same frames and units. ITcPlotterInfo describes the device the plugin drives. When a device's Driver names the plugin's Name, TonCut takes the plugin's plotter info as the source of the plugin-controlled device settings, including the default rotation, mirror, and axis directions that define the output frame. The plugin implements ITcPlotterInfo itself; the Quickstart contains a complete implementation.

The plotter info also filters what the user can save through the plugin:

  • The Save results dialog disables every page whose material kind is not in PlotterInfo.MaterialKinds. A plugin that saves both 1D and 2D results returns [mk1D, mk2D].
  • When the plugin advertises a plot save flag, the dialog also disables every page whose device Driver is not the plugin's Name.

Was this page helpful?