sla_test_utils.cpp 16 KB

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