sla_test_utils.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. #include "sla_test_utils.hpp"
  2. #include "libslic3r/TriangleMeshSlicer.hpp"
  3. #include "libslic3r/SLA/AGGRaster.hpp"
  4. #include "libslic3r/SLA/DefaultSupportTree.hpp"
  5. #include "libslic3r/SLA/BranchingTreeSLA.hpp"
  6. #include <iomanip>
  7. void test_support_model_collision(
  8. const std::string &obj_filename,
  9. const sla::SupportTreeConfig &input_supportcfg,
  10. const sla::HollowingConfig &hollowingcfg,
  11. const sla::DrainHoles &drainholes)
  12. {
  13. SupportByproducts byproducts;
  14. sla::SupportTreeConfig supportcfg = input_supportcfg;
  15. // Set head penetration to a small negative value which should ensure that
  16. // the supports will not touch the model body.
  17. supportcfg.head_penetration_mm = -0.2;
  18. test_supports(obj_filename, supportcfg, hollowingcfg, drainholes, byproducts);
  19. // Slice the support mesh given the slice grid of the model.
  20. std::vector<ExPolygons> support_slices =
  21. sla::slice(byproducts.suptree_builder.retrieve_mesh(sla::MeshType::Support),
  22. byproducts.suptree_builder.retrieve_mesh(sla::MeshType::Pad),
  23. byproducts.slicegrid, CLOSING_RADIUS, {});
  24. // The slices originate from the same slice grid so the numbers must match
  25. bool support_mesh_is_empty =
  26. byproducts.suptree_builder.retrieve_mesh(sla::MeshType::Pad).empty() &&
  27. byproducts.suptree_builder.retrieve_mesh(sla::MeshType::Support).empty();
  28. if (support_mesh_is_empty)
  29. REQUIRE(support_slices.empty());
  30. else
  31. REQUIRE(support_slices.size() == byproducts.model_slices.size());
  32. bool notouch = true;
  33. for (size_t n = 0; notouch && n < support_slices.size(); ++n) {
  34. const ExPolygons &sup_slice = support_slices[n];
  35. const ExPolygons &mod_slice = byproducts.model_slices[n];
  36. Polygons intersections = intersection(sup_slice, mod_slice);
  37. double pinhead_r = scaled(input_supportcfg.head_front_radius_mm);
  38. // TODO:: make it strict without a threshold of PI * pihead_radius ^ 2
  39. notouch = notouch && area(intersections) < PI * pinhead_r * pinhead_r;
  40. }
  41. if (!notouch)
  42. export_failed_case(support_slices, byproducts);
  43. REQUIRE(notouch);
  44. }
  45. void export_failed_case(const std::vector<ExPolygons> &support_slices, const SupportByproducts &byproducts)
  46. {
  47. bool do_export_stl = false;
  48. for (size_t n = 0; n < support_slices.size(); ++n) {
  49. const ExPolygons &sup_slice = support_slices[n];
  50. const ExPolygons &mod_slice = byproducts.model_slices[n];
  51. Polygons intersections = intersection(sup_slice, mod_slice);
  52. std::stringstream ss;
  53. if (!intersections.empty()) {
  54. ss << byproducts.obj_fname << std::setprecision(4) << n << ".svg";
  55. SVG svg(ss.str());
  56. svg.draw(sup_slice, "green");
  57. svg.draw(mod_slice, "blue");
  58. svg.draw(intersections, "red");
  59. svg.Close();
  60. }
  61. do_export_stl = do_export_stl || !intersections.empty();
  62. }
  63. if (do_export_stl) {
  64. indexed_triangle_set its;
  65. byproducts.suptree_builder.retrieve_full_mesh(its);
  66. TriangleMesh m{its};
  67. m.merge(byproducts.input_mesh);
  68. m.WriteOBJFile((Catch::getResultCapture().getCurrentTestName() + "_" +
  69. byproducts.obj_fname).c_str());
  70. }
  71. }
  72. void test_supports(const std::string &obj_filename,
  73. const sla::SupportTreeConfig &supportcfg,
  74. const sla::HollowingConfig &hollowingcfg,
  75. const sla::DrainHoles &drainholes,
  76. SupportByproducts &out)
  77. {
  78. using namespace Slic3r;
  79. TriangleMesh mesh = load_model(obj_filename);
  80. REQUIRE_FALSE(mesh.empty());
  81. if (hollowingcfg.enabled) {
  82. sla::InteriorPtr interior = sla::generate_interior(mesh.its, hollowingcfg);
  83. REQUIRE(interior);
  84. mesh.merge(TriangleMesh{sla::get_mesh(*interior)});
  85. }
  86. auto bb = mesh.bounding_box();
  87. double zmin = bb.min.z();
  88. double zmax = bb.max.z();
  89. double gnd = zmin - supportcfg.object_elevation_mm;
  90. auto layer_h = 0.05f;
  91. out.slicegrid = grid(float(gnd), float(zmax), layer_h);
  92. out.model_slices = slice_mesh_ex(mesh.its, out.slicegrid, CLOSING_RADIUS);
  93. sla::cut_drainholes(out.model_slices, out.slicegrid, CLOSING_RADIUS, drainholes, []{});
  94. // Create the special index-triangle mesh with spatial indexing which
  95. // is the input of the support point and support mesh generators
  96. sla::SupportableMesh sm{mesh.its, {}, supportcfg};
  97. #ifdef SLIC3R_HOLE_RAYCASTER
  98. if (hollowingcfg.enabled)
  99. emesh.load_holes(drainholes);
  100. #endif
  101. // TODO: do the cgal hole cutting...
  102. // Create the support point generator
  103. sla::SupportPointGenerator::Config autogencfg;
  104. autogencfg.head_diameter = float(2 * supportcfg.head_front_radius_mm);
  105. sla::SupportPointGenerator point_gen{sm.emesh, autogencfg, [] {}, [](int) {}};
  106. point_gen.seed(0); // Make the test repeatable
  107. point_gen.execute(out.model_slices, out.slicegrid);
  108. // Get the calculated support points.
  109. sm.pts = point_gen.output();
  110. int validityflags = ASSUME_NO_REPAIR;
  111. // If there is no elevation, support points shall be removed from the
  112. // bottom of the object.
  113. if (std::abs(supportcfg.object_elevation_mm) < EPSILON) {
  114. sla::remove_bottom_points(sm.pts, zmin + supportcfg.base_height_mm);
  115. } else {
  116. // Should be support points at least on the bottom of the model
  117. REQUIRE_FALSE(sm.pts.empty());
  118. // Also the support mesh should not be empty.
  119. validityflags |= ASSUME_NO_EMPTY;
  120. }
  121. // Generate the actual support tree
  122. sla::SupportTreeBuilder treebuilder;
  123. switch (sm.cfg.tree_type) {
  124. case sla::SupportTreeType::Default: {
  125. sla::DefaultSupportTree::execute(treebuilder, sm);
  126. check_support_tree_integrity(treebuilder, supportcfg, sla::ground_level(sm));
  127. break;
  128. }
  129. case sla::SupportTreeType::Branching: {
  130. create_branching_tree(treebuilder, sm);
  131. // TODO: check_support_tree_integrity(treebuilder, supportcfg);
  132. break;
  133. }
  134. default:;
  135. }
  136. TriangleMesh output_mesh{treebuilder.retrieve_mesh(sla::MeshType::Support)};
  137. check_validity(output_mesh, validityflags);
  138. // Quick check if the dimensions and placement of supports are correct
  139. auto obb = output_mesh.bounding_box();
  140. double allowed_zmin = zmin - supportcfg.object_elevation_mm;
  141. if (std::abs(supportcfg.object_elevation_mm) < EPSILON)
  142. allowed_zmin = zmin - 2 * supportcfg.head_back_radius_mm;
  143. #ifndef NDEBUG
  144. if (!(obb.min.z() >= Approx(allowed_zmin)) || !(obb.max.z() <= Approx(zmax)))
  145. {
  146. indexed_triangle_set its;
  147. treebuilder.retrieve_full_mesh(its);
  148. TriangleMesh m{its};
  149. m.merge(mesh);
  150. m.WriteOBJFile((Catch::getResultCapture().getCurrentTestName() + "_" +
  151. obj_filename).c_str());
  152. }
  153. #endif
  154. REQUIRE(obb.min.z() >= Approx(allowed_zmin));
  155. REQUIRE(obb.max.z() <= Approx(zmax));
  156. // Move out the support tree into the byproducts, we can examine it further
  157. // in various tests.
  158. out.obj_fname = std::move(obj_filename);
  159. out.suptree_builder = std::move(treebuilder);
  160. out.input_mesh = std::move(mesh);
  161. }
  162. void check_support_tree_integrity(const sla::SupportTreeBuilder &stree,
  163. const sla::SupportTreeConfig &cfg,
  164. double gnd)
  165. {
  166. double H1 = cfg.max_solo_pillar_height_mm;
  167. double H2 = cfg.max_dual_pillar_height_mm;
  168. for (const sla::Head &head : stree.heads()) {
  169. REQUIRE((!head.is_valid() || head.pillar_id != sla::SupportTreeNode::ID_UNSET ||
  170. head.bridge_id != sla::SupportTreeNode::ID_UNSET));
  171. }
  172. for (const sla::Pillar &pillar : stree.pillars()) {
  173. if (std::abs(pillar.endpoint().z() - gnd) < EPSILON) {
  174. double h = pillar.height;
  175. if (h > H1) REQUIRE(pillar.links >= 1);
  176. else if(h > H2) { REQUIRE(pillar.links >= 2); }
  177. }
  178. REQUIRE(pillar.links <= cfg.pillar_cascade_neighbors);
  179. REQUIRE(pillar.bridges <= cfg.max_bridges_on_pillar);
  180. }
  181. double max_bridgelen = 0.;
  182. auto chck_bridge = [&cfg](const sla::Bridge &bridge, double &max_brlen) {
  183. Vec3d n = bridge.endp - bridge.startp;
  184. double d = sla::distance(n);
  185. max_brlen = std::max(d, max_brlen);
  186. double z = n.z();
  187. double polar = std::acos(z / d);
  188. double slope = -polar + PI / 2.;
  189. REQUIRE(std::abs(slope) >= cfg.bridge_slope - EPSILON);
  190. };
  191. for (auto &bridge : stree.bridges()) chck_bridge(bridge, max_bridgelen);
  192. REQUIRE(max_bridgelen <= Approx(cfg.max_bridge_length_mm));
  193. max_bridgelen = 0;
  194. for (auto &bridge : stree.crossbridges()) chck_bridge(bridge, max_bridgelen);
  195. double md = cfg.max_pillar_link_distance_mm / std::cos(-cfg.bridge_slope);
  196. REQUIRE(max_bridgelen <= md);
  197. }
  198. void test_pad(const std::string &obj_filename, const sla::PadConfig &padcfg, PadByproducts &out)
  199. {
  200. REQUIRE(padcfg.validate().empty());
  201. TriangleMesh mesh = load_model(obj_filename);
  202. REQUIRE_FALSE(mesh.empty());
  203. // Create pad skeleton only from the model
  204. Slic3r::sla::pad_blueprint(mesh.its, out.model_contours);
  205. test_concave_hull(out.model_contours);
  206. REQUIRE_FALSE(out.model_contours.empty());
  207. // Create the pad geometry for the model contours only
  208. indexed_triangle_set out_its;
  209. Slic3r::sla::create_pad({}, out.model_contours, out_its, padcfg);
  210. out.mesh = TriangleMesh{out_its};
  211. check_validity(out.mesh);
  212. auto bb = out.mesh.bounding_box();
  213. REQUIRE(bb.max.z() - bb.min.z() == Approx(padcfg.full_height()));
  214. }
  215. static void _test_concave_hull(const Polygons &hull, const ExPolygons &polys)
  216. {
  217. REQUIRE(polys.size() >=hull.size());
  218. double polys_area = 0;
  219. for (const ExPolygon &p : polys) polys_area += p.area();
  220. double cchull_area = 0;
  221. for (const Slic3r::Polygon &p : hull) cchull_area += p.area();
  222. REQUIRE(cchull_area >= Approx(polys_area));
  223. size_t cchull_holes = 0;
  224. for (const Slic3r::Polygon &p : hull)
  225. cchull_holes += p.is_clockwise() ? 1 : 0;
  226. REQUIRE(cchull_holes == 0);
  227. Polygons diff_poly = diff(to_polygons(polys), hull);
  228. if (!diff_poly.empty()) {
  229. BOOST_LOG_TRIVIAL(warning)
  230. << "Concave hull diff with original shape is not completely empty."
  231. << "See pad_chull.svg for details.";
  232. SVG svg("pad_chull.svg");
  233. svg.draw(polys, "green");
  234. svg.draw(hull, "red");
  235. svg.draw(diff_poly, "blue");
  236. }
  237. double diff_area = area(diff_poly);
  238. REQUIRE(std::abs(diff_area) < std::pow(scaled(2 * EPSILON), 2));
  239. }
  240. void test_concave_hull(const ExPolygons &polys) {
  241. sla::PadConfig pcfg;
  242. Slic3r::sla::ConcaveHull cchull{polys, pcfg.max_merge_dist_mm, []{}};
  243. _test_concave_hull(cchull.polygons(), polys);
  244. coord_t delta = scaled(pcfg.brim_size_mm + pcfg.wing_distance());
  245. ExPolygons wafflex = sla::offset_waffle_style_ex(cchull, delta);
  246. Polygons waffl = sla::offset_waffle_style(cchull, delta);
  247. _test_concave_hull(to_polygons(wafflex), polys);
  248. _test_concave_hull(waffl, polys);
  249. }
  250. //FIXME this functionality is gone after TriangleMesh refactoring to get rid of admesh.
  251. void check_validity(const TriangleMesh &input_mesh, int flags)
  252. {
  253. /*
  254. TriangleMesh mesh{input_mesh};
  255. if (flags & ASSUME_NO_EMPTY) {
  256. REQUIRE_FALSE(mesh.empty());
  257. } else if (mesh.empty())
  258. return; // If it can be empty and it is, there is nothing left to do.
  259. bool do_update_shared_vertices = false;
  260. mesh.repair(do_update_shared_vertices);
  261. if (flags & ASSUME_NO_REPAIR) {
  262. REQUIRE_FALSE(mesh.repaired());
  263. }
  264. if (flags & ASSUME_MANIFOLD) {
  265. if (!mesh.is_manifold()) mesh.WriteOBJFile("non_manifold.obj");
  266. REQUIRE(mesh.is_manifold());
  267. }
  268. */
  269. }
  270. void check_raster_transformations(sla::RasterBase::Orientation o, sla::RasterBase::TMirroring mirroring)
  271. {
  272. double disp_w = 120., disp_h = 68.;
  273. sla::Resolution res{2560, 1440};
  274. sla::PixelDim pixdim{disp_w / res.width_px, disp_h / res.height_px};
  275. auto bb = BoundingBox({0, 0}, {scaled(disp_w), scaled(disp_h)});
  276. sla::RasterBase::Trafo trafo{o, mirroring};
  277. trafo.center_x = bb.center().x();
  278. trafo.center_y = bb.center().y();
  279. double gamma = 1.;
  280. sla::RasterGrayscaleAAGammaPower raster{res, pixdim, trafo, gamma};
  281. // create box of size 32x32 pixels (not 1x1 to avoid antialiasing errors)
  282. coord_t pw = 32 * coord_t(std::ceil(scaled<double>(pixdim.w_mm)));
  283. coord_t ph = 32 * coord_t(std::ceil(scaled<double>(pixdim.h_mm)));
  284. ExPolygon box;
  285. box.contour.points = {{-pw, -ph}, {pw, -ph}, {pw, ph}, {-pw, ph}};
  286. double tr_x = scaled<double>(20.), tr_y = tr_x;
  287. box.translate(tr_x, tr_y);
  288. ExPolygon expected_box = box;
  289. // Now calculate the position of the translated box according to output
  290. // trafo.
  291. if (o == sla::RasterBase::Orientation::roPortrait) expected_box.rotate(PI / 2.);
  292. if (mirroring[X])
  293. for (auto &p : expected_box.contour.points) p.x() = -p.x();
  294. if (mirroring[Y])
  295. for (auto &p : expected_box.contour.points) p.y() = -p.y();
  296. raster.draw(box);
  297. Point expected_coords = expected_box.contour.bounding_box().center();
  298. double rx = unscaled(expected_coords.x() + bb.center().x()) / pixdim.w_mm;
  299. double ry = unscaled(expected_coords.y() + bb.center().y()) / pixdim.h_mm;
  300. auto w = size_t(std::floor(rx));
  301. auto h = res.height_px - size_t(std::floor(ry));
  302. REQUIRE((w < res.width_px && h < res.height_px));
  303. auto px = raster.read_pixel(w, h);
  304. if (px != FullWhite) {
  305. std::fstream outf("out.png", std::ios::out);
  306. outf << raster.encode(sla::PNGRasterEncoder());
  307. }
  308. REQUIRE(px == FullWhite);
  309. }
  310. ExPolygon square_with_hole(double v)
  311. {
  312. ExPolygon poly;
  313. coord_t V = scaled(v / 2.);
  314. poly.contour.points = {{-V, -V}, {V, -V}, {V, V}, {-V, V}};
  315. poly.holes.emplace_back();
  316. V = V / 2;
  317. poly.holes.front().points = {{-V, V}, {V, V}, {V, -V}, {-V, -V}};
  318. return poly;
  319. }
  320. long raster_pxsum(const sla::RasterGrayscaleAA &raster)
  321. {
  322. auto res = raster.resolution();
  323. long a = 0;
  324. for (size_t x = 0; x < res.width_px; ++x)
  325. for (size_t y = 0; y < res.height_px; ++y)
  326. a += raster.read_pixel(x, y);
  327. return a;
  328. }
  329. double raster_white_area(const sla::RasterGrayscaleAA &raster)
  330. {
  331. if (raster.resolution().pixels() == 0) return NaNd;
  332. auto res = raster.resolution();
  333. double a = 0;
  334. for (size_t x = 0; x < res.width_px; ++x)
  335. for (size_t y = 0; y < res.height_px; ++y) {
  336. auto px = raster.read_pixel(x, y);
  337. a += pixel_area(px, raster.pixel_dimensions());
  338. }
  339. return a;
  340. }
  341. double predict_error(const ExPolygon &p, const sla::PixelDim &pd)
  342. {
  343. auto lines = p.lines();
  344. double pix_err = pixel_area(FullWhite, pd) / 2.;
  345. // Worst case is when a line is parallel to the shorter axis of one pixel,
  346. // when the line will be composed of the max number of pixels
  347. double pix_l = std::min(pd.h_mm, pd.w_mm);
  348. double error = 0.;
  349. for (auto &l : lines)
  350. error += (unscaled(l.length()) / pix_l) * pix_err;
  351. return error;
  352. }
  353. sla::SupportPoints calc_support_pts(
  354. const TriangleMesh & mesh,
  355. const sla::SupportPointGenerator::Config &cfg)
  356. {
  357. // Prepare the slice grid and the slices
  358. auto bb = cast<float>(mesh.bounding_box());
  359. std::vector<float> heights = grid(bb.min.z(), bb.max.z(), 0.1f);
  360. std::vector<ExPolygons> slices = slice_mesh_ex(mesh.its, heights, CLOSING_RADIUS);
  361. // Prepare the support point calculator
  362. AABBMesh emesh{mesh};
  363. sla::SupportPointGenerator spgen{emesh, cfg, []{}, [](int){}};
  364. // Calculate the support points
  365. spgen.seed(0);
  366. spgen.execute(slices, heights);
  367. return spgen.output();
  368. }