Reorg: move svg-flatten files into subdir

This commit is contained in:
jaseg 2021-01-30 20:01:00 +01:00
parent 617a42a674
commit 2133867c8a
25 changed files with 12 additions and 13 deletions

View file

@ -0,0 +1,36 @@
/*
* This file is part of gerbolyze, a vector image preprocessing toolchain
* Copyright (C) 2021 Jan Sebastian Götte <gerbolyze@jaseg.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <cmath>
#include <algorithm>
#include <string>
#include <gerbolyze.hpp>
#include <svg_import_defs.h>
using namespace gerbolyze;
using namespace std;
LambdaPolygonSink& LambdaPolygonSink::operator<<(const Polygon &poly) {
m_lambda(poly, m_currentPolarity);
return *this;
}
LambdaPolygonSink& LambdaPolygonSink::operator<<(GerberPolarityToken pol) {
m_currentPolarity = pol;
return *this;
}

395
svg-flatten/src/main.cpp Normal file
View file

@ -0,0 +1,395 @@
#include <cstdlib>
#include <cstdio>
#include <filesystem>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
#include <argagg.hpp>
#include <subprocess.h>
#include <gerbolyze.hpp>
#include "vec_core.h"
#include <base64.h>
using argagg::parser_results;
using argagg::parser;
using namespace std;
using namespace gerbolyze;
int main(int argc, char **argv) {
parser argparser {{
{"help", {"-h", "--help"},
"Print help and exit",
0},
{"version", {"-v", "--version"},
"Print version and exit",
0},
{"ofmt", {"-o", "--format"},
"Output format. Supported: gerber, svg, s-exp (KiCAD S-Expression)",
1},
{"precision", {"-p", "--precision"},
"Number of decimal places use for exported coordinates (gerber: 1-9, SVG: 0-*)",
1},
{"svg_clear_color", {"--clear-color"},
"SVG color to use for \"clear\" areas (default: white)",
1},
{"svg_dark_color", {"--dark-color"},
"SVG color to use for \"dark\" areas (default: black)",
1},
{"min_feature_size", {"-d", "--trace-space"},
"Minimum feature size of elements in vectorized graphics (trace/space) in mm. Default: 0.1mm.",
1},
{"no_header", {"--no-header"},
"Do not export output format header/footer, only export the primitives themselves",
0},
{"flatten", {"--flatten"},
"Flatten output so it only consists of non-overlapping white polygons. This perform composition at the vector level. Potentially slow.",
0},
{"no_flatten", {"--no-flatten"},
"Disable automatic flattening for KiCAD S-Exp export",
0},
{"dilate", {"--dilate"},
"Dilate output gerber primitives by this amount in mm. Used for masking out other layers.",
1},
{"only_groups", {"-g", "--only-groups"},
"Comma-separated list of group IDs to export.",
1},
{"vectorizer", {"-b", "--vectorizer"},
"Vectorizer to use for bitmap images. One of poisson-disc (default), hex-grid, square-grid, binary-contours, dev-null.",
1},
{"vectorizer_map", {"--vectorizer-map"},
"Map from image element id to vectorizer. Overrides --vectorizer. Format: id1=vectorizer,id2=vectorizer,...",
1},
{"force_svg", {"--force-svg"},
"Force SVG input irrespective of file name",
0},
{"force_png", {"--force-png"},
"Force bitmap graphics input irrespective of file name",
0},
{"size", {"-s", "--size"},
"Bitmap mode only: Physical size of output image in mm. Format: 12.34x56.78",
1},
{"sexp_mod_name", {"--sexp-mod-name"},
"Module name for KiCAD S-Exp output",
1},
{"sexp_layer", {"--sexp-layer"},
"Layer for KiCAD S-Exp output. Defaults to auto-detect layers from SVG layer/top-level group names",
1},
{"preserve_aspect_ratio", {"-a", "--preserve-aspect-ratio"},
"Bitmap mode only: Preserve aspect ratio of image. Allowed values are meet, slice. Can also parse full SVG preserveAspectRatio syntax.",
1},
{"skip_usvg", {"--no-usvg"},
"Do not preprocess input using usvg (do not use unless you know *exactly* what you're doing)",
0},
{"exclude_groups", {"-e", "--exclude-groups"},
"Comma-separated list of group IDs to exclude from export. Takes precedence over --only-groups.",
1},
}};
ostringstream usage;
usage
<< argv[0] << " " << lib_version << endl
<< endl
<< "Usage: " << argv[0] << " [options]... [input_file] [output_file]" << endl
<< endl
<< "Specify \"-\" for stdin/stdout." << endl
<< endl;
argagg::parser_results args;
try {
args = argparser.parse(argc, argv);
} catch (const std::exception& e) {
argagg::fmt_ostream fmt(cerr);
fmt << usage.str() << argparser << '\n'
<< "Encountered exception while parsing arguments: " << e.what()
<< '\n';
return EXIT_FAILURE;
}
if (args["help"]) {
argagg::fmt_ostream fmt(cerr);
fmt << usage.str() << argparser;
return EXIT_SUCCESS;
}
if (args["version"]) {
cerr << lib_version << endl;
return EXIT_SUCCESS;
}
string in_f_name;
istream *in_f = &cin;
ifstream in_f_file;
string out_f_name;
ostream *out_f = &cout;
ofstream out_f_file;
if (args.pos.size() >= 1) {
in_f_name = args.pos[0];
if (args.pos.size() >= 2) {
out_f_name = args.pos[1];
}
}
if (!in_f_name.empty() && in_f_name != "-") {
in_f_file.open(in_f_name);
if (!in_f_file) {
cerr << "Cannot open input file \"" << in_f_name << "\"" << endl;
return EXIT_FAILURE;
}
in_f = &in_f_file;
}
if (!out_f_name.empty() && out_f_name != "-") {
out_f_file.open(out_f_name);
if (!out_f_file) {
cerr << "Cannot open output file \"" << out_f_name << "\"" << endl;
return EXIT_FAILURE;
}
out_f = &out_f_file;
}
bool only_polys = args["no_header"];
int precision = 6;
if (args["precision"]) {
precision = atoi(args["precision"]);
}
string fmt = args["ofmt"] ? args["ofmt"] : "gerber";
transform(fmt.begin(), fmt.end(), fmt.begin(), [](unsigned char c){ return std::tolower(c); }); /* c++ yeah */
string sexp_layer = args["sexp_layer"] ? args["sexp_layer"].as<string>() : "auto";
bool force_flatten = false;
bool is_sexp = false;
PolygonSink *sink = nullptr;
PolygonSink *flattener = nullptr;
PolygonSink *dilater = nullptr;
if (fmt == "svg") {
string dark_color = args["svg_dark_color"] ? args["svg_dark_color"] : "#000000";
string clear_color = args["svg_clear_color"] ? args["svg_clear_color"] : "#ffffff";
sink = new SimpleSVGOutput(*out_f, only_polys, precision, dark_color, clear_color);
} else if (fmt == "gbr" || fmt == "grb" || fmt == "gerber") {
sink = new SimpleGerberOutput(*out_f, only_polys, 4, precision);
} else if (fmt == "s-exp" || fmt == "sexp" || fmt == "kicad") {
if (!args["sexp_mod_name"]) {
cerr << "--sexp-mod-name must be given for sexp export" << endl;
argagg::fmt_ostream fmt(cerr);
fmt << usage.str() << argparser;
return EXIT_FAILURE;
}
sink = new KicadSexpOutput(*out_f, args["sexp_mod_name"], sexp_layer, only_polys);
force_flatten = true;
is_sexp = true;
} else {
cerr << "Unknown output format \"" << fmt << "\"" << endl;
argagg::fmt_ostream fmt(cerr);
fmt << usage.str() << argparser;
return EXIT_FAILURE;
}
PolygonSink *top_sink = sink;
if (args["dilate"]) {
dilater = new Dilater(*top_sink, args["dilate"].as<double>());
top_sink = dilater;
}
if (args["flatten"] || (force_flatten && !args["no_flatten"])) {
flattener = new Flattener(*top_sink);
top_sink = flattener;
}
/* Because the C++ stdlib is bullshit */
auto id_match = [](string in, vector<string> &out) {
stringstream ss(in);
while (getline(ss, out.emplace_back(), ',')) {
}
out.pop_back();
};
IDElementSelector sel;
if (args["only_groups"])
id_match(args["only_groups"], sel.include);
if (args["exclude_groups"])
id_match(args["exclude_groups"], sel.exclude);
if (is_sexp && sexp_layer == "auto") {
sel.layers = &gerbolyze::kicad_default_layers;
}
string vectorizer = args["vectorizer"] ? args["vectorizer"] : "poisson-disc";
/* Check argument */
ImageVectorizer *vec = makeVectorizer(vectorizer);
if (!vec) {
cerr << "Unknown vectorizer \"" << vectorizer << "\"." << endl;
argagg::fmt_ostream fmt(cerr);
fmt << usage.str() << argparser;
return EXIT_FAILURE;
}
delete vec;
double min_feature_size = 0.1; /* mm */
if (args["min_feature_size"]) {
min_feature_size = args["min_feature_size"].as<double>();
}
string ending = "";
auto idx = in_f_name.rfind(".");
if (idx != string::npos) {
ending = in_f_name.substr(idx);
transform(ending.begin(), ending.end(), ending.begin(), [](unsigned char c){ return std::tolower(c); }); /* c++ yeah */
}
filesystem::path barf = { filesystem::temp_directory_path() /= (std::tmpnam(nullptr) + string(".svg")) };
filesystem::path frob = { filesystem::temp_directory_path() /= (std::tmpnam(nullptr) + string(".svg")) };
bool is_svg = args["force_svg"] || (ending == ".svg" && !args["force_png"]);
if (!is_svg) {
cerr << "writing bitmap into svg" << endl;
if (!args["size"]) {
cerr << "Error: --size must be given when using bitmap input." << endl;
argagg::fmt_ostream fmt(cerr);
fmt << usage.str() << argparser;
return EXIT_FAILURE;
}
string sz = args["size"].as<string>();
auto pos = sz.find_first_of("x*,");
if (pos == string::npos) {
cerr << "Error: --size must be of form 12.34x56.78" << endl;
argagg::fmt_ostream fmt(cerr);
fmt << usage.str() << argparser;
return EXIT_FAILURE;
}
string x_str = sz.substr(0, pos);
string y_str = sz.substr(pos+1);
double width = std::strtod(x_str.c_str(), nullptr);
double height = std::strtod(y_str.c_str(), nullptr);
if (width < 1 || height < 1) {
cerr << "Error: --size must be of form 12.34x56.78 and values must be positive floating-point numbers in mm" << endl;
argagg::fmt_ostream fmt(cerr);
fmt << usage.str() << argparser;
return EXIT_FAILURE;
}
ofstream svg(barf.c_str());
svg << "<svg width=\"" << width << "mm\" height=\"" << height << "mm\" viewBox=\"0 0 "
<< width << " " << height << "\" "
<< "xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">" << endl;
string par_attr = "none";
if (args["preserve_aspect_ratio"]) {
string aspect_ratio = args["preserve_aspect_ratio"].as<string>();
if (aspect_ratio == "meet") {
par_attr = "xMidYMid meet";
} else if (aspect_ratio == "slice") {
par_attr = "xMidYMid slice";
} else {
par_attr = aspect_ratio;
}
}
svg << "<image width=\"" << width << "\" height=\"" << height << "\" x=\"0\" y=\"0\" preserveAspectRatio=\""
<< par_attr << "\" xlink:href=\"data:image/png;base64,";
/* c++ has the best hacks */
std::ostringstream sstr;
sstr << in_f->rdbuf();
string le_data = sstr.str();
svg << base64_encode(le_data);
svg << "\"/>" << endl;
svg << "</svg>" << endl;
svg.close();
} else { /* svg file */
cerr << "copying svg input into temp svg" << endl;
/* c++ has the best hacks */
std::ostringstream sstr;
sstr << in_f->rdbuf();
ofstream tmp_out(barf.c_str());
tmp_out << sstr.str();
tmp_out.close();
}
if (args["skip_usvg"]) {
cerr << "skipping usvg" << endl;
frob = barf;
} else {
cerr << "calling usvg on " << barf << " and " << frob << endl;
const char *command_line[] = {"usvg", "--keep-named-groups", barf.c_str(), frob.c_str(), NULL};
struct subprocess_s subprocess;
int rc = subprocess_create(command_line, subprocess_option_inherit_environment, &subprocess);
if (rc) {
cerr << "Error calling usvg!" << endl;
return EXIT_FAILURE;
}
int usvg_rc = 0;
rc = subprocess_join(&subprocess, &usvg_rc);
if (rc) {
cerr << "Error calling usvg!" << endl;
return EXIT_FAILURE;
}
if (usvg_rc) {
cerr << "usvg returned an error code: " << usvg_rc << endl;
return EXIT_FAILURE;
}
rc = subprocess_destroy(&subprocess);
if (rc) {
cerr << "Error calling usvg!" << endl;
return EXIT_FAILURE;
}
}
VectorizerSelectorizer vec_sel(vectorizer, args["vectorizer_map"] ? args["vectorizer_map"] : "");
RenderSettings rset {
min_feature_size,
vec_sel,
};
SVGDocument doc;
cerr << "Loading temporary file " << frob << endl;
ifstream load_f(frob);
if (!doc.load(load_f)) {
cerr << "Error loading input file \"" << in_f_name << "\", exiting." << endl;
return EXIT_FAILURE;
}
doc.render(rset, *top_sink, &sel);
if (!is_svg) {
remove(frob.c_str());
remove(barf.c_str());
}
if (flattener) {
delete flattener;
}
if (dilater) {
delete dilater;
}
if (sink) {
delete sink;
}
return EXIT_SUCCESS;
}

View file

@ -0,0 +1,90 @@
/*
* This file is part of gerbolyze, a vector image preprocessing toolchain
* Copyright (C) 2021 Jan Sebastian Götte <gerbolyze@jaseg.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <cmath>
#include <algorithm>
#include <string>
#include <iostream>
#include <iomanip>
#include <gerbolyze.hpp>
#include <clipper.hpp>
#include <svg_import_defs.h>
#include <svg_geom.h>
#include "polylinecombine.hpp"
using namespace gerbolyze;
using namespace std;
void Dilater::header(d2p origin, d2p size) {
m_sink.header(origin, size);
}
void Dilater::footer() {
m_sink.footer();
}
Dilater &Dilater::operator<<(const LayerNameToken &layer_name) {
m_sink << layer_name;
return *this;
}
Dilater &Dilater::operator<<(GerberPolarityToken pol) {
m_current_polarity = pol;
m_sink << pol;
return *this;
}
Dilater &Dilater::operator<<(const Polygon &poly) {
static int i = 0;
cerr << "dilating poly " << i++ << endl;
cerr << "got poly of " << poly.size() << " nodes" << endl;
ClipperLib::Path poly_c;
for (auto &p : poly) {
poly_c.push_back({(ClipperLib::cInt)round(p[0] * clipper_scale), (ClipperLib::cInt)round(p[1] * clipper_scale)});
}
ClipperLib::ClipperOffset offx;
offx.ArcTolerance = 0.01 * clipper_scale; /* 10µm; TODO: Make this configurable */
offx.AddPath(poly_c, ClipperLib::jtRound, ClipperLib::etClosedPolygon);
double dilation = m_dilation;
if (m_current_polarity == GRB_POL_CLEAR) {
dilation = -dilation;
}
ClipperLib::PolyTree solution;
offx.Execute(solution, dilation * clipper_scale);
ClipperLib::Paths c_nice_polys;
dehole_polytree(solution, c_nice_polys);
for (auto &nice_poly : c_nice_polys) {
Polygon new_poly;
for (auto &p : nice_poly) {
new_poly.push_back({
(double)p.X / clipper_scale,
(double)p.Y / clipper_scale });
}
m_sink << new_poly;
}
return *this;
}

View file

@ -0,0 +1,187 @@
/*
* This file is part of gerbolyze, a vector image preprocessing toolchain
* Copyright (C) 2021 Jan Sebastian Götte <gerbolyze@jaseg.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <cmath>
#include <algorithm>
#include <string>
#include <iostream>
#include <iomanip>
#include <gerbolyze.hpp>
#include <svg_import_defs.h>
#include <svg_geom.h>
#include "polylinecombine.hpp"
using namespace gerbolyze;
using namespace std;
static void polygon_to_cavc (const Polygon &in, cavc::Polyline<double> &out) {
for (auto &p : in) {
out.addVertex(p[0], p[1], 0);
}
out.isClosed() = true; /* sic! */
}
static void cavc_to_polygon (const cavc::Polyline<double> &in, Polygon &out) {
for (auto &p : in.vertexes()) {
out.emplace_back(d2p{p.x(), p.y()});
}
}
namespace gerbolyze {
class Flattener_D {
public:
vector<cavc::Polyline<double>> dark_polys;
vector<cavc::Polyline<double>> clear_polys;
void add_dark_polygon(const Polygon &in) {
polygon_to_cavc(in, dark_polys.emplace_back());
}
void add_clear_polygon(const Polygon &in) {
polygon_to_cavc(in, clear_polys.emplace_back());
}
};
}
Flattener::Flattener(PolygonSink &sink) : m_sink(sink) {
d = new Flattener_D();
}
Flattener::~Flattener() {
delete d;
}
void Flattener::header(d2p origin, d2p size) {
m_sink.header(origin, size);
}
void Flattener::render_out_clear_polys() {
for (auto &sub : d->clear_polys) {
vector<cavc::Polyline<double>> new_dark_polys;
new_dark_polys.reserve(d->dark_polys.size());
for (cavc::Polyline<double> cavc_in : d->dark_polys) {
auto res = cavc::combinePolylines(cavc_in, sub, cavc::PlineCombineMode::Exclude);
if (res.subtracted.size() == 0) {
for (auto &rem : res.remaining) {
new_dark_polys.push_back(std::move(rem));
}
} else { /* custom one-hole deholing code */
assert (res.remaining.size() == 1);
assert (res.subtracted.size() == 1);
auto &rem = res.remaining[0];
auto &sub = res.subtracted[0];
auto bbox = getExtents(rem);
cavc::Polyline<double> quad;
quad.addVertex(bbox.xMin, bbox.yMin, 0);
if (sub.vertexes()[0].x() < sub.vertexes()[1].x()) {
quad.addVertex(sub.vertexes()[0]);
quad.addVertex(sub.vertexes()[1]);
} else {
quad.addVertex(sub.vertexes()[1]);
quad.addVertex(sub.vertexes()[0]);
}
quad.addVertex(bbox.xMax, bbox.yMin, 0);
quad.isClosed() = true; /* sic! */
auto res2 = cavc::combinePolylines(rem, quad, cavc::PlineCombineMode::Exclude);
assert (res2.subtracted.size() == 0);
for (auto &rem : res2.remaining) {
auto res3 = cavc::combinePolylines(rem, sub, cavc::PlineCombineMode::Exclude);
assert (res3.subtracted.size() == 0);
for (auto &p : res3.remaining) {
new_dark_polys.push_back(std::move(p));
}
}
auto res4 = cavc::combinePolylines(rem, quad, cavc::PlineCombineMode::Intersect);
assert (res4.subtracted.size() == 0);
for (auto &rem : res4.remaining) {
auto res5 = cavc::combinePolylines(rem, sub, cavc::PlineCombineMode::Exclude);
assert (res5.subtracted.size() == 0);
for (auto &p : res5.remaining) {
new_dark_polys.push_back(std::move(p));
}
}
}
}
d->dark_polys = std::move(new_dark_polys);
}
d->clear_polys.clear();
}
Flattener &Flattener::operator<<(GerberPolarityToken pol) {
if (m_current_polarity != pol) {
m_current_polarity = pol;
if (pol == GRB_POL_DARK) {
render_out_clear_polys();
}
}
return *this;
}
Flattener &Flattener::operator<<(const LayerNameToken &layer_name) {
flush_polys_to_sink();
m_sink << layer_name;
cerr << "Flattener forwarding layer name to sink: \"" << layer_name.m_name << "\"" << endl;
return *this;
}
Flattener &Flattener::operator<<(const Polygon &poly) {
if (m_current_polarity == GRB_POL_DARK) {
d->add_dark_polygon(poly);
} else { /* clear */
d->add_clear_polygon(poly);
render_out_clear_polys();
}
return *this;
}
void Flattener::flush_polys_to_sink() {
*this << GRB_POL_DARK; /* force render */
m_sink << GRB_POL_DARK;
for (auto &poly : d->dark_polys) {
Polygon poly_out;
for (auto &p : poly.vertexes()) {
poly_out.emplace_back(d2p{p.x(), p.y()});
}
m_sink << poly_out;
}
d->clear_polys.clear();
d->dark_polys.clear();
}
void Flattener::footer() {
flush_polys_to_sink();
m_sink.footer();
}

View file

@ -0,0 +1,99 @@
/*
* This file is part of gerbolyze, a vector image preprocessing toolchain
* Copyright (C) 2021 Jan Sebastian Götte <gerbolyze@jaseg.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <cmath>
#include <algorithm>
#include <string>
#include <iostream>
#include <iomanip>
#include <gerbolyze.hpp>
#include <svg_import_defs.h>
using namespace gerbolyze;
using namespace std;
SimpleGerberOutput::SimpleGerberOutput(ostream &out, bool only_polys, int digits_int, int digits_frac, d2p offset)
: StreamPolygonSink(out, only_polys),
m_digits_int(digits_int),
m_digits_frac(digits_frac),
m_offset(offset)
{
assert(1 <= digits_int && digits_int <= 9);
assert(0 <= digits_frac && digits_frac <= 9);
m_gerber_scale = round(pow(10, m_digits_frac));
}
void SimpleGerberOutput::header_impl(d2p origin, d2p size) {
m_offset[0] += origin[0];
m_offset[1] += origin[1];
m_width = size[0] - origin[0];
m_height = size[1] - origin[1];
if (pow(10, m_digits_int-1) < max(m_width, m_height)) {
cerr << "Warning: Input has bounding box too large for " << m_digits_int << "." << m_digits_frac << " gerber resolution!" << endl;
}
m_out << "%FSLAX" << m_digits_int << m_digits_frac << "Y" << m_digits_int << m_digits_frac << "*%" << endl;
m_out << "%MOMM*%" << endl;
m_out << "%LPD*%" << endl;
m_out << "G01*" << endl;
m_out << "%ADD10C,0.050000*%" << endl;
m_out << "D10*" << endl;
}
SimpleGerberOutput& SimpleGerberOutput::operator<<(GerberPolarityToken pol) {
if (pol == GRB_POL_DARK) {
m_out << "%LPD*%" << endl;
} else if (pol == GRB_POL_CLEAR) {
m_out << "%LPC*%" << endl;
} else {
assert(false);
}
return *this;
}
SimpleGerberOutput& SimpleGerberOutput::operator<<(const Polygon &poly) {
if (poly.size() < 3) {
cerr << "Warning: " << poly.size() << "-element polygon passed to SimpleGerberOutput" << endl;
return *this;
}
/* NOTE: Clipper and gerber both have different fixed-point scales. We get points in double mm. */
double x = round((poly[0][0] + m_offset[0]) * m_gerber_scale);
double y = round((m_height - poly[0][1] + m_offset[1]) * m_gerber_scale);
m_out << "G36*" << endl;
m_out << "X" << setw(m_digits_int + m_digits_frac) << setfill('0') << (long long int)x
<< "Y" << setw(m_digits_int + m_digits_frac) << setfill('0') << (long long int)y
<< "D02*" << endl;
m_out << "G01*" << endl;
for (size_t i=1; i<poly.size(); i++) {
double x = round((poly[i][0] + m_offset[0]) * m_gerber_scale);
double y = round((m_height - poly[i][1] + m_offset[1]) * m_gerber_scale);
m_out << "X" << setw(m_digits_int + m_digits_frac) << setfill('0') << (long long int)x
<< "Y" << setw(m_digits_int + m_digits_frac) << setfill('0') << (long long int)y
<< "D01*" << endl;
}
m_out << "G37*" << endl;
return *this;
}
void SimpleGerberOutput::footer_impl() {
m_out << "M02*" << endl;
}

View file

@ -0,0 +1,108 @@
/*
* This file is part of gerbolyze, a vector image preprocessing toolchain
* Copyright (C) 2021 Jan Sebastian Götte <gerbolyze@jaseg.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <cmath>
#include <algorithm>
#include <string>
#include <iostream>
#include <iomanip>
#include <gerbolyze.hpp>
#include <svg_import_defs.h>
#include <ctime>
using namespace gerbolyze;
using namespace std;
KicadSexpOutput::KicadSexpOutput(ostream &out, string mod_name, string layer, bool only_polys, string ref_text, string val_text, d2p ref_pos, d2p val_pos)
: StreamPolygonSink(out, only_polys),
m_mod_name(mod_name),
m_layer(layer == "auto" ? "unknown" : layer),
m_auto_layer(layer == "auto"),
m_val_text(val_text),
m_ref_pos(ref_pos),
m_val_pos(val_pos)
{
if (ref_text.empty()) {
m_ref_text = mod_name;
} else {
m_ref_text = ref_text;
}
}
void KicadSexpOutput::header_impl(d2p, d2p) {
auto tedit = std::time(0);
m_out << "(module " << m_mod_name << " (layer F.Cu) (tedit " << std::hex << std::setfill('0') << std::setw(8) << tedit << ")" << endl;
m_out << " (fp_text reference " << m_ref_text << " (at " << m_ref_pos[0] << " " << m_ref_pos[1] << ") (layer F.SilkS) hide" << endl;
m_out << " (effects (font (size 1 1) (thickness 0.15)))" << endl;
m_out << " )" << endl;
m_out << " (fp_text value " << m_val_text << " (at " << m_val_pos[0] << " " << m_val_pos[1] << ") (layer F.SilkS) hide" << endl;
m_out << " (effects (font (size 1 1) (thickness 0.15)))" << endl;
m_out << " )" << endl;
}
KicadSexpOutput &KicadSexpOutput::operator<<(GerberPolarityToken pol) {
if (pol == GRB_POL_CLEAR) {
cerr << "Warning: clear polarity not supported since KiCAD manages to have an even worse graphics model than gerber, except it can't excuse itself by its age..... -.-" << endl;
}
return *this;
}
KicadSexpOutput &KicadSexpOutput::operator<<(const LayerNameToken &layer_name) {
if (!m_auto_layer)
return *this;
cerr << "Setting S-Exp export layer to \"" << layer_name.m_name << "\"" << endl;
if (!layer_name.m_name.empty()) {
m_layer = layer_name.m_name;
} else {
m_layer = "unknown";
}
return *this;
}
KicadSexpOutput &KicadSexpOutput::operator<<(const Polygon &poly) {
if (m_auto_layer) {
if (std::find(m_export_layers->begin(), m_export_layers->end(), m_layer) == m_export_layers->end()) {
cerr << "Rejecting S-Exp export layer \"" << m_layer << "\"" << endl;
return *this;
}
}
if (poly.size() < 3) {
cerr << "Warning: " << poly.size() << "-element polygon passed to KicadSexpOutput" << endl;
return *this;
}
m_out << " (fp_poly (pts";
for (auto &p : poly) {
m_out << " (xy " << p[0] << " " << p[1] << ")";
}
m_out << ")";
m_out << " (layer " << m_layer << ") (width 0))" << endl;
return *this;
}
void KicadSexpOutput::footer_impl() {
m_out << ")" << endl;
}

View file

@ -0,0 +1,80 @@
/*
* This file is part of gerbolyze, a vector image preprocessing toolchain
* Copyright (C) 2021 Jan Sebastian Götte <gerbolyze@jaseg.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <cmath>
#include <algorithm>
#include <string>
#include <iostream>
#include <iomanip>
#include <gerbolyze.hpp>
#include <svg_import_defs.h>
using namespace gerbolyze;
using namespace std;
SimpleSVGOutput::SimpleSVGOutput(ostream &out, bool only_polys, int digits_frac, string dark_color, string clear_color)
: StreamPolygonSink(out, only_polys),
m_digits_frac(digits_frac),
m_dark_color(dark_color),
m_clear_color(clear_color),
m_current_color(dark_color)
{
}
void SimpleSVGOutput::header_impl(d2p origin, d2p size) {
m_offset[0] = origin[0];
m_offset[1] = origin[1];
m_out << "<svg width=\"" << size[0] << "mm\" height=\"" << size[1] << "mm\" viewBox=\"0 0 "
<< size[0] << " " << size[1] << "\" xmlns=\"http://www.w3.org/2000/svg\">" << endl;
}
SimpleSVGOutput &SimpleSVGOutput::operator<<(GerberPolarityToken pol) {
if (pol == GRB_POL_DARK) {
m_current_color = m_dark_color;
} else if (pol == GRB_POL_CLEAR) {
m_current_color = m_clear_color;
} else {
assert(false);
}
return *this;
}
SimpleSVGOutput &SimpleSVGOutput::operator<<(const Polygon &poly) {
if (poly.size() < 3) {
cerr << "Warning: " << poly.size() << "-element polygon passed to SimpleGerberOutput" << endl;
return *this;
}
m_out << "<path fill=\"" << m_current_color << "\" d=\"";
m_out << "M " << setprecision(m_digits_frac) << (poly[0][0] + m_offset[0])
<< " " << setprecision(m_digits_frac) << (poly[0][1] + m_offset[1]);
for (size_t i=1; i<poly.size(); i++) {
m_out << " L " << setprecision(m_digits_frac) << (poly[i][0] + m_offset[0])
<< " " << setprecision(m_digits_frac) << (poly[i][1] + m_offset[1]);
}
m_out << " Z";
m_out << "\"/>" << endl;
return *this;
}
void SimpleSVGOutput::footer_impl() {
m_out << "</svg>" << endl;
}

View file

@ -0,0 +1,119 @@
/*
* This file is part of gerbolyze, a vector image preprocessing toolchain
* Copyright (C) 2021 Jan Sebastian Götte <gerbolyze@jaseg.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "svg_color.h"
#include <assert.h>
#include <string>
#include <cmath>
using namespace gerbolyze;
using namespace std;
/* Map an SVG fill or stroke definition (color, but may also be a pattern) to a gerber color.
*
* This function handles transparency: Transparent SVG colors are mapped such that no gerber output is generated for
* them.
*/
enum gerber_color gerbolyze::svg_color_to_gerber(string color, string opacity, enum gerber_color default_val) {
float alpha = 1.0;
if (!opacity.empty() && opacity[0] != '\0') {
char *endptr = nullptr;
alpha = strtof(opacity.data(), &endptr);
assert(endptr);
assert(*endptr == '\0');
}
if (alpha < 0.5f) {
return GRB_NONE;
}
if (color.empty()) {
return default_val;
}
if (color == "none") {
return GRB_NONE;
}
if (color.rfind("url(#", 0) != string::npos) {
return GRB_PATTERN_FILL;
}
if (color.length() == 7 && color[0] == '#') {
HSVColor hsv(color);
if (hsv.v >= 0.5) {
return GRB_CLEAR;
}
}
return GRB_DARK;
}
gerbolyze::RGBColor::RGBColor(string hex) {
assert(hex[0] == '#');
char *endptr = nullptr;
const char *c = hex.data();
int rgb = strtol(c + 1, &endptr, 16);
assert(endptr);
assert(endptr == c + 7);
assert(*endptr == '\0');
r = ((rgb >> 16) & 0xff) / 255.0f;
g = ((rgb >> 8) & 0xff) / 255.0f;
b = ((rgb >> 0) & 0xff) / 255.0f;
};
gerbolyze::HSVColor::HSVColor(const RGBColor &color) {
float xmax = fmax(color.r, fmax(color.g, color.b));
float xmin = fmin(color.r, fmin(color.g, color.b));
float c = xmax - xmin;
v = xmax;
if (c == 0)
h = 0;
else if (v == color.r)
h = 1/3 * (0 + (color.g - color.b) / c);
else if (v == color.g)
h = 1/3 * (2 + (color.b - color.r) / c);
else // v == color.b
h = 1/3 * (4 + (color.r - color.g) / c);
s = (v == 0) ? 0 : (c/v);
}
/* Invert gerber color */
enum gerber_color gerbolyze::gerber_color_invert(enum gerber_color color) {
switch (color) {
case GRB_CLEAR: return GRB_DARK;
case GRB_DARK: return GRB_CLEAR;
default: return color; /* none, pattern */
}
}
/* Read node's fill attribute and convert it to a gerber color */
enum gerber_color gerbolyze::gerber_fill_color(const pugi::xml_node &node) {
return svg_color_to_gerber(node.attribute("fill").value(), node.attribute("fill-opacity").value(), GRB_DARK);
}
/* Read node's stroke attribute and convert it to a gerber color */
enum gerber_color gerbolyze::gerber_stroke_color(const pugi::xml_node &node) {
return svg_color_to_gerber(node.attribute("stroke").value(), node.attribute("stroke-opacity").value(), GRB_NONE);
}

View file

@ -0,0 +1,51 @@
/*
* This file is part of gerbolyze, a vector image preprocessing toolchain
* Copyright (C) 2021 Jan Sebastian Götte <gerbolyze@jaseg.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <pugixml.hpp>
namespace gerbolyze {
/* Enum that describes the color with which an SVG primite should be exported */
enum gerber_color {
GRB_NONE = 0,
GRB_CLEAR,
GRB_DARK,
GRB_PATTERN_FILL,
};
class RGBColor {
public:
float r, g, b;
RGBColor(std::string hex);
};
class HSVColor {
public:
float h, s, v;
HSVColor(const RGBColor &color);
};
enum gerber_color svg_color_to_gerber(std::string color, std::string opacity, enum gerber_color default_val);
enum gerber_color gerber_color_invert(enum gerber_color color);
enum gerber_color gerber_fill_color(const pugi::xml_node &node);
enum gerber_color gerber_stroke_color(const pugi::xml_node &node);
} /* namespace gerbolyze */

539
svg-flatten/src/svg_doc.cpp Normal file
View file

@ -0,0 +1,539 @@
/*
* This file is part of gerbolyze, a vector image preprocessing toolchain
* Copyright (C) 2021 Jan Sebastian Götte <gerbolyze@jaseg.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <fstream>
#include <gerbolyze.hpp>
#include "svg_import_defs.h"
#include "svg_color.h"
#include "svg_geom.h"
#include "svg_path.h"
#include "vec_core.h"
using namespace gerbolyze;
using namespace std;
using namespace ClipperLib;
gerbolyze::SVGDocument::~SVGDocument() {
if (cr)
cairo_destroy (cr);
if (surface)
cairo_surface_destroy (surface);
}
bool gerbolyze::SVGDocument::load(string filename, string debug_out_filename) {
ifstream in_f;
in_f.open(filename);
return in_f && load(in_f, debug_out_filename);
}
bool gerbolyze::SVGDocument::load(istream &in, string debug_out_filename) {
/* Load XML document */
auto res = svg_doc.load(in);
if (!res) {
cerr << "Cannot parse input file" << endl;
return false;
}
root_elem = svg_doc.child("svg");
if (!root_elem) {
cerr << "Input file is missing root <svg> element" << endl;
return false;
}
/* Set up the document's viewport transform */
istringstream vb_stream(root_elem.attribute("viewBox").value());
vb_stream >> vb_x >> vb_y >> vb_w >> vb_h;
cerr << "loaded viewbox: " << vb_x << ", " << vb_y << ", " << vb_w << ", " << vb_h << endl;
page_w = usvg_double_attr(root_elem, "width");
page_h = usvg_double_attr(root_elem, "height");
/* usvg resolves all units, but instead of outputting some reasonable absolute length like mm, it converts
* everything to px, which depends on usvg's DPI setting (--dpi).
*/
page_w_mm = page_w / assumed_usvg_dpi * 25.4;
page_h_mm = page_h / assumed_usvg_dpi * 25.4;
if (!(page_w_mm > 0.0 && page_h_mm > 0.0 && page_w_mm < 10e3 && page_h_mm < 10e3)) {
cerr << "Warning: Page has zero or negative size, or is larger than 10 x 10 meters! Parsed size: " << page_w << " x " << page_h << " millimeter" << endl;
}
if (fabs((vb_w / page_w) / (vb_h / page_h) - 1.0) > 0.001) {
cerr << "Warning: Document has different document unit scale in x and y direction! Output will likely be garbage!" << endl;
}
/* Get the one document defs element */
defs_node = root_elem.child("defs");
if (!defs_node) {
cerr << "Warning: Input file is missing <defs> node" << endl;
}
setup_debug_output(debug_out_filename);
setup_viewport_clip();
load_clips();
load_patterns();
_valid = true;
return true;
}
const Paths *gerbolyze::SVGDocument::lookup_clip_path(const pugi::xml_node &node) {
string id(usvg_id_url(node.attribute("clip-path").value()));
if (id.empty() || !clip_path_map.contains(id)) {
return nullptr;
}
return &clip_path_map[id];
}
Pattern *gerbolyze::SVGDocument::lookup_pattern(const string id) {
if (id.empty() || !pattern_map.contains(id)) {
return nullptr;
}
return &pattern_map[id];
};
/* Used to convert mm values from configuration such as the minimum feature size into document units. */
double gerbolyze::SVGDocument::mm_to_doc_units(double mm) const {
return mm * (vb_w / page_w_mm);
}
double gerbolyze::SVGDocument::doc_units_to_mm(double px) const {
return px / (vb_w / page_w_mm);
}
bool IDElementSelector::match(const pugi::xml_node &node, bool included, bool is_root) const {
string id = node.attribute("id").value();
if (is_root && layers) {
bool layer_match = std::find(layers->begin(), layers->end(), id) != layers->end();
if (!layer_match) {
cerr << "Rejecting layer \"" << id << "\"" << endl;
return false;
}
}
if (include.empty() && exclude.empty())
return true;
bool include_match = std::find(include.begin(), include.end(), id) != include.end();
bool exclude_match = std::find(exclude.begin(), exclude.end(), id) != exclude.end();
if (exclude_match || (!included && !include_match)) {
return false;
}
return true;
}
/* Recursively export all SVG elements in the given group. */
void gerbolyze::SVGDocument::export_svg_group(const RenderSettings &rset, const pugi::xml_node &group, Paths &parent_clip_path, const ElementSelector *sel, bool included, bool is_root) {
/* Enter the group's coordinate system */
cairo_save(cr);
apply_cairo_transform_from_svg(cr, group.attribute("transform").value());
/* Fetch clip path from global registry and transform it into document coordinates. */
Paths clip_path;
auto *lookup = lookup_clip_path(group);
if (!lookup) {
string id(usvg_id_url(group.attribute("clip-path").value()));
if (!id.empty()) {
cerr << "Warning: Cannot find clip path with ID \"" << group.attribute("clip-path").value() << "\" for group \"" << group.attribute("id").value() << "\"." << endl;
}
} else {
clip_path = *lookup;
}
transform_paths(cr, clip_path);
/* Clip against parent's clip path (both are now in document coordinates) */
if (!parent_clip_path.empty()) {
if (!clip_path.empty()) {
combine_clip_paths(parent_clip_path, clip_path, clip_path);
} else {
clip_path = parent_clip_path;
}
}
/* Iterate over the group's children, exporting them one by one. */
for (const auto &node : group.children()) {
if (sel && !sel->match(node, included, is_root))
continue;
string name(node.name());
if (name == "g") {
if (is_root) { /* Treat top-level groups as "layers" like inkscape does. */
cerr << "Forwarding layer name to sink: \"" << node.attribute("id").value() << "\"" << endl;
LayerNameToken tok { node.attribute("id").value() };
*polygon_sink << tok;
}
export_svg_group(rset, node, clip_path, sel, true);
if (is_root) {
LayerNameToken tok {""};
*polygon_sink << tok;
}
} else if (name == "path") {
export_svg_path(rset, node, clip_path);
} else if (name == "image") {
ImageVectorizer *vec = rset.m_vec_sel.select(node);
if (!vec) {
cerr << "Cannot resolve vectorizer for node \"" << node.attribute("id").value() << "\"" << endl;
continue;
}
double min_feature_size_px = mm_to_doc_units(rset.m_minimum_feature_size_mm);
vec->vectorize_image(cr, node, clip_path, viewport_matrix, *polygon_sink, min_feature_size_px);
delete vec;
} else if (name == "defs") {
/* ignore */
} else {
cerr << " Unexpected child: <" << node.name() << ">" << endl;
}
}
cairo_restore(cr);
}
/* Export an SVG path element to gerber. Apply patterns and clip on the fly. */
void gerbolyze::SVGDocument::export_svg_path(const RenderSettings &rset, const pugi::xml_node &node, Paths &clip_path) {
enum gerber_color fill_color = gerber_fill_color(node);
enum gerber_color stroke_color = gerber_stroke_color(node);
double stroke_width = usvg_double_attr(node, "stroke-width", /* default */ 1.0);
assert(stroke_width > 0.0);
enum ClipperLib::EndType end_type = clipper_end_type(node);
enum ClipperLib::JoinType join_type = clipper_join_type(node);
vector<double> dasharray;
parse_dasharray(node, dasharray);
/* TODO add stroke-miterlimit */
if (!fill_color && !stroke_color) { /* Ignore "transparent" paths */
return;
}
/* Load path from SVG path data and transform into document units. */
PolyTree ptree;
cairo_save(cr);
apply_cairo_transform_from_svg(cr, node.attribute("transform").value());
load_svg_path(cr, node, ptree);
cairo_restore (cr);
Paths open_paths, closed_paths;
OpenPathsFromPolyTree(ptree, open_paths);
ClosedPathsFromPolyTree(ptree, closed_paths);
/* Skip filling for transparent fills */
if (fill_color) {
/* Clip paths. Consider all paths closed for filling. */
if (!clip_path.empty()) {
Clipper c;
c.AddPaths(open_paths, ptSubject, /* closed */ false);
c.AddPaths(closed_paths, ptSubject, /* closed */ true);
c.AddPaths(clip_path, ptClip, /* closed */ true);
c.StrictlySimple(true);
/* fill rules are nonzero since both subject and clip have already been normalized by clipper. */
c.Execute(ctIntersection, ptree, pftNonZero, pftNonZero);
}
/* Call out to pattern tiler for pattern fills. The path becomes the clip here. */
if (fill_color == GRB_PATTERN_FILL) {
string fill_pattern_id = usvg_id_url(node.attribute("fill").value());
Pattern *pattern = lookup_pattern(fill_pattern_id);
if (!pattern) {
cerr << "Warning: Fill pattern with id \"" << fill_pattern_id << "\" not found." << endl;
} else {
Paths clip;
PolyTreeToPaths(ptree, clip);
pattern->tile(rset, clip);
}
} else { /* solid fill */
Paths f_polys;
/* Important for gerber spec compliance and also for reliable rendering results irrespective of board house
* and gerber viewer. */
dehole_polytree(ptree, f_polys);
/* Export SVG */
cairo_save(cr);
cairo_set_matrix(cr, &viewport_matrix);
cairo_new_path(cr);
ClipperLib::cairo::clipper_to_cairo(f_polys, cr, CAIRO_PRECISION, ClipperLib::cairo::tNone);
if (fill_color == GRB_DARK) {
cairo_set_source_rgba(cr, 0.0, 0.0, 1.0, dbg_fill_alpha);
} else { /* GRB_CLEAR */
cairo_set_source_rgba(cr, 1.0, 0.0, 0.0, dbg_fill_alpha);
}
cairo_fill (cr);
/* export gerber */
cairo_identity_matrix(cr);
for (const auto &poly : f_polys) {
vector<array<double, 2>> out;
for (const auto &p : poly)
out.push_back(std::array<double, 2>{
((double)p.X) / clipper_scale, ((double)p.Y) / clipper_scale
});
*polygon_sink << (fill_color == GRB_DARK ? GRB_POL_DARK : GRB_POL_CLEAR) << out;
}
cairo_restore(cr);
}
}
if (stroke_color && stroke_width > 0.0) {
ClipperOffset offx;
offx.ArcTolerance = 0.01 * clipper_scale; /* 10µm; TODO: Make this configurable */
/* For stroking we have to separately handle open and closed paths */
for (const auto &poly : closed_paths) {
if (poly.empty()) /* do we need this? */
continue;
/* Special case: A closed path becomes a number of open paths when it is dashed. */
if (dasharray.empty()) {
offx.AddPath(poly, join_type, etClosedLine);
} else {
Path poly_copy(poly);
poly_copy.push_back(poly[0]);
Paths out;
dash_path(poly_copy, out, dasharray);
offx.AddPaths(out, join_type, end_type);
}
}
for (const auto &poly : open_paths) {
Paths out;
dash_path(poly, out, dasharray);
offx.AddPaths(out, join_type, end_type);
}
/* Execute clipper offset operation to generate stroke outlines */
offx.Execute(ptree, 0.5 * stroke_width * clipper_scale);
/* Clip. Note that after the outline, all we have is closed paths as any open path's stroke outline is itself
* a closed path. */
if (!clip_path.empty()) {
Clipper c;
Paths outline_paths;
PolyTreeToPaths(ptree, outline_paths);
c.AddPaths(outline_paths, ptSubject, /* closed */ true);
c.AddPaths(clip_path, ptClip, /* closed */ true);
c.StrictlySimple(true);
/* fill rules are nonzero since both subject and clip have already been normalized by clipper. */
c.Execute(ctIntersection, ptree, pftNonZero, pftNonZero);
}
/* Call out to pattern tiler for pattern strokes. The stroke's outline becomes the clip here. */
if (stroke_color == GRB_PATTERN_FILL) {
string stroke_pattern_id = usvg_id_url(node.attribute("stroke").value());
Pattern *pattern = lookup_pattern(stroke_pattern_id);
if (!pattern) {
cerr << "Warning: Fill pattern with id \"" << stroke_pattern_id << "\" not found." << endl;
} else {
Paths clip;
PolyTreeToPaths(ptree, clip);
pattern->tile(rset, clip);
}
} else {
Paths s_polys;
dehole_polytree(ptree, s_polys);
/* Export debug svg */
cairo_save(cr);
cairo_set_matrix(cr, &viewport_matrix);
cairo_new_path(cr);
ClipperLib::cairo::clipper_to_cairo(s_polys, cr, CAIRO_PRECISION, ClipperLib::cairo::tNone);
if (stroke_color == GRB_DARK) {
cairo_set_source_rgba(cr, 0.0, 0.0, 1.0, dbg_stroke_alpha);
} else { /* GRB_CLEAR */
cairo_set_source_rgba(cr, 1.0, 0.0, 0.0, dbg_stroke_alpha);
}
cairo_fill (cr);
/* export gerber */
cairo_identity_matrix(cr);
for (const auto &poly : s_polys) {
vector<array<double, 2>> out;
for (const auto &p : poly)
out.push_back(std::array<double, 2>{
((double)p.X) / clipper_scale, ((double)p.Y) / clipper_scale
});
*polygon_sink << (stroke_color == GRB_DARK ? GRB_POL_DARK : GRB_POL_CLEAR) << out;
}
cairo_restore(cr);
}
}
}
void gerbolyze::SVGDocument::render(const RenderSettings &rset, PolygonSink &sink, const ElementSelector *sel) {
assert(_valid);
/* Export the actual SVG document to both SVG for debuggin and to gerber. We do this as we go, i.e. we immediately
* process each element to gerber as we encounter it instead of first rendering everything to a giant list of gerber
* primitives and then serializing those later. Exporting them on the fly saves a ton of memory and is much faster.
*/
polygon_sink = &sink;
sink.header({vb_x, vb_y}, {vb_w, vb_h});
ClipperLib::Clipper c;
c.AddPaths(vb_paths, ptSubject, /* closed */ true);
ClipperLib::IntRect bbox = c.GetBounds();
cerr << "document viewbox clip: bbox={" << bbox.left << ", " << bbox.top << "} - {" << bbox.right << ", " << bbox.bottom << "}" << endl;
export_svg_group(rset, root_elem, vb_paths, sel, false, true);
sink.footer();
}
void gerbolyze::SVGDocument::render_to_list(const RenderSettings &rset, vector<pair<Polygon, GerberPolarityToken>> &out, const ElementSelector *sel) {
LambdaPolygonSink sink([&out](const Polygon &poly, GerberPolarityToken pol) {
out.emplace_back(pair<Polygon, GerberPolarityToken>{poly, pol});
});
render(rset, sink, sel);
}
void gerbolyze::SVGDocument::setup_debug_output(string filename) {
/* Setup cairo to draw into a SVG surface (for debugging). For actual rendering, something like a recording surface
* would work fine, too. */
/* Cairo expects the SVG surface size to be given in pt (72.0 pt = 1.0 in = 25.4 mm) */
const char *fn = filename.empty() ? nullptr : filename.c_str();
assert (!cr);
assert (!surface);
surface = cairo_svg_surface_create(fn, page_w_mm / 25.4 * 72.0, page_h_mm / 25.4 * 72.0);
cr = cairo_create (surface);
/* usvg returns "pixels", cairo thinks we draw "points" at 72.0 pt per inch. */
cairo_scale(cr, page_w / vb_w * 72.0 / assumed_usvg_dpi, page_h / vb_h * 72.0 / assumed_usvg_dpi);
cairo_translate(cr, -vb_x, -vb_y);
/* Store viewport transform and reset cairo's active transform. We have to do this since we have to render out all
* gerber primitives in mm, not px and most gerber primitives we export pass through Cairo at some point.
*
* We manually apply this viewport transform every time for debugging we actually use Cairo to export SVG. */
cairo_get_matrix(cr, &viewport_matrix);
cairo_identity_matrix(cr);
cairo_set_line_width (cr, 0.1);
cairo_set_source_rgba (cr, 1.0, 0.0, 0.0, 1.0);
}
void gerbolyze::SVGDocument::setup_viewport_clip() {
/* Set up view port clip path */
Path vb_path;
for (auto &elem : vector<pair<double, double>> {{vb_x, vb_y}, {vb_x+vb_w, vb_y}, {vb_x+vb_w, vb_y+vb_h}, {vb_x, vb_y+vb_h}}) {
double x = elem.first, y = elem.second;
vb_path.push_back({ (cInt)round(x * clipper_scale), (cInt)round(y * clipper_scale) });
}
vb_paths.push_back(vb_path);
ClipperLib::Clipper c;
c.AddPaths(vb_paths, ptSubject, /* closed */ true);
}
void gerbolyze::SVGDocument::load_patterns() {
/* Set up document-wide pattern registry. Load patterns from <defs> node. */
for (const auto &node : defs_node.children("pattern")) {
pattern_map.emplace(std::piecewise_construct, std::forward_as_tuple(node.attribute("id").value()), std::forward_as_tuple(node, *this));
}
}
void gerbolyze::SVGDocument::load_clips() {
/* Set up document-wide clip path registry: Extract clip path definitions from <defs> element */
for (const auto &node : defs_node.children("clipPath")) {
cairo_save(cr);
apply_cairo_transform_from_svg(cr, node.attribute("transform").value());
string meta_clip_path_id(usvg_id_url(node.attribute("clip-path").value()));
Clipper c;
/* The clipPath node can only contain <path> children. usvg converts all geometric objects (rect etc.) to
* <path>s. Raster images are invalid inside a clip path. usvg removes all groups that are not relevant to
* rendering, and the only way a group might stay is if it affects rasterization (e.g. through mask, clipPath).
*/
for (const auto &child : node.children("path")) {
PolyTree ptree;
cairo_save(cr);
/* TODO: we currently only support clipPathUnits="userSpaceOnUse", not "objectBoundingBox". */
apply_cairo_transform_from_svg(cr, child.attribute("transform").value());
load_svg_path(cr, child, ptree);
cairo_restore (cr);
Paths paths;
PolyTreeToPaths(ptree, paths);
c.AddPaths(paths, ptSubject, /* closed */ false);
}
/* Support clip paths that themselves have clip paths */
if (!meta_clip_path_id.empty()) {
if (clip_path_map.contains(meta_clip_path_id)) {
/* all clip paths must be closed */
c.AddPaths(clip_path_map[meta_clip_path_id], ptClip, /* closed */ true);
} else {
cerr << "Warning: Cannot find clip path with ID \"" << meta_clip_path_id << "\", ignoring." << endl;
}
}
PolyTree ptree;
c.StrictlySimple(true);
/* This unions all child <path>s together and at the same time applies any meta clip path. */
/* The fill rules are both nonzero since both subject and clip have already been normalized by clipper. */
c.Execute(ctUnion, ptree, pftNonZero, pftNonZero);
/* Insert into document clip path map */
PolyTreeToPaths(ptree, clip_path_map[node.attribute("id").value()]);
cairo_restore(cr);
}
}
/* Note: These values come from KiCAD's common/lset.cpp. KiCAD uses *multiple different names* for the same layer in
* different places, and not all of them are stable. Sometimes, these names change without notice. If this list isn't
* up-to-date, it's not my fault. Still, please file an issue. */
const std::vector<std::string> gerbolyze::kicad_default_layers ({
/* Copper */
"F.Cu",
"In1.Cu", "In2.Cu", "In3.Cu", "In4.Cu", "In5.Cu", "In6.Cu", "In7.Cu", "In8.Cu",
"In9.Cu", "In10.Cu", "In11.Cu", "In12.Cu", "In13.Cu", "In14.Cu", "In15.Cu", "In16.Cu",
"In17.Cu", "In18.Cu", "In19.Cu", "In20.Cu", "In21.Cu", "In22.Cu", "In23.Cu",
"In24.Cu", "In25.Cu", "In26.Cu", "In27.Cu", "In28.Cu", "In29.Cu", "In30.Cu",
"B.Cu",
/* Technical layers */
"B.Adhes", "F.Adhes",
"B.Paste", "F.Paste",
"B.SilkS", "F.SilkS",
"B.Mask", "F.Mask",
/* User layers */
"Dwgs.User",
"Cmts.User",
"Eco1.User", "Eco2.User",
"Edge.Cuts",
"Margin",
/* Footprint layers */
"F.CrtYd", "B.CrtYd",
"F.Fab", "B.Fab",
/* Layers for user scripting etc. */
"User.1", "User.2", "User.3", "User.4", "User.5", "User.6", "User.7", "User.8", "User.9",
});

View file

@ -0,0 +1,182 @@
/*
* This file is part of gerbolyze, a vector image preprocessing toolchain
* Copyright (C) 2021 Jan Sebastian Götte <gerbolyze@jaseg.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "svg_geom.h"
#include <cmath>
#include <string>
#include <sstream>
#include <queue>
#include <assert.h>
#include <cairo.h>
#include "svg_import_defs.h"
using namespace ClipperLib;
using namespace std;
/* Get bounding box of a Clipper Paths */
IntRect gerbolyze::get_paths_bounds(const Paths &paths) {
if (paths.empty()) {
return {0, 0, 0, 0};
}
if (paths[0].empty()) {
return {0, 0, 0, 0};
}
IntPoint p0 = paths[0][0];
cInt x0=p0.X, y0=p0.Y, x1=p0.X, y1=p0.Y;
for (const Path &p : paths) {
for (const IntPoint ip : p) {
if (ip.X < x0)
x0 = ip.X;
if (ip.Y < y0)
y0 = ip.Y;
if (ip.X > x1)
x1 = ip.X;
if (ip.Y > y1)
y1 = ip.Y;
}
}
return {x0, y0, x1, y1};
}
enum ClipperLib::PolyFillType gerbolyze::clipper_fill_rule(const pugi::xml_node &node) {
string val(node.attribute("fill-rule").value());
if (val == "evenodd")
return ClipperLib::pftEvenOdd;
else
return ClipperLib::pftNonZero; /* default */
}
enum ClipperLib::EndType gerbolyze::clipper_end_type(const pugi::xml_node &node) {
string val(node.attribute("stroke-linecap").value());
if (val == "round")
return ClipperLib::etOpenRound;
if (val == "square")
return ClipperLib::etOpenSquare;
return ClipperLib::etOpenButt;
}
enum ClipperLib::JoinType gerbolyze::clipper_join_type(const pugi::xml_node &node) {
string val(node.attribute("stroke-linejoin").value());
if (val == "round")
return ClipperLib::jtRound;
if (val == "bevel")
return ClipperLib::jtSquare;
return ClipperLib::jtMiter;
}
static void dehole_polytree_worker(PolyNode &ptree, Paths &out, queue<PolyTree> &todo) {
for (int i=0; i<ptree.ChildCount(); i++) {
PolyNode *nod = ptree.Childs[i];
assert(nod);
assert(!nod->IsHole());
/* First, recursively process inner polygons. */
for (int j=0; j<nod->ChildCount(); j++) {
PolyNode *child = nod->Childs[j];
assert(child);
assert(child->IsHole());
if (child->ChildCount() > 0) {
dehole_polytree_worker(*child, out, todo);
}
}
if (nod->ChildCount() == 0) {
out.push_back(nod->Contour);
} else {
/* Do not add children's children, those were handled in the recursive call above */
Clipper c;
c.AddPath(nod->Contour, ptSubject, /* closed= */ true);
for (int k=0; k<nod->ChildCount(); k++) {
c.AddPath(nod->Childs[k]->Contour, ptSubject, /* closed= */ true);
}
/* Find a viable cut: Cut from top-left bounding box corner, through two subsequent points on the hole
* outline and to top-right bbox corner. */
IntRect bbox = c.GetBounds();
Path tri = { { bbox.left, bbox.top }, nod->Childs[0]->Contour[0], nod->Childs[0]->Contour[1], { bbox.right, bbox.top } };
c.AddPath(tri, ptClip, true);
c.StrictlySimple(true);
/* Execute twice, once for intersection fragment and once for difference fragment. Note that this will yield
* at least two, but possibly more polygons. */
c.Execute(ctDifference, todo.emplace(), pftNonZero);
c.Execute(ctIntersection, todo.emplace(), pftNonZero);
}
}
}
/* Take a Clipper polytree, i.e. a description of a set of polygons, their holes and their inner polygons, and remove
* all holes from it. We remove holes by splitting each polygon that has a hole into two or more pieces so that the hole
* is no more. These pieces perfectly fit each other so there is no visual or functional difference.
*/
void gerbolyze::dehole_polytree(PolyTree &ptree, Paths &out) {
queue<PolyTree> todo;
dehole_polytree_worker(ptree, out, todo);
while (!todo.empty()) {
dehole_polytree_worker(todo.front(), out, todo);
todo.pop();
}
}
/* Intersect two clip paths. Both must share a coordinate system. */
void gerbolyze::combine_clip_paths(Paths &in_a, Paths &in_b, Paths &out) {
Clipper c;
c.StrictlySimple(true);
c.AddPaths(in_a, ptClip, /* closed */ true);
c.AddPaths(in_b, ptSubject, /* closed */ true);
/* Nonzero fill since both input clip paths must already have been preprocessed by clipper. */
c.Execute(ctIntersection, out, pftNonZero);
}
/* Transform given clipper paths under the given cairo transform. If no transform is given, use cairo's current
* user-to-device transform. */
void gerbolyze::transform_paths(cairo_t *cr, Paths &paths, cairo_matrix_t *mat) {
cairo_save(cr);
if (mat != nullptr) {
cairo_set_matrix(cr, mat);
}
for (Path &p : paths) {
transform(p.begin(), p.end(), p.begin(),
[cr](IntPoint p) -> IntPoint {
double x = p.X / clipper_scale, y = p.Y / clipper_scale;
cairo_user_to_device(cr, &x, &y);
return { (cInt)round(x * clipper_scale), (cInt)round(y * clipper_scale) };
});
}
cairo_restore(cr);
}

View file

@ -0,0 +1,36 @@
/*
* This file is part of gerbolyze, a vector image preprocessing toolchain
* Copyright (C) 2021 Jan Sebastian Götte <gerbolyze@jaseg.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <cairo.h>
#include <clipper.hpp>
#include <pugixml.hpp>
namespace gerbolyze {
ClipperLib::IntRect get_paths_bounds(const ClipperLib::Paths &paths);
enum ClipperLib::PolyFillType clipper_fill_rule(const pugi::xml_node &node);
enum ClipperLib::EndType clipper_end_type(const pugi::xml_node &node);
enum ClipperLib::JoinType clipper_join_type(const pugi::xml_node &node);
void dehole_polytree(ClipperLib::PolyTree &ptree, ClipperLib::Paths &out);
void combine_clip_paths(ClipperLib::Paths &in_a, ClipperLib::Paths &in_b, ClipperLib::Paths &out);
void transform_paths(cairo_t *cr, ClipperLib::Paths &paths, cairo_matrix_t *mat=nullptr);
} /* namespace gerbolyze */

View file

@ -0,0 +1,49 @@
/*
* This program source code file is part of KICAD, a free EDA CAD application.
*
* Copyright (C) 2016 CERN
* @author Janito V. Ferreira Filho <janito.vff@gmail.com>
* Copyright (C) 2018-2019 KiCad Developers, see AUTHORS.txt for contributors.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, you may find one here:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
* or you may search the http://www.gnu.org website for the version 2 license,
* or you may write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#ifndef SVG_IMPORT_DEFS_H
#define SVG_IMPORT_DEFS_H
#include <cfloat>
template <typename T>
constexpr T ipow(T num, unsigned int pow)
{
return (pow >= sizeof(unsigned int)*8) ? 0 :
pow == 0 ? 1 : num * ipow(num, pow-1);
}
constexpr int CAIRO_PRECISION = 7;
constexpr double clipper_scale = ipow(10.0, CAIRO_PRECISION);
#define JC_VORONOI_IMPLEMENTATION
#define JCV_REAL_TYPE double
#define JCV_ATAN2 atan2
#define JCV_SQRT sqrt
#define JCV_FLT_MAX DBL_MAX
#define JCV_PI 3.141592653589793115997963468544185161590576171875
//define JCV_EDGE_INTERSECT_THRESHOLD 1.0e-10F
#endif /* SVG_IMPORT_DEFS_H */

View file

@ -0,0 +1,123 @@
/*
* This file is part of gerbolyze, a vector image preprocessing toolchain
* Copyright (C) 2021 Jan Sebastian Götte <gerbolyze@jaseg.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <cmath>
#include "base64.h"
#include "svg_import_util.h"
using namespace std;
void gerbolyze::print_matrix(cairo_t *cr, bool print_examples) {
cairo_matrix_t mat;
cairo_get_matrix(cr, &mat);
cerr << " xform matrix = { xx=" << mat.xx << ", yx=" << mat.yx << ", xy=" << mat.xy << ", yy=" << mat.yy << ", x0=" << mat.x0 << ", y0=" << mat.y0 << " }" << endl;
if (print_examples) {
double x=0, y=0;
cairo_user_to_device(cr, &x, &y);
cerr << " (0, 0) -> (" << x << ", " << y << ")" << endl;
x = 1, y = 0;
cairo_user_to_device(cr, &x, &y);
cerr << " (1, 0) -> (" << x << ", " << y << ")" << endl;
x = 0, y = 1;
cairo_user_to_device(cr, &x, &y);
cerr << " (0, 1) -> (" << x << ", " << y << ")" << endl;
x = 1, y = 1;
cairo_user_to_device(cr, &x, &y);
cerr << " (1, 1) -> (" << x << ", " << y << ")" << endl;
}
}
/* Read a double value formatted like usvg formats doubles from an SVG attribute */
double gerbolyze::usvg_double_attr(const pugi::xml_node &node, const char *attr, double default_value) {
const auto *val = node.attribute(attr).value();
if (*val == '\0')
return default_value;
return atof(val);
}
/* Read an url from an usvg attribute */
string gerbolyze::usvg_id_url(string attr) {
if (attr.rfind("url(#", 0) == string::npos)
return string();
attr = attr.substr(strlen("url(#"));
attr = attr.substr(0, attr.size()-1);
return attr;
}
gerbolyze::RelativeUnits gerbolyze::map_str_to_units(string str, gerbolyze::RelativeUnits default_val) {
if (str == "objectBoundingBox")
return SVG_ObjectBoundingBox;
else if (str == "userSpaceOnUse")
return SVG_UserSpaceOnUse;
return default_val;
}
void gerbolyze::load_cairo_matrix_from_svg(const string &transform, cairo_matrix_t &mat) {
if (transform.empty()) {
cairo_matrix_init_identity(&mat);
return;
}
string start("matrix(");
assert(transform.substr(0, start.length()) == start);
assert(transform.back() == ')');
const string &foo = transform.substr(start.length(), transform.length());
const string &bar = foo.substr(0, foo.length() - 1);
istringstream xform(bar);
double a, c, e,
b, d, f;
xform >> a >> b >> c >> d >> e >> f;
assert(!xform.fail());
cairo_matrix_init(&mat, a, b, c, d, e, f);
}
void gerbolyze::apply_cairo_transform_from_svg(cairo_t *cr, const string &transform) {
cairo_matrix_t mat;
load_cairo_matrix_from_svg(transform, mat);
cairo_transform(cr, &mat); /* or cairo_transform? */
}
/* Cf. https://tools.ietf.org/html/rfc2397 */
string gerbolyze::parse_data_iri(const string &data_url) {
if (data_url.rfind("data:", 0) == string::npos) /* check if url starts with "data:" */
return string();
size_t foo = data_url.find("base64,");
if (foo == string::npos) /* check if this is actually a data URL */
return string();
size_t b64_begin = data_url.find_first_not_of(" ", foo + strlen("base64,"));
assert(b64_begin != string::npos);
return base64_decode(data_url.substr(b64_begin));
}
/* for debug svg output */
void gerbolyze::apply_viewport_matrix(cairo_t *cr, cairo_matrix_t &viewport_matrix) {
/* Multiply viewport matrix *from the left*, i.e. as if it had been applied *before* the currently set matrix. */
cairo_matrix_t old_matrix;
cairo_get_matrix(cr, &old_matrix);
cairo_set_matrix(cr, &viewport_matrix);
cairo_transform(cr, &old_matrix);
}

View file

@ -0,0 +1,61 @@
/*
* This file is part of gerbolyze, a vector image preprocessing toolchain
* Copyright (C) 2021 Jan Sebastian Götte <gerbolyze@jaseg.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <math.h>
#include <cmath>
#include <stdlib.h>
#include <assert.h>
#include <limits>
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <regex>
#include <pango/pangocairo.h>
#include <cairo-svg.h>
#include <clipper.hpp>
#include "cairo_clipper.hpp"
#include <pugixml.hpp>
#include "svg_import_defs.h"
namespace gerbolyze {
/* Coordinate system selection for things like "patternContentUnits" */
enum RelativeUnits {
SVG_UnknownUnits = 0,
SVG_UserSpaceOnUse,
SVG_ObjectBoundingBox,
};
void print_matrix(cairo_t *cr, bool print_examples=false);
double usvg_double_attr(const pugi::xml_node &node, const char *attr, double default_value=0.0);
std::string usvg_id_url(std::string attr);
RelativeUnits map_str_to_units(std::string str, RelativeUnits default_val=SVG_UnknownUnits);
void load_cairo_matrix_from_svg(const std::string &transform, cairo_matrix_t &mat);
void apply_cairo_transform_from_svg(cairo_t *cr, const std::string &transform);
std::string parse_data_iri(const std::string &data_url);
void apply_viewport_matrix(cairo_t *cr, cairo_matrix_t &viewport_matrix);
} /* namespace gerbolyze */

View file

@ -0,0 +1,213 @@
/*
* This file is part of gerbolyze, a vector image preprocessing toolchain
* Copyright (C) 2021 Jan Sebastian Götte <gerbolyze@jaseg.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <cmath>
#include <assert.h>
#include <iostream>
#include <sstream>
#include "cairo_clipper.hpp"
#include "svg_import_defs.h"
#include "svg_path.h"
using namespace std;
static void clipper_add_cairo_path(cairo_t *cr, ClipperLib::Clipper &c, bool closed) {
ClipperLib::Paths in_poly;
ClipperLib::cairo::cairo_to_clipper(cr, in_poly, CAIRO_PRECISION, ClipperLib::cairo::tNone);
c.AddPaths(in_poly, ClipperLib::ptSubject, closed);
}
static void path_to_clipper_via_cairo(cairo_t *cr, ClipperLib::Clipper &c, const pugi::char_t *path_data) {
istringstream d(path_data);
string cmd;
double x, y, c1x, c1y, c2x, c2y;
bool first = true;
bool path_is_empty = true;
while (!d.eof()) {
d >> cmd;
assert (!d.fail());
assert(!first || cmd == "M");
if (cmd == "Z") { /* Close path */
cairo_close_path(cr);
clipper_add_cairo_path(cr, c, /* closed= */ true);
cairo_new_path(cr);
path_is_empty = true;
} else if (cmd == "M") { /* Move to */
d >> x >> y;
/* We need to transform all points ourselves here, and cannot use the transform feature of cairo_to_clipper:
* Our transform may contain offsets, and clipper only passes its data into cairo's transform functions
* after scaling up to its internal fixed-point ints, but it does not scale the transform accordingly. This
* means a scale/rotation we set before calling clipper works out fine, but translations get lost as they
* get scaled by something like 1e-6.
*/
cairo_user_to_device(cr, &x, &y);
assert (!d.fail());
if (!first)
clipper_add_cairo_path(cr, c, /* closed= */ false);
cairo_new_path (cr);
path_is_empty = true;
cairo_move_to(cr, x, y);
} else if (cmd == "L") { /* Line to */
d >> x >> y;
cairo_user_to_device(cr, &x, &y);
assert (!d.fail());
cairo_line_to(cr, x, y);
path_is_empty = false;
} else { /* Curve to */
assert(cmd == "C");
d >> c1x >> c1y; /* first control point */
cairo_user_to_device(cr, &c1x, &c1y);
d >> c2x >> c2y; /* second control point */
cairo_user_to_device(cr, &c2x, &c2y);
d >> x >> y; /* end point */
cairo_user_to_device(cr, &x, &y);
assert (!d.fail());
cairo_curve_to(cr, c1x, c1y, c2x, c2y, x, y);
path_is_empty = false;
}
first = false;
}
if (!path_is_empty) {
cairo_close_path(cr);
clipper_add_cairo_path(cr, c, /* closed= */ false);
}
}
void gerbolyze::load_svg_path(cairo_t *cr, const pugi::xml_node &node, ClipperLib::PolyTree &ptree) {
auto *path_data = node.attribute("d").value();
auto fill_rule = clipper_fill_rule(node);
/* For open paths, clipper does not correctly remove self-intersections. Thus, we pass everything into
* clipper twice: Once with all paths set to "closed" to compute fill areas, and once with correct
* open/closed properties for stroke offsetting. */
cairo_set_tolerance (cr, 0.1); /* FIXME make configurable, scale properly for units */
cairo_set_fill_rule(cr, CAIRO_FILL_RULE_WINDING);
ClipperLib::Clipper c;
c.StrictlySimple(true);
path_to_clipper_via_cairo(cr, c, path_data);
/* We canont clip the polygon here since that would produce incorrect results for our stroke. */
c.Execute(ClipperLib::ctUnion, ptree, fill_rule, ClipperLib::pftNonZero);
}
void gerbolyze::parse_dasharray(const pugi::xml_node &node, vector<double> &out) {
out.clear();
string val(node.attribute("stroke-dasharray").value());
if (val.empty() || val == "none")
return;
istringstream desc_stream(val);
while (!desc_stream.eof()) {
/* usvg says the array only contains unitless (px) values. I don't know what resvg does with percentages inside
* dash arrays. We just assume everything is a unitless number here. In case usvg passes through percentages,
* well, bad luck. They are a kind of weird thing inside a dash array in the first place. */
double d;
desc_stream >> d;
out.push_back(d);
}
assert(out.size() % 2 == 0); /* according to resvg spec */
}
/* Take a Clipper path in clipper-scaled document units, and apply the given SVG dash array to it. Do this by walking
* the path from start to end while emitting dashes. */
void gerbolyze::dash_path(const ClipperLib::Path &in, ClipperLib::Paths &out, const vector<double> dasharray, double dash_offset) {
out.clear();
if (dasharray.empty() || in.size() < 2) {
out.push_back(in);
return;
}
size_t dash_idx = 0;
size_t num_dashes = dasharray.size();
while (dash_offset > dasharray[dash_idx]) {
dash_offset -= dasharray[dash_idx];
dash_idx = (dash_idx + 1) % num_dashes;
}
double dash_remaining = dasharray[dash_idx] - dash_offset;
ClipperLib::Path current_dash;
current_dash.push_back(in[0]);
double dbg_total_len = 0.0;
for (size_t i=1; i<in.size(); i++) {
ClipperLib::IntPoint p1(in[i-1]), p2(in[i]);
double x1 = p1.X / clipper_scale, y1 = p1.Y / clipper_scale, x2 = p2.X / clipper_scale, y2 = p2.Y / clipper_scale;
double dist = sqrt(pow(x2-x1, 2) + pow(y2-y1, 2));
dbg_total_len += dist;
if (dist < dash_remaining) {
/* dash extends beyond this segment, append this segment and continue. */
dash_remaining -= dist;
current_dash.push_back(p2);
} else {
/* dash started in some previous segment ends in this segment */
double dash_frac = dash_remaining/dist;
double x = x1 + (x2 - x1) * dash_frac,
y = y1 + (y2 - y1) * dash_frac;
ClipperLib::IntPoint intermediate {(ClipperLib::cInt)round(x * clipper_scale), (ClipperLib::cInt)round(y * clipper_scale)};
/* end this dash */
current_dash.push_back(intermediate);
if (dash_idx%2 == 0) { /* dash */
out.push_back(current_dash);
} /* else space */
dash_idx = (dash_idx + 1) % num_dashes;
double offset = dash_remaining;
/* start next dash */
current_dash.clear();
current_dash.push_back(intermediate);
/* handle case where multiple dashes fit into this segment */
while ((dist - offset) > dasharray[dash_idx]) {
offset += dasharray[dash_idx];
double dash_frac = offset/dist;
double x = x1 + (x2 - x1) * dash_frac,
y = y1 + (y2 - y1) * dash_frac;
ClipperLib::IntPoint intermediate {(ClipperLib::cInt)round(x * clipper_scale), (ClipperLib::cInt)round(y * clipper_scale)};
/* end this dash */
current_dash.push_back(intermediate);
if (dash_idx%2 == 0) { /* dash */
out.push_back(current_dash);
} /* else space */
dash_idx = (dash_idx + 1) % num_dashes;
/* start next dash */
current_dash.clear();
current_dash.push_back(intermediate);
}
dash_remaining = dasharray[dash_idx] - (dist - offset);
current_dash.push_back(p2);
}
}
}

View file

@ -0,0 +1,30 @@
/*
* This file is part of gerbolyze, a vector image preprocessing toolchain
* Copyright (C) 2021 Jan Sebastian Götte <gerbolyze@jaseg.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <vector>
#include <cairo.h>
#include "svg_geom.h"
namespace gerbolyze {
void load_svg_path(cairo_t *cr, const pugi::xml_node &node, ClipperLib::PolyTree &ptree);
void parse_dasharray(const pugi::xml_node &node, std::vector<double> &out);
void dash_path(const ClipperLib::Path &in, ClipperLib::Paths &out, const std::vector<double> dasharray, double dash_offset=0.0);
}

View file

@ -0,0 +1,113 @@
/*
* This file is part of gerbolyze, a vector image preprocessing toolchain
* Copyright (C) 2021 Jan Sebastian Götte <gerbolyze@jaseg.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <assert.h>
#include "svg_import_util.h"
#include "svg_pattern.h"
#include "svg_import_defs.h"
#include "svg_geom.h"
#include <gerbolyze.hpp>
using namespace std;
gerbolyze::Pattern::Pattern(const pugi::xml_node &node, SVGDocument &doc) : _node(node), doc(&doc) {
/* Read pattern attributes from SVG node */
cerr << "creating pattern for node with id \"" << node.attribute("id").value() << "\"" << endl;
x = usvg_double_attr(node, "x");
y = usvg_double_attr(node, "y");
w = usvg_double_attr(node, "width");
h = usvg_double_attr(node, "height");
patternTransform = node.attribute("patternTransform").value();
string vb_s(node.attribute("viewBox").value());
has_vb = !vb_s.empty();
if (has_vb) {
istringstream vb_stream(vb_s);
vb_stream >> vb_x >> vb_y >> vb_w >> vb_h;
}
patternUnits = map_str_to_units(node.attribute("patternUnits").value(), SVG_ObjectBoundingBox);
patternContentUnits = map_str_to_units(node.attribute("patternContentUnits").value(), SVG_UserSpaceOnUse);
}
/* Tile pattern into gerber. Note that this function may be called several times in case the pattern is
* referenced from multiple places, so we must not clobber any of the object's state. */
void gerbolyze::Pattern::tile (const gerbolyze::RenderSettings &rset, ClipperLib::Paths &clip) {
assert(doc);
cairo_t *cr = doc->cairo();
assert(cr);
cairo_save(cr);
/* Transform x, y, w, h from pattern coordinate space into parent coordinates by applying the inverse
* patternTransform. This is necessary so we iterate over the correct bounds when tiling below */
cairo_matrix_t mat;
load_cairo_matrix_from_svg(patternTransform, mat);
if (cairo_matrix_invert(&mat) != CAIRO_STATUS_SUCCESS) {
cerr << "Cannot invert patternTransform matrix on pattern \"" << _node.attribute("id").value() << "\"." << endl;
cairo_restore(cr);
}
double inst_x = x, inst_y = y, inst_w = w, inst_h = h;
cairo_user_to_device(cr, &inst_x, &inst_y);
cairo_user_to_device_distance(cr, &inst_w, &inst_h);
cairo_restore(cr);
ClipperLib::IntRect clip_bounds = get_paths_bounds(clip);
double bx = clip_bounds.left / clipper_scale;
double by = clip_bounds.top / clipper_scale;
double bw = (clip_bounds.right - clip_bounds.left) / clipper_scale;
double bh = (clip_bounds.bottom - clip_bounds.top) / clipper_scale;
if (patternUnits == SVG_ObjectBoundingBox) {
inst_x *= bw;
inst_y *= bh;
inst_w *= bw;
inst_h *= bh;
}
/* Switch to pattern coordinates */
cairo_save(cr);
cairo_translate(cr, bx, by);
apply_cairo_transform_from_svg(cr, patternTransform);
/* Iterate over all pattern tiles in pattern coordinates */
for (double inst_off_x = fmod(inst_x, inst_w) - inst_w;
inst_off_x < bw + inst_w;
inst_off_x += inst_w) {
for (double inst_off_y = fmod(inst_y, inst_h) - inst_h;
inst_off_y < bh + inst_h;
inst_off_y += inst_h) {
cairo_save(cr);
/* Change into this individual tile's coordinate system */
cairo_translate(cr, inst_off_x, inst_off_y);
if (has_vb) {
cairo_translate(cr, vb_x, vb_y);
cairo_scale(cr, inst_w / vb_w, inst_h / vb_h);
} else if (patternContentUnits == SVG_ObjectBoundingBox) {
cairo_scale(cr, bw, bh);
}
/* Export the pattern tile's content like a group */
doc->export_svg_group(rset, _node, clip);
cairo_restore(cr);
}
}
cairo_restore(cr);
}

View file

@ -0,0 +1,51 @@
/*
* This file is part of gerbolyze, a vector image preprocessing toolchain
* Copyright (C) 2021 Jan Sebastian Götte <gerbolyze@jaseg.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <string>
#include <cairo.h>
#include <pugixml.hpp>
#include <clipper.hpp>
#include "svg_import_util.h"
namespace gerbolyze {
class SVGDocument;
class RenderSettings;
class Pattern {
public:
Pattern() {}
Pattern(const pugi::xml_node &node, SVGDocument &doc);
void tile (const gerbolyze::RenderSettings &rset, ClipperLib::Paths &clip);
private:
double x, y, w, h;
double vb_x, vb_y, vb_w, vb_h;
bool has_vb;
std::string patternTransform;
enum RelativeUnits patternUnits;
enum RelativeUnits patternContentUnits;
const pugi::xml_node _node;
SVGDocument *doc = nullptr;
};
} /* namespace gerbolyze */

View file

@ -0,0 +1,567 @@
/*
* This file is part of gerbolyze, a vector image preprocessing toolchain
* Copyright (C) 2021 Jan Sebastian Götte <gerbolyze@jaseg.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <cmath>
#include <string>
#include <iostream>
#include <algorithm>
#include <vector>
#include <regex>
#include <opencv2/opencv.hpp>
#include "svg_import_util.h"
#include "vec_core.h"
#include "svg_import_defs.h"
#include "jc_voronoi.h"
using namespace gerbolyze;
using namespace std;
ImageVectorizer *gerbolyze::makeVectorizer(const std::string &name) {
if (name == "poisson-disc")
return new VoronoiVectorizer(POISSON_DISC, /* relax */ true);
else if (name == "hex-grid")
return new VoronoiVectorizer(HEXGRID, /* relax */ false);
else if (name == "square-grid")
return new VoronoiVectorizer(SQUAREGRID, /* relax */ false);
else if (name == "binary-contours")
return new OpenCVContoursVectorizer();
else if (name == "dev-null")
return new DevNullVectorizer();
return nullptr;
}
/* debug function */
static void dbg_show_cv_image(cv::Mat &img) {
string windowName = "Debug image";
cv::namedWindow(windowName);
cv::imshow(windowName, img);
cv::waitKey(0);
cv::destroyWindow(windowName);
}
/* From jcv voronoi README */
static void voronoi_relax_points(const jcv_diagram* diagram, jcv_point* points) {
const jcv_site* sites = jcv_diagram_get_sites(diagram);
for (int i=0; i<diagram->numsites; i++) {
const jcv_site* site = &sites[i];
jcv_point sum = site->p;
int count = 1;
const jcv_graphedge* edge = site->edges;
while (edge) {
sum.x += edge->pos[0].x;
sum.y += edge->pos[0].y;
count++;
edge = edge->next;
}
points[site->index].x = sum.x / count;
points[site->index].y = sum.y / count;
}
}
void gerbolyze::parse_img_meta(const pugi::xml_node &node, double &x, double &y, double &width, double &height) {
/* Read XML node attributes */
x = usvg_double_attr(node, "x", 0.0);
y = usvg_double_attr(node, "y", 0.0);
width = usvg_double_attr(node, "width", 0.0);
height = usvg_double_attr(node, "height", 0.0);
assert (width > 0 && height > 0);
cerr << "image elem: w="<<width<<", h="<<height<<endl;
}
string gerbolyze::read_img_data(const pugi::xml_node &node) {
/* Read image from data:base64... URL */
string img_data = parse_data_iri(node.attribute("xlink:href").value());
if (img_data.empty()) {
cerr << "Warning: Empty or invalid image element with id \"" << node.attribute("id").value() << "\"" << endl;
return "";
}
return img_data;
}
cv::Mat read_img_opencv(const pugi::xml_node &node) {
string img_data = read_img_data(node);
/* slightly annoying round-trip through the std:: and cv:: APIs */
vector<unsigned char> img_vec(img_data.begin(), img_data.end());
cv::Mat data_mat(img_vec, true);
cv::Mat img = cv::imdecode(data_mat, cv::ImreadModes::IMREAD_GRAYSCALE | cv::ImreadModes::IMREAD_ANYDEPTH);
data_mat.release();
if (img.empty()) {
cerr << "Warning: Could not decode content of image element with id \"" << node.attribute("id").value() << "\"" << endl;
}
return img;
}
void gerbolyze::draw_bg_rect(cairo_t *cr, double width, double height, ClipperLib::Paths &clip_path, PolygonSink &sink, cairo_matrix_t &viewport_matrix) {
/* For both our debug SVG output and for the gerber output, we have to paint the image's bounding box in black as
* background for our halftone blobs. We cannot simply draw a rect here, though. Instead we have to first intersect
* the bounding box with the clip path we get from the caller, then we have to translate it into Cairo-SVG's
* document units. */
/* First, setup the bounding box rectangle in our local px coordinate space. */
ClipperLib::Path rect_path;
for (auto &elem : vector<pair<double, double>> {{0, 0}, {width, 0}, {width, height}, {0, height}}) {
double x = elem.first, y = elem.second;
cairo_user_to_device(cr, &x, &y);
rect_path.push_back({ (ClipperLib::cInt)round(x * clipper_scale), (ClipperLib::cInt)round(y * clipper_scale) });
}
/* Intersect the bounding box with the caller's clip path */
ClipperLib::Clipper c;
c.AddPath(rect_path, ClipperLib::ptSubject, /* closed */ true);
if (!clip_path.empty()) {
c.AddPaths(clip_path, ClipperLib::ptClip, /* closed */ true);
}
ClipperLib::Paths rect_out;
c.StrictlySimple(true);
c.Execute(ClipperLib::ctIntersection, rect_out, ClipperLib::pftNonZero, ClipperLib::pftNonZero);
/* Finally, translate into Cairo-SVG's document units and draw. */
cairo_save(cr);
cairo_set_matrix(cr, &viewport_matrix);
cairo_new_path(cr);
ClipperLib::cairo::clipper_to_cairo(rect_out, cr, CAIRO_PRECISION, ClipperLib::cairo::tNone);
cairo_set_source_rgba (cr, 0.0, 0.0, 0.0, 1.0);
/* First, draw into SVG */
cairo_fill(cr);
cairo_restore(cr);
/* Second, draw into gerber. */
for (const auto &poly : rect_out) {
vector<array<double, 2>> out;
for (const auto &p : poly)
out.push_back(std::array<double, 2>{
((double)p.X) / clipper_scale, ((double)p.Y) / clipper_scale
});
sink << GRB_POL_CLEAR << out;
}
}
/* Render image into gerber file.
*
* This function renders an image into a number of vector primitives emulating the images grayscale brightness by
* differently sized vector shaped giving an effect similar to halftone printing used in newspapers.
*
* On a high level, this function does this in four steps:
* 1. It preprocesses the source image at the pixel level. This involves several tasks:
* 1.1. It converts the image to grayscale.
* 1.2. It scales the image up or down to match the given minimum feature size.
* 1.3. It applies a blur depending on the given minimum feature size to prevent aliasing artifacts.
* 2. It randomly spread points across the image using poisson disc sampling. This yields points that have a fairly even
* average distance to each other across the image, and that have a guaranteed minimum distance that depends on
* minimum feature size.
* 3. It calculates a voronoi map based on this set of points and it calculats the polygon shape of each cell of the
* voronoi map.
* 4. It scales each of these voronoi cell polygons to match the input images brightness at the spot covered by this
* cell.
*/
void gerbolyze::VoronoiVectorizer::vectorize_image(cairo_t *cr, const pugi::xml_node &node, ClipperLib::Paths &clip_path, cairo_matrix_t &viewport_matrix, PolygonSink &sink, double min_feature_size_px) {
double x, y, width, height;
parse_img_meta(node, x, y, width, height);
cv::Mat img = read_img_opencv(node);
if (img.empty())
return;
cairo_save(cr);
/* Set up target transform using SVG transform and x/y attributes */
apply_cairo_transform_from_svg(cr, node.attribute("transform").value());
cairo_translate(cr, x, y);
double orig_rows = img.rows;
double orig_cols = img.cols;
double scale_x = (double)width / orig_cols;
double scale_y = (double)height / orig_rows;
double off_x = 0;
double off_y = 0;
handle_aspect_ratio(node.attribute("preserveAspectRatio").value(),
scale_x, scale_y, off_x, off_y, orig_cols, orig_rows);
/* Adjust minimum feature size given in mm and translate into px document units in our local coordinate system. */
double f_x = min_feature_size_px, f_y = 0;
cairo_device_to_user_distance(cr, &f_x, &f_y);
min_feature_size_px = sqrt(f_x*f_x + f_y*f_y);
draw_bg_rect(cr, width, height, clip_path, sink, viewport_matrix);
/* Set up a poisson-disc sampled point "grid" covering the image. Calculate poisson disc parameters from given
* minimum feature size. */
double grayscale_overhead = 0.8; /* fraction of distance between two adjacent cell centers that is reserved for
grayscale interpolation. Larger values -> better grayscale resolution,
larger cells. */
double center_distance = min_feature_size_px * 2.0 * (1.0 / (1.0-grayscale_overhead));
vector<d2p> *grid_centers = get_sampler(m_grid_type)(scale_x * orig_cols, scale_y*orig_rows, center_distance);
//vector<d2p> *grid_centers = sample_poisson_disc(width, height, min_feature_size_px * 2.0 * 2.0);
//vector<d2p> *grid_centers = sample_hexgrid(width, height, center_distance);
//vector<d2p> *grid_centers = sample_squaregrid(width, height, center_distance);
/* Target factor between given min_feature_size and intermediate image pixels,
* i.e. <scale_featuresize_factor> px ^= min_feature_size */
double scale_featuresize_factor = 3.0;
/* TODO: support for preserveAspectRatio attribute */
double px_w = width / min_feature_size_px * scale_featuresize_factor;
double px_h = height / min_feature_size_px * scale_featuresize_factor;
/* Scale intermediate image (step 1.2) to have <scale_featuresize_factor> pixels per min_feature_size. */
cv::Mat scaled(cv::Size{(int)round(px_w), (int)round(px_h)}, img.type());
cv::resize(img, scaled, scaled.size(), 0, 0);
cerr << "scaled " << img.cols << ", " << img.rows << " -> " << scaled.cols << ", " << scaled.rows << endl;
img.release();
/* Blur image with a kernel larger than our minimum feature size to avoid aliasing. */
cv::Mat blurred(scaled.size(), scaled.type());
int blur_size = (int)ceil(fmax(scaled.cols / width, scaled.rows / height) * center_distance);
if (blur_size%2 == 0)
blur_size += 1;
cerr << "blur size " << blur_size << endl;
cv::GaussianBlur(scaled, blurred, {blur_size, blur_size}, 0, 0);
scaled.release();
/* Calculate voronoi diagram for the grid generated above. */
jcv_diagram diagram;
memset(&diagram, 0, sizeof(jcv_diagram));
cerr << "adjusted scale " << scale_x << " " << scale_y << endl;
cerr << "voronoi clip rect " << (scale_x * orig_cols) << " " << (scale_y * orig_rows) << endl;
jcv_rect rect {{0.0, 0.0}, {scale_x * orig_cols, scale_y * orig_rows}};
jcv_point *pts = reinterpret_cast<jcv_point *>(grid_centers->data()); /* hackety hack */
jcv_diagram_generate(grid_centers->size(), pts, &rect, 0, &diagram);
/* Relax points, i.e. wiggle them around a little bit to equalize differences between cell sizes a little bit. */
if (m_relax)
voronoi_relax_points(&diagram, pts);
memset(&diagram, 0, sizeof(jcv_diagram));
jcv_diagram_generate(grid_centers->size(), pts, &rect, 0, &diagram);
/* For each voronoi cell calculated above, find the brightness of the blurred image pixel below its center. We do
* not have to average over the entire cell's area here: The blur is doing a good approximation of that while being
* simpler and faster.
*
* We do this step before generating the cell poygons below because we have to look up a cell's neighbor's fill
* factor during gap filling for minimum feature size preservation. */
vector<double> fill_factors(diagram.numsites); /* Factor to be multiplied with site polygon radius to yield target
fill level */
const jcv_site* sites = jcv_diagram_get_sites(&diagram);
int j = 0;
for (int i=0; i<diagram.numsites; i++) {
const jcv_point center = sites[i].p;
double pxd = (double)blurred.at<unsigned char>(
(int)round(center.y / (scale_y * orig_rows / blurred.rows)),
(int)round(center.x / (scale_x * orig_cols / blurred.cols))) / 255.0;
/* FIXME: This is a workaround for a memory corruption bug that happens with the square-grid setting. When using
* square-grid on a fairly small test image, sometimes sites[i].index will be out of bounds here.
*/
if (sites[i].index < fill_factors.size())
fill_factors[sites[i].index] = sqrt(pxd);
}
/* Minimum gap between adjacent scaled site polygons. */
double min_gap_px = min_feature_size_px;
vector<double> adjusted_fill_factors;
adjusted_fill_factors.reserve(32); /* Vector to hold adjusted fill factors for each edge for gap filling */
/* now iterate over all voronoi cells again to generate each cell's scaled polygon halftone blob. */
for (int i=0; i<diagram.numsites; i++) {
const jcv_point center = sites[i].p;
double fill_factor_ours = fill_factors[sites[i].index];
/* Do not render halftone blobs that are too small */
if (fill_factor_ours * 0.5 * center_distance < min_gap_px)
continue;
/* Iterate over this cell's edges. For each edge, check the gap that would result between this cell's halftone
* blob and the neighboring cell's halftone blob based on their fill factors. If the gap is too small, either
* widen it by adjusting both fill factors down a bit (for this edge only!), or eliminate it by setting both
* fill factors to 1.0 (again, for this edge only!). */
adjusted_fill_factors.clear();
const jcv_graphedge* e = sites[i].edges;
while (e) {
/* half distance between both neighbors of this edge, i.e. sites[i] and its neighbor. */
/* Note that in a voronoi tesselation, this edge is always halfway between. */
double adjusted_fill_factor = fill_factor_ours;
if (e->neighbor != nullptr) { /* nullptr -> edge is on the voronoi map's border */
double rad = sqrt(pow(center.x - e->neighbor->p.x, 2) + pow(center.y - e->neighbor->p.y, 2)) / 2.0;
double fill_factor_theirs = fill_factors[e->neighbor->index];
double gap_px = (1.0 - fill_factor_ours) * rad + (1.0 - fill_factor_theirs) * rad;
if (gap_px > min_gap_px) {
/* all good. gap is wider than minimum. */
} else if (gap_px > 0.5 * min_gap_px) {
/* gap is narrower than minimum, but more than half of minimum width. */
/* force gap open, distribute adjustment evenly on left/right */
double fill_factor_adjustment = (min_gap_px - gap_px) / 2.0 / rad;
adjusted_fill_factor -= fill_factor_adjustment;
} else {
/* gap is less than half of minimum width. Force gap closed. */
adjusted_fill_factor = 1.0;
}
}
adjusted_fill_factors.push_back(adjusted_fill_factor);
e = e->next;
}
/* Now, generate the actual halftone blob polygon */
ClipperLib::Path cell_path;
double last_fill_factor = adjusted_fill_factors.back();
e = sites[i].edges;
j = 0;
while (e) {
double fill_factor = adjusted_fill_factors[j];
if (last_fill_factor != fill_factor) {
/* Fill factor was adjusted since last edge, so generate one extra point so we have a nice radial
* "step". */
double x = e->pos[0].x;
double y = e->pos[0].y;
x = off_x + center.x + (x - center.x) * fill_factor;
y = off_y + center.y + (y - center.y) * fill_factor;
cairo_user_to_device(cr, &x, &y);
cell_path.push_back({ (ClipperLib::cInt)round(x * clipper_scale), (ClipperLib::cInt)round(y * clipper_scale) });
}
/* Emit endpoint of current edge */
double x = e->pos[1].x;
double y = e->pos[1].y;
x = off_x + center.x + (x - center.x) * fill_factor;
y = off_y + center.y + (y - center.y) * fill_factor;
cairo_user_to_device(cr, &x, &y);
cell_path.push_back({ (ClipperLib::cInt)round(x * clipper_scale), (ClipperLib::cInt)round(y * clipper_scale) });
j += 1;
last_fill_factor = fill_factor;
e = e->next;
}
/* Now, clip the halftone blob generated above against the given clip path. We do this individually for each
* blob since this way is *much* faster than throwing a million blobs at once at poor clipper. */
ClipperLib::Paths polys;
ClipperLib::Clipper c;
c.AddPath(cell_path, ClipperLib::ptSubject, /* closed */ true);
if (!clip_path.empty()) {
c.AddPaths(clip_path, ClipperLib::ptClip, /* closed */ true);
}
c.StrictlySimple(true);
c.Execute(ClipperLib::ctIntersection, polys, ClipperLib::pftNonZero, ClipperLib::pftNonZero);
/* Export halftone blob to debug svg */
cairo_save(cr);
cairo_set_matrix(cr, &viewport_matrix);
cairo_new_path(cr);
ClipperLib::cairo::clipper_to_cairo(polys, cr, CAIRO_PRECISION, ClipperLib::cairo::tNone);
cairo_set_source_rgba(cr, 1, 1, 1, 1);
cairo_fill(cr);
cairo_restore(cr);
/* And finally, export halftone blob to gerber. */
for (const auto &poly : polys) {
vector<array<double, 2>> out;
for (const auto &p : poly)
out.push_back(std::array<double, 2>{
((double)p.X) / clipper_scale, ((double)p.Y) / clipper_scale
});
sink << GRB_POL_DARK << out;
}
}
blurred.release();
jcv_diagram_free( &diagram );
delete grid_centers;
cairo_restore(cr);
}
void gerbolyze::handle_aspect_ratio(string spec, double &scale_x, double &scale_y, double &off_x, double &off_y, double cols, double rows) {
if (spec.empty()) {
spec = "xMidYMid meet";
}
auto idx = spec.find(" ");
string par_align = spec;
string par_meet = "meet";
if (idx != string::npos) {
par_align = spec.substr(0, idx);
par_meet = spec.substr(idx+1);
}
if (par_align != "none") {
double scale = scale_x;
if (par_meet == "slice") {
scale = std::max(scale_x, scale_y);
} else {
scale = std::min(scale_x, scale_y);
}
std::regex reg("x(Min|Mid|Max)Y(Min|Mid|Max)");
std::smatch match;
cerr << "data: " <<" "<< scale_x << "/" << scale_y << ": " << scale << endl;
off_x = (scale_x - scale) * cols;
off_y = (scale_y - scale) * rows;
cerr << rows <<","<<cols<<" " << off_x << "," << off_y << endl;
if (std::regex_match(par_align, match, reg)) {
assert (match.size() == 3);
if (match[1].str() == "Min") {
off_x = 0;
} else if (match[1].str() == "Mid") {
off_x *= 0.5;
}
if (match[2].str() == "Min") {
off_y = 0;
} else if (match[2].str() == "Mid") {
off_y *= 0.5;
}
} else {
cerr << "Invalid preserveAspectRatio meetOrSlice value \"" << par_align << "\"" << endl;
off_x *= 0.5;
off_y *= 0.5;
}
scale_x = scale_y = scale;
}
cerr << "res: "<< off_x << "," << off_y << endl;
}
void gerbolyze::OpenCVContoursVectorizer::vectorize_image(cairo_t *cr, const pugi::xml_node &node, ClipperLib::Paths &clip_path, cairo_matrix_t &viewport_matrix, PolygonSink &sink, double min_feature_size_px) {
double x, y, width, height;
parse_img_meta(node, x, y, width, height);
cv::Mat img = read_img_opencv(node);
if (img.empty())
return;
cairo_save(cr);
/* Set up target transform using SVG transform and x/y attributes */
apply_cairo_transform_from_svg(cr, node.attribute("transform").value());
cairo_translate(cr, x, y);
double scale_x = (double)width / (double)img.cols;
double scale_y = (double)height / (double)img.rows;
double off_x = 0;
double off_y = 0;
handle_aspect_ratio(node.attribute("preserveAspectRatio").value(),
scale_x, scale_y, off_x, off_y, img.cols, img.rows);
draw_bg_rect(cr, width, height, clip_path, sink, viewport_matrix);
vector<vector<cv::Point>> contours;
vector<cv::Vec4i> hierarchy;
cv::findContours(img, contours, hierarchy, cv::RETR_TREE, cv::CHAIN_APPROX_TC89_KCOS);
queue<pair<size_t, bool>> child_stack;
child_stack.push({ 0, true });
while (!child_stack.empty()) {
bool dark = child_stack.front().second;
for (int i=child_stack.front().first; i>=0; i = hierarchy[i][0]) {
if (hierarchy[i][2] >= 0) {
child_stack.push({ hierarchy[i][2], !dark });
}
sink << (dark ? GRB_POL_DARK : GRB_POL_CLEAR);
bool is_clockwise = cv::contourArea(contours[i], true) > 0;
if (!is_clockwise)
std::reverse(contours[i].begin(), contours[i].end());
ClipperLib::Path out;
for (const auto &p : contours[i]) {
double x = off_x + (double)p.x * scale_x;
double y = off_y + (double)p.y * scale_y;
cairo_user_to_device(cr, &x, &y);
out.push_back({ (ClipperLib::cInt)round(x * clipper_scale), (ClipperLib::cInt)round(y * clipper_scale) });
}
ClipperLib::Clipper c;
c.AddPath(out, ClipperLib::ptSubject, /* closed */ true);
if (!clip_path.empty()) {
c.AddPaths(clip_path, ClipperLib::ptClip, /* closed */ true);
}
c.StrictlySimple(true);
ClipperLib::Paths polys;
c.Execute(ClipperLib::ctIntersection, polys, ClipperLib::pftNonZero, ClipperLib::pftNonZero);
/* Finally, translate into Cairo-SVG's document units and draw. */
cairo_save(cr);
cairo_set_matrix(cr, &viewport_matrix);
cairo_new_path(cr);
ClipperLib::cairo::clipper_to_cairo(polys, cr, CAIRO_PRECISION, ClipperLib::cairo::tNone);
cairo_set_source_rgba (cr, 0.0, 0.0, 0.0, 1.0);
/* First, draw into SVG */
cairo_fill(cr);
cairo_restore(cr);
/* Second, draw into gerber. */
for (const auto &poly : polys) {
vector<array<double, 2>> out;
for (const auto &p : poly)
out.push_back(std::array<double, 2>{
((double)p.X) / clipper_scale, ((double)p.Y) / clipper_scale
});
sink << out;
}
}
child_stack.pop();
}
cairo_restore(cr);
}
gerbolyze::VectorizerSelectorizer::VectorizerSelectorizer(const string default_vectorizer, const string defs)
: m_default(default_vectorizer) {
istringstream foo(defs);
string elem;
while (std::getline(foo, elem, ',')) {
size_t pos = elem.find_first_of("=");
if (pos == string::npos) {
cerr << "Error parsing vectorizer selection string at element \"" << elem << "\"" << endl;
continue;
}
const string parsed_id = elem.substr(0, pos);
const string mapping = elem.substr(pos+1);
m_map[parsed_id] = mapping;
}
cerr << "parsed " << m_map.size() << " vectorizers" << endl;
for (auto &elem : m_map) {
cerr << " " << elem.first << " -> " << elem.second << endl;
}
}
ImageVectorizer *gerbolyze::VectorizerSelectorizer::select(const pugi::xml_node &img) {
const string id = img.attribute("id").value();
cerr << "selecting vectorizer for image \"" << id << "\"" << endl;
if (m_map.contains(id)) {
cerr << " -> found" << endl;
return makeVectorizer(m_map[id]);
}
cerr << " -> default" << endl;
return makeVectorizer(m_default);
}

View file

@ -0,0 +1,58 @@
/*
* This file is part of gerbolyze, a vector image preprocessing toolchain
* Copyright (C) 2021 Jan Sebastian Götte <gerbolyze@jaseg.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <cairo.h>
#include <pugixml.hpp>
#include <clipper.hpp>
#include <gerbolyze.hpp>
#include "vec_grid.h"
namespace gerbolyze {
class VoronoiVectorizer : public ImageVectorizer {
public:
VoronoiVectorizer(grid_type grid, bool relax=true) : m_relax(relax), m_grid_type(grid) {}
virtual void vectorize_image(cairo_t *cr, const pugi::xml_node &node, ClipperLib::Paths &clip_path, cairo_matrix_t &viewport_matrix, PolygonSink &sink, double min_feature_size_px);
private:
double m_relax;
grid_type m_grid_type;
};
class OpenCVContoursVectorizer : public ImageVectorizer {
public:
OpenCVContoursVectorizer() {}
virtual void vectorize_image(cairo_t *cr, const pugi::xml_node &node, ClipperLib::Paths &clip_path, cairo_matrix_t &viewport_matrix, PolygonSink &sink, double min_feature_size_px);
};
class DevNullVectorizer : public ImageVectorizer {
public:
DevNullVectorizer() {}
virtual void vectorize_image(cairo_t *, const pugi::xml_node &, ClipperLib::Paths &, cairo_matrix_t &, PolygonSink &, double) {}
};
void parse_img_meta(const pugi::xml_node &node, double &x, double &y, double &width, double &height);
std::string read_img_data(const pugi::xml_node &node);
void draw_bg_rect(cairo_t *cr, double width, double height, ClipperLib::Paths &clip_path, PolygonSink &sink, cairo_matrix_t &viewport_matrix);
void handle_aspect_ratio(std::string spec, double &scale_x, double &scale_y, double &off_x, double &off_y, double cols, double rows);
}

View file

@ -0,0 +1,99 @@
/*
* This file is part of gerbolyze, a vector image preprocessing toolchain
* Copyright (C) 2021 Jan Sebastian Götte <gerbolyze@jaseg.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "poisson_disk_sampling.h"
#include "vec_grid.h"
using namespace std;
using namespace gerbolyze;
sampling_fun gerbolyze::get_sampler(enum grid_type type) {
switch(type) {
case POISSON_DISC:
return sample_poisson_disc;
case HEXGRID:
return sample_hexgrid;
case SQUAREGRID:
return sample_squaregrid;
default:
return sample_poisson_disc;
}
}
vector<d2p> *gerbolyze::sample_poisson_disc(double w, double h, double center_distance) {
d2p top_left {0, 0};
d2p bottom_right {w, h};
return new auto(thinks::PoissonDiskSampling(center_distance/2.5, top_left, bottom_right));
}
vector<d2p> *gerbolyze::sample_hexgrid(double w, double h, double center_distance) {
double radius = center_distance / 2.0 / (sqrt(3) / 2.0); /* radius of hexagon */
double pitch_v = 1.5 * radius;
double pitch_h = center_distance;
/* offset of first hexagon to make sure the entire area is covered. We use slightly larger values here to avoid
* corner cases during clipping in the voronoi map generator. The inaccuracies this causes at the edges are
* negligible. */
double off_x = 0.5001 * center_distance;
double off_y = 0.5001 * radius;
/* NOTE: The voronoi generator is not quite stable when points lie outside the bounds. Thus, floor(). */
long long int points_x = floor(w / pitch_h);
long long int points_y = floor(h / pitch_v);
vector<d2p> *out = new vector<d2p>();
out->reserve((points_x+1) * points_y);
/* This may generate up to one extra row of points. We don't care since these points will simply be clipped during
* voronoi map generation. */
for (long long int y_i=0; y_i<points_y; y_i+=2) {
for (long long int x_i=0; x_i<points_x; x_i++) { /* allow one extra point to compensate for row shift */
out->push_back(d2p{off_x + x_i * pitch_h, off_y + y_i * pitch_v});
}
for (long long int x_i=0; x_i<points_x+1; x_i++) { /* allow one extra point to compensate for row shift */
out->push_back(d2p{off_x + (x_i - 0.5) * pitch_h, off_y + (y_i + 1) * pitch_v});
}
}
return out;
}
vector<d2p> *gerbolyze::sample_squaregrid(double w, double h, double center_distance) {
/* offset of first square to make sure the entire area is covered. We use slightly larger values here to avoid
* corner cases during clipping in the voronoi map generator. The inaccuracies this causes at the edges are
* negligible. */
double off_x = 0.5 * center_distance;
double off_y = 0.5 * center_distance;
long long int points_x = ceil(w / center_distance);
long long int points_y = ceil(h / center_distance);
vector<d2p> *out = new vector<d2p>();
out->reserve(points_x * points_y);
for (long long int y_i=0; y_i<points_y; y_i++) {
for (long long int x_i=0; x_i<points_x; x_i++) {
out->push_back({off_x + x_i*center_distance, off_y + y_i*center_distance});
}
}
return out;
}

View file

@ -0,0 +1,41 @@
/*
* This file is part of gerbolyze, a vector image preprocessing toolchain
* Copyright (C) 2021 Jan Sebastian Götte <gerbolyze@jaseg.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <array>
#include <vector>
#include <functional>
#include <gerbolyze.hpp>
namespace gerbolyze {
enum grid_type {
POISSON_DISC,
HEXGRID,
SQUAREGRID
};
sampling_fun get_sampler(enum grid_type type);
std::vector<d2p> *sample_poisson_disc(double w, double h, double center_distance);
std::vector<d2p> *sample_hexgrid(double w, double h, double center_distance);
std::vector<d2p> *sample_squaregrid(double w, double h, double center_distance);
} /* namespace gerbolyze */