My Marlin configs for Fabrikator Mini and CTC i3 Pro B
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
  4. *
  5. * Based on Sprinter and grbl.
  6. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. #include "../../../inc/MarlinConfig.h"
  23. #if ENABLED(AUTO_BED_LEVELING_UBL)
  24. #include "../bedlevel.h"
  25. #include "../../../MarlinCore.h"
  26. #include "../../../HAL/shared/eeprom_api.h"
  27. #include "../../../libs/hex_print_routines.h"
  28. #include "../../../module/configuration_store.h"
  29. #include "../../../lcd/ultralcd.h"
  30. #include "../../../module/stepper.h"
  31. #include "../../../module/planner.h"
  32. #include "../../../module/motion.h"
  33. #include "../../../module/probe.h"
  34. #include "../../../gcode/gcode.h"
  35. #include "../../../libs/least_squares_fit.h"
  36. #if HAS_MULTI_HOTEND
  37. #include "../../../module/tool_change.h"
  38. #endif
  39. #define DEBUG_OUT ENABLED(DEBUG_LEVELING_FEATURE)
  40. #include "../../../core/debug_out.h"
  41. #if ENABLED(EXTENSIBLE_UI)
  42. #include "../../../lcd/extui/ui_api.h"
  43. #endif
  44. #include <math.h>
  45. #define UBL_G29_P31
  46. #if HAS_LCD_MENU
  47. void _lcd_ubl_output_map_lcd();
  48. #endif
  49. #define SIZE_OF_LITTLE_RAISE 1
  50. #define BIG_RAISE_NOT_NEEDED 0
  51. int unified_bed_leveling::g29_verbose_level,
  52. unified_bed_leveling::g29_phase_value,
  53. unified_bed_leveling::g29_repetition_cnt,
  54. unified_bed_leveling::g29_storage_slot = 0,
  55. unified_bed_leveling::g29_map_type;
  56. bool unified_bed_leveling::g29_c_flag;
  57. float unified_bed_leveling::g29_card_thickness = 0,
  58. unified_bed_leveling::g29_constant = 0;
  59. xy_bool_t unified_bed_leveling::xy_seen;
  60. xy_pos_t unified_bed_leveling::g29_pos;
  61. #if HAS_BED_PROBE
  62. int unified_bed_leveling::g29_grid_size;
  63. #endif
  64. /**
  65. * G29: Unified Bed Leveling by Roxy
  66. *
  67. * Parameters understood by this leveling system:
  68. *
  69. * A Activate Activate the Unified Bed Leveling system.
  70. *
  71. * B # Business Use the 'Business Card' mode of the Manual Probe subsystem with P2.
  72. * Note: A non-compressible Spark Gap feeler gauge is recommended over a business card.
  73. * In this mode of G29 P2, a business or index card is used as a shim that the nozzle can
  74. * grab onto as it is lowered. In principle, the nozzle-bed distance is the same when the
  75. * same resistance is felt in the shim. You can omit the numerical value on first invocation
  76. * of G29 P2 B to measure shim thickness. Subsequent use of 'B' will apply the previously-
  77. * measured thickness by default.
  78. *
  79. * C Continue G29 P1 C continues the generation of a partially-constructed Mesh without invalidating
  80. * previous measurements.
  81. *
  82. * C G29 P2 C tells the Manual Probe subsystem to not use the current nozzle
  83. * location in its search for the closest unmeasured Mesh Point. Instead, attempt to
  84. * start at one end of the uprobed points and Continue sequentially.
  85. *
  86. * G29 P3 C specifies the Constant for the fill. Otherwise, uses a "reasonable" value.
  87. *
  88. * C Current G29 Z C uses the Current location (instead of bed center or nearest edge).
  89. *
  90. * D Disable Disable the Unified Bed Leveling system.
  91. *
  92. * E Stow_probe Stow the probe after each sampled point.
  93. *
  94. * F # Fade Fade the amount of Mesh Based Compensation over a specified height. At the
  95. * specified height, no correction is applied and natural printer kenimatics take over. If no
  96. * number is specified for the command, 10mm is assumed to be reasonable.
  97. *
  98. * H # Height With P2, 'H' specifies the Height to raise the nozzle after each manual probe of the bed.
  99. * If omitted, the nozzle will raise by Z_CLEARANCE_BETWEEN_PROBES.
  100. *
  101. * H # Offset With P4, 'H' specifies the Offset above the mesh height to place the nozzle.
  102. * If omitted, Z_CLEARANCE_BETWEEN_PROBES will be used.
  103. *
  104. * I # Invalidate Invalidate the specified number of Mesh Points near the given 'X' 'Y'. If X or Y are omitted,
  105. * the nozzle location is used. If no 'I' value is given, only the point nearest to the location
  106. * is invalidated. Use 'T' to produce a map afterward. This command is useful to invalidate a
  107. * portion of the Mesh so it can be adjusted using other UBL tools. When attempting to invalidate
  108. * an isolated bad mesh point, the 'T' option shows the nozzle position in the Mesh with (#). You
  109. * can move the nozzle around and use this feature to select the center of the area (or cell) to
  110. * invalidate.
  111. *
  112. * J # Grid Perform a Grid Based Leveling of the current Mesh using a grid with n points on a side.
  113. * Not specifying a grid size will invoke the 3-Point leveling function.
  114. *
  115. * L Load Load Mesh from the previously activated location in the EEPROM.
  116. *
  117. * L # Load Load Mesh from the specified location in the EEPROM. Set this location as activated
  118. * for subsequent Load and Store operations.
  119. *
  120. * The P or Phase commands are used for the bulk of the work to setup a Mesh. In general, your Mesh will
  121. * start off being initialized with a G29 P0 or a G29 P1. Further refinement of the Mesh happens with
  122. * each additional Phase that processes it.
  123. *
  124. * P0 Phase 0 Zero Mesh Data and turn off the Mesh Compensation System. This reverts the
  125. * 3D Printer to the same state it was in before the Unified Bed Leveling Compensation
  126. * was turned on. Setting the entire Mesh to Zero is a special case that allows
  127. * a subsequent G or T leveling operation for backward compatibility.
  128. *
  129. * P1 Phase 1 Invalidate entire Mesh and continue with automatic generation of the Mesh data using
  130. * the Z-Probe. Usually the probe can't reach all areas that the nozzle can reach. For delta
  131. * printers only the areas where the probe and nozzle can both reach will be automatically probed.
  132. *
  133. * Unreachable points will be handled in Phase 2 and Phase 3.
  134. *
  135. * Use 'C' to leave the previous mesh intact and automatically probe needed points. This allows you
  136. * to invalidate parts of the Mesh but still use Automatic Probing.
  137. *
  138. * The 'X' and 'Y' parameters prioritize where to try and measure points. If omitted, the current
  139. * probe position is used.
  140. *
  141. * Use 'T' (Topology) to generate a report of mesh generation.
  142. *
  143. * P1 will suspend Mesh generation if the controller button is held down. Note that you may need
  144. * to press and hold the switch for several seconds if moves are underway.
  145. *
  146. * P2 Phase 2 Probe unreachable points.
  147. *
  148. * Use 'H' to set the height between Mesh points. If omitted, Z_CLEARANCE_BETWEEN_PROBES is used.
  149. * Smaller values will be quicker. Move the nozzle down till it barely touches the bed. Make sure the
  150. * nozzle is clean and unobstructed. Use caution and move slowly. This can damage your printer!
  151. * (Uses SIZE_OF_LITTLE_RAISE mm if the nozzle is moving less than BIG_RAISE_NOT_NEEDED mm.)
  152. *
  153. * The 'H' value can be negative if the Mesh dips in a large area. Press and hold the
  154. * controller button to terminate the current Phase 2 command. You can then re-issue "G29 P 2"
  155. * with an 'H' parameter more suitable for the area you're manually probing. Note that the command
  156. * tries to start in a corner of the bed where movement will be predictable. Override the distance
  157. * calculation location with the X and Y parameters. You can print a Mesh Map (G29 T) to see where
  158. * the mesh is invalidated and where the nozzle needs to move to complete the command. Use 'C' to
  159. * indicate that the search should be based on the current position.
  160. *
  161. * The 'B' parameter for this command is described above. It places the manual probe subsystem into
  162. * Business Card mode where the thickness of a business card is measured and then used to accurately
  163. * set the nozzle height in all manual probing for the duration of the command. A Business card can
  164. * be used, but you'll get better results with a flexible Shim that doesn't compress. This makes it
  165. * easier to produce similar amounts of force and get more accurate measurements. Google if you're
  166. * not sure how to use a shim.
  167. *
  168. * The 'T' (Map) parameter helps track Mesh building progress.
  169. *
  170. * NOTE: P2 requires an LCD controller!
  171. *
  172. * P3 Phase 3 Fill the unpopulated regions of the Mesh with a fixed value. There are two different paths to
  173. * go down:
  174. *
  175. * - If a 'C' constant is specified, the closest invalid mesh points to the nozzle will be filled,
  176. * and a repeat count can then also be specified with 'R'.
  177. *
  178. * - Leaving out 'C' invokes Smart Fill, which scans the mesh from the edges inward looking for
  179. * invalid mesh points. Adjacent points are used to determine the bed slope. If the bed is sloped
  180. * upward from the invalid point, it takes the value of the nearest point. If sloped downward, it's
  181. * replaced by a value that puts all three points in a line. This version of G29 P3 is a quick, easy
  182. * and (usually) safe way to populate unprobed mesh regions before continuing to G26 Mesh Validation
  183. * Pattern. Note that this populates the mesh with unverified values. Pay attention and use caution.
  184. *
  185. * P4 Phase 4 Fine tune the Mesh. The Delta Mesh Compensation System assumes the existence of
  186. * an LCD Panel. It is possible to fine tune the mesh without an LCD Panel using
  187. * G42 and M421. See the UBL documentation for further details.
  188. *
  189. * Phase 4 is meant to be used with G26 Mesh Validation to fine tune the mesh by direct editing
  190. * of Mesh Points. Raise and lower points to fine tune the mesh until it gives consistently reliable
  191. * adhesion.
  192. *
  193. * P4 moves to the closest Mesh Point (and/or the given X Y), raises the nozzle above the mesh height
  194. * by the given 'H' offset (or default 0), and waits while the controller is used to adjust the nozzle
  195. * height. On click the displayed height is saved in the mesh.
  196. *
  197. * Start Phase 4 at a specific location with X and Y. Adjust a specific number of Mesh Points with
  198. * the 'R' (Repeat) parameter. (If 'R' is left out, the whole matrix is assumed.) This command can be
  199. * terminated early (e.g., after editing the area of interest) by pressing and holding the encoder button.
  200. *
  201. * The general form is G29 P4 [R points] [X position] [Y position]
  202. *
  203. * The H [offset] parameter is useful if a shim is used to fine-tune the mesh. For a 0.4mm shim the
  204. * command would be G29 P4 H0.4. The nozzle is moved to the shim height, you adjust height to the shim,
  205. * and on click the height minus the shim thickness will be saved in the mesh.
  206. *
  207. * !!Use with caution, as a very poor mesh could cause the nozzle to crash into the bed!!
  208. *
  209. * NOTE: P4 is not available unless you have LCD support enabled!
  210. *
  211. * P5 Phase 5 Find Mean Mesh Height and Standard Deviation. Typically, it is easier to use and
  212. * work with the Mesh if it is Mean Adjusted. You can specify a C parameter to
  213. * Correct the Mesh to a 0.00 Mean Height. Adding a C parameter will automatically
  214. * execute a G29 P6 C <mean height>.
  215. *
  216. * P6 Phase 6 Shift Mesh height. The entire Mesh's height is adjusted by the height specified
  217. * with the C parameter. Being able to adjust the height of a Mesh is useful tool. It
  218. * can be used to compensate for poorly calibrated Z-Probes and other errors. Ideally,
  219. * you should have the Mesh adjusted for a Mean Height of 0.00 and the Z-Probe measuring
  220. * 0.000 at the Z Home location.
  221. *
  222. * Q Test Load specified Test Pattern to assist in checking correct operation of system. This
  223. * command is not anticipated to be of much value to the typical user. It is intended
  224. * for developers to help them verify correct operation of the Unified Bed Leveling System.
  225. *
  226. * R # Repeat Repeat this command the specified number of times. If no number is specified the
  227. * command will be repeated GRID_MAX_POINTS_X * GRID_MAX_POINTS_Y times.
  228. *
  229. * S Store Store the current Mesh in the Activated area of the EEPROM. It will also store the
  230. * current state of the Unified Bed Leveling system in the EEPROM.
  231. *
  232. * S # Store Store the current Mesh at the specified location in EEPROM. Activate this location
  233. * for subsequent Load and Store operations. Valid storage slot numbers begin at 0 and
  234. * extend to a limit related to the available EEPROM storage.
  235. *
  236. * S -1 Store Print the current Mesh as G-code that can be used to restore the mesh anytime.
  237. *
  238. * T Topology Display the Mesh Map Topology.
  239. * 'T' can be used alone (e.g., G29 T) or in combination with most of the other commands.
  240. * This option works with all Phase commands (e.g., G29 P4 R 5 T X 50 Y100 C -.1 O)
  241. * This parameter can also specify a Map Type. T0 (the default) is user-readable. T1
  242. * is suitable to paste into a spreadsheet for a 3D graph of the mesh.
  243. *
  244. * U Unlevel Perform a probe of the outer perimeter to assist in physically leveling unlevel beds.
  245. * Only used for G29 P1 T U. This speeds up the probing of the edge of the bed. Useful
  246. * when the entire bed doesn't need to be probed because it will be adjusted.
  247. *
  248. * V # Verbosity Set the verbosity level (0-4) for extra details. (Default 0)
  249. *
  250. * X # X Location for this command
  251. *
  252. * Y # Y Location for this command
  253. *
  254. * With UBL_DEVEL_DEBUGGING:
  255. *
  256. * K # Kompare Kompare current Mesh with stored Mesh #, replacing current Mesh with the result.
  257. * This command literally performs a diff between two Meshes.
  258. *
  259. * Q-1 Dump EEPROM Dump the UBL contents stored in EEPROM as HEX format. Useful for developers to help
  260. * verify correct operation of the UBL.
  261. *
  262. * W What? Display valuable UBL data.
  263. *
  264. *
  265. * Release Notes:
  266. * You MUST do M502, M500 to initialize the storage. Failure to do this will cause all
  267. * kinds of problems. Enabling EEPROM Storage is required.
  268. *
  269. * When you do a G28 and G29 P1 to automatically build your first mesh, you are going to notice that
  270. * UBL probes points increasingly further from the starting location. (The starting location defaults
  271. * to the center of the bed.) In contrast, ABL and MBL follow a zigzag pattern. The spiral pattern is
  272. * especially better for Delta printers, since it populates the center of the mesh first, allowing for
  273. * a quicker test print to verify settings. You don't need to populate the entire mesh to use it.
  274. * After all, you don't want to spend a lot of time generating a mesh only to realize the resolution
  275. * or probe offsets are incorrect. Mesh-generation gathers points starting closest to the nozzle unless
  276. * an (X,Y) coordinate pair is given.
  277. *
  278. * Unified Bed Leveling uses a lot of EEPROM storage to hold its data, and it takes some effort to get
  279. * the mesh just right. To prevent this valuable data from being destroyed as the EEPROM structure
  280. * evolves, UBL stores all mesh data at the end of EEPROM.
  281. *
  282. * UBL is founded on Edward Patel's Mesh Bed Leveling code. A big 'Thanks!' to him and the creators of
  283. * 3-Point and Grid Based leveling. Combining their contributions we now have the functionality and
  284. * features of all three systems combined.
  285. */
  286. void unified_bed_leveling::G29() {
  287. bool probe_deployed = false;
  288. if (g29_parameter_parsing()) return; // Abort on parameter error
  289. const int8_t p_val = parser.intval('P', -1);
  290. const bool may_move = p_val == 1 || p_val == 2 || p_val == 4 || parser.seen('J');
  291. TERN_(HAS_MULTI_HOTEND, const uint8_t old_tool_index = active_extruder);
  292. // Check for commands that require the printer to be homed
  293. if (may_move) {
  294. planner.synchronize();
  295. if (axes_need_homing()) gcode.home_all_axes();
  296. TERN_(HAS_MULTI_HOTEND, if (active_extruder) tool_change(0));
  297. }
  298. // Invalidate Mesh Points. This command is a little bit asymmetrical because
  299. // it directly specifies the repetition count and does not use the 'R' parameter.
  300. if (parser.seen('I')) {
  301. uint8_t cnt = 0;
  302. g29_repetition_cnt = parser.has_value() ? parser.value_int() : 1;
  303. if (g29_repetition_cnt >= GRID_MAX_POINTS) {
  304. set_all_mesh_points_to_value(NAN);
  305. }
  306. else {
  307. while (g29_repetition_cnt--) {
  308. if (cnt > 20) { cnt = 0; idle(); }
  309. const mesh_index_pair closest = find_closest_mesh_point_of_type(REAL, g29_pos);
  310. const xy_int8_t &cpos = closest.pos;
  311. if (cpos.x < 0) {
  312. // No more REAL mesh points to invalidate, so we ASSUME the user
  313. // meant to invalidate the ENTIRE mesh, which cannot be done with
  314. // find_closest_mesh_point loop which only returns REAL points.
  315. set_all_mesh_points_to_value(NAN);
  316. SERIAL_ECHOLNPGM("Entire Mesh invalidated.\n");
  317. break; // No more invalid Mesh Points to populate
  318. }
  319. z_values[cpos.x][cpos.y] = NAN;
  320. TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(cpos, 0.0f));
  321. cnt++;
  322. }
  323. }
  324. SERIAL_ECHOLNPGM("Locations invalidated.\n");
  325. }
  326. if (parser.seen('Q')) {
  327. const int test_pattern = parser.has_value() ? parser.value_int() : -99;
  328. if (!WITHIN(test_pattern, -1, 2)) {
  329. SERIAL_ECHOLNPGM("Invalid test_pattern value. (-1 to 2)\n");
  330. return;
  331. }
  332. SERIAL_ECHOLNPGM("Loading test_pattern values.\n");
  333. switch (test_pattern) {
  334. #if ENABLED(UBL_DEVEL_DEBUGGING)
  335. case -1:
  336. g29_eeprom_dump();
  337. break;
  338. #endif
  339. case 0:
  340. GRID_LOOP(x, y) { // Create a bowl shape similar to a poorly-calibrated Delta
  341. const float p1 = 0.5f * (GRID_MAX_POINTS_X) - x,
  342. p2 = 0.5f * (GRID_MAX_POINTS_Y) - y;
  343. z_values[x][y] += 2.0f * HYPOT(p1, p2);
  344. TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, z_values[x][y]));
  345. }
  346. break;
  347. case 1:
  348. LOOP_L_N(x, GRID_MAX_POINTS_X) { // Create a diagonal line several Mesh cells thick that is raised
  349. z_values[x][x] += 9.999f;
  350. z_values[x][x + (x < (GRID_MAX_POINTS_Y) - 1) ? 1 : -1] += 9.999f; // We want the altered line several mesh points thick
  351. #if ENABLED(EXTENSIBLE_UI)
  352. ExtUI::onMeshUpdate(x, x, z_values[x][x]);
  353. ExtUI::onMeshUpdate(x, (x + (x < (GRID_MAX_POINTS_Y) - 1) ? 1 : -1), z_values[x][x + (x < (GRID_MAX_POINTS_Y) - 1) ? 1 : -1]);
  354. #endif
  355. }
  356. break;
  357. case 2:
  358. // Allow the user to specify the height because 10mm is a little extreme in some cases.
  359. for (uint8_t x = (GRID_MAX_POINTS_X) / 3; x < 2 * (GRID_MAX_POINTS_X) / 3; x++) // Create a rectangular raised area in
  360. for (uint8_t y = (GRID_MAX_POINTS_Y) / 3; y < 2 * (GRID_MAX_POINTS_Y) / 3; y++) { // the center of the bed
  361. z_values[x][y] += parser.seen('C') ? g29_constant : 9.99f;
  362. TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, z_values[x][y]));
  363. }
  364. break;
  365. }
  366. }
  367. #if HAS_BED_PROBE
  368. if (parser.seen('J')) {
  369. if (g29_grid_size) { // if not 0 it is a normal n x n grid being probed
  370. save_ubl_active_state_and_disable();
  371. tilt_mesh_based_on_probed_grid(false /* false says to do normal grid probing */ );
  372. restore_ubl_active_state_and_leave();
  373. }
  374. else { // grid_size == 0 : A 3-Point leveling has been requested
  375. save_ubl_active_state_and_disable();
  376. tilt_mesh_based_on_probed_grid(true /* true says to do 3-Point leveling */ );
  377. restore_ubl_active_state_and_leave();
  378. }
  379. do_blocking_move_to_xy(0.5f * (MESH_MAX_X - (MESH_MIN_X)), 0.5f * (MESH_MAX_Y - (MESH_MIN_Y)));
  380. report_current_position();
  381. probe_deployed = true;
  382. }
  383. #endif // HAS_BED_PROBE
  384. if (parser.seen('P')) {
  385. if (WITHIN(g29_phase_value, 0, 1) && storage_slot == -1) {
  386. storage_slot = 0;
  387. SERIAL_ECHOLNPGM("Default storage slot 0 selected.");
  388. }
  389. switch (g29_phase_value) {
  390. case 0:
  391. //
  392. // Zero Mesh Data
  393. //
  394. reset();
  395. SERIAL_ECHOLNPGM("Mesh zeroed.");
  396. break;
  397. #if HAS_BED_PROBE
  398. case 1: {
  399. //
  400. // Invalidate Entire Mesh and Automatically Probe Mesh in areas that can be reached by the probe
  401. //
  402. if (!parser.seen('C')) {
  403. invalidate();
  404. SERIAL_ECHOLNPGM("Mesh invalidated. Probing mesh.");
  405. }
  406. if (g29_verbose_level > 1) {
  407. SERIAL_ECHOPAIR("Probing around (", g29_pos.x);
  408. SERIAL_CHAR(',');
  409. SERIAL_ECHO(g29_pos.y);
  410. SERIAL_ECHOLNPGM(").\n");
  411. }
  412. const xy_pos_t near_probe_xy = g29_pos + probe.offset_xy;
  413. probe_entire_mesh(near_probe_xy, parser.seen('T'), parser.seen('E'), parser.seen('U'));
  414. report_current_position();
  415. probe_deployed = true;
  416. } break;
  417. #endif // HAS_BED_PROBE
  418. case 2: {
  419. #if HAS_LCD_MENU
  420. //
  421. // Manually Probe Mesh in areas that can't be reached by the probe
  422. //
  423. SERIAL_ECHOLNPGM("Manually probing unreachable points.");
  424. do_blocking_move_to_z(Z_CLEARANCE_BETWEEN_PROBES);
  425. if (parser.seen('C') && !xy_seen) {
  426. /**
  427. * Use a good default location for the path.
  428. * The flipped > and < operators in these comparisons is intentional.
  429. * It should cause the probed points to follow a nice path on Cartesian printers.
  430. * It may make sense to have Delta printers default to the center of the bed.
  431. * Until that is decided, this can be forced with the X and Y parameters.
  432. */
  433. g29_pos.set(
  434. #if IS_KINEMATIC
  435. X_HOME_POS, Y_HOME_POS
  436. #else
  437. probe.offset_xy.x > 0 ? X_BED_SIZE : 0,
  438. probe.offset_xy.y < 0 ? Y_BED_SIZE : 0
  439. #endif
  440. );
  441. }
  442. if (parser.seen('B')) {
  443. g29_card_thickness = parser.has_value() ? parser.value_float() : measure_business_card_thickness((float) Z_CLEARANCE_BETWEEN_PROBES);
  444. if (ABS(g29_card_thickness) > 1.5f) {
  445. SERIAL_ECHOLNPGM("?Error in Business Card measurement.");
  446. return;
  447. }
  448. probe_deployed = true;
  449. }
  450. if (!position_is_reachable(g29_pos)) {
  451. SERIAL_ECHOLNPGM("XY outside printable radius.");
  452. return;
  453. }
  454. const float height = parser.floatval('H', Z_CLEARANCE_BETWEEN_PROBES);
  455. manually_probe_remaining_mesh(g29_pos, height, g29_card_thickness, parser.seen('T'));
  456. SERIAL_ECHOLNPGM("G29 P2 finished.");
  457. report_current_position();
  458. #else
  459. SERIAL_ECHOLNPGM("?P2 is only available when an LCD is present.");
  460. return;
  461. #endif
  462. } break;
  463. case 3: {
  464. /**
  465. * Populate invalid mesh areas. Proceed with caution.
  466. * Two choices are available:
  467. * - Specify a constant with the 'C' parameter.
  468. * - Allow 'G29 P3' to choose a 'reasonable' constant.
  469. */
  470. if (g29_c_flag) {
  471. if (g29_repetition_cnt >= GRID_MAX_POINTS) {
  472. set_all_mesh_points_to_value(g29_constant);
  473. }
  474. else {
  475. while (g29_repetition_cnt--) { // this only populates reachable mesh points near
  476. const mesh_index_pair closest = find_closest_mesh_point_of_type(INVALID, g29_pos);
  477. const xy_int8_t &cpos = closest.pos;
  478. if (cpos.x < 0) {
  479. // No more REAL INVALID mesh points to populate, so we ASSUME
  480. // user meant to populate ALL INVALID mesh points to value
  481. GRID_LOOP(x, y) if (isnan(z_values[x][y])) z_values[x][y] = g29_constant;
  482. break; // No more invalid Mesh Points to populate
  483. }
  484. else {
  485. z_values[cpos.x][cpos.y] = g29_constant;
  486. TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(cpos, g29_constant));
  487. }
  488. }
  489. }
  490. }
  491. else {
  492. const float cvf = parser.value_float();
  493. switch ((int)truncf(cvf * 10.0f) - 30) { // 3.1 -> 1
  494. #if ENABLED(UBL_G29_P31)
  495. case 1: {
  496. // P3.1 use least squares fit to fill missing mesh values
  497. // P3.10 zero weighting for distance, all grid points equal, best fit tilted plane
  498. // P3.11 10X weighting for nearest grid points versus farthest grid points
  499. // P3.12 100X distance weighting
  500. // P3.13 1000X distance weighting, approaches simple average of nearest points
  501. const float weight_power = (cvf - 3.10f) * 100.0f, // 3.12345 -> 2.345
  502. weight_factor = weight_power ? POW(10.0f, weight_power) : 0;
  503. smart_fill_wlsf(weight_factor);
  504. }
  505. break;
  506. #endif
  507. case 0: // P3 or P3.0
  508. default: // and anything P3.x that's not P3.1
  509. smart_fill_mesh(); // Do a 'Smart' fill using nearby known values
  510. break;
  511. }
  512. }
  513. break;
  514. }
  515. case 4: // Fine Tune (i.e., Edit) the Mesh
  516. #if HAS_LCD_MENU
  517. fine_tune_mesh(g29_pos, parser.seen('T'));
  518. #else
  519. SERIAL_ECHOLNPGM("?P4 is only available when an LCD is present.");
  520. return;
  521. #endif
  522. break;
  523. case 5: adjust_mesh_to_mean(g29_c_flag, g29_constant); break;
  524. case 6: shift_mesh_height(); break;
  525. }
  526. }
  527. #if ENABLED(UBL_DEVEL_DEBUGGING)
  528. //
  529. // Much of the 'What?' command can be eliminated. But until we are fully debugged, it is
  530. // good to have the extra information. Soon... we prune this to just a few items
  531. //
  532. if (parser.seen('W')) g29_what_command();
  533. //
  534. // When we are fully debugged, this may go away. But there are some valid
  535. // use cases for the users. So we can wait and see what to do with it.
  536. //
  537. if (parser.seen('K')) // Kompare Current Mesh Data to Specified Stored Mesh
  538. g29_compare_current_mesh_to_stored_mesh();
  539. #endif // UBL_DEVEL_DEBUGGING
  540. //
  541. // Load a Mesh from the EEPROM
  542. //
  543. if (parser.seen('L')) { // Load Current Mesh Data
  544. g29_storage_slot = parser.has_value() ? parser.value_int() : storage_slot;
  545. int16_t a = settings.calc_num_meshes();
  546. if (!a) {
  547. SERIAL_ECHOLNPGM("?EEPROM storage not available.");
  548. return;
  549. }
  550. if (!WITHIN(g29_storage_slot, 0, a - 1)) {
  551. SERIAL_ECHOLNPAIR("?Invalid storage slot.\n?Use 0 to ", a - 1);
  552. return;
  553. }
  554. settings.load_mesh(g29_storage_slot);
  555. storage_slot = g29_storage_slot;
  556. SERIAL_ECHOLNPGM("Done.");
  557. }
  558. //
  559. // Store a Mesh in the EEPROM
  560. //
  561. if (parser.seen('S')) { // Store (or Save) Current Mesh Data
  562. g29_storage_slot = parser.has_value() ? parser.value_int() : storage_slot;
  563. if (g29_storage_slot == -1) // Special case, the user wants to 'Export' the mesh to the
  564. return report_current_mesh(); // host program to be saved on the user's computer
  565. int16_t a = settings.calc_num_meshes();
  566. if (!a) {
  567. SERIAL_ECHOLNPGM("?EEPROM storage not available.");
  568. goto LEAVE;
  569. }
  570. if (!WITHIN(g29_storage_slot, 0, a - 1)) {
  571. SERIAL_ECHOLNPAIR("?Invalid storage slot.\n?Use 0 to ", a - 1);
  572. goto LEAVE;
  573. }
  574. settings.store_mesh(g29_storage_slot);
  575. storage_slot = g29_storage_slot;
  576. SERIAL_ECHOLNPGM("Done.");
  577. }
  578. if (parser.seen('T'))
  579. display_map(g29_map_type);
  580. LEAVE:
  581. #if HAS_LCD_MENU
  582. ui.reset_alert_level();
  583. ui.quick_feedback();
  584. ui.reset_status();
  585. ui.release();
  586. #endif
  587. #ifdef Z_PROBE_END_SCRIPT
  588. if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPAIR("Z Probe End Script: ", Z_PROBE_END_SCRIPT);
  589. if (probe_deployed) {
  590. planner.synchronize();
  591. gcode.process_subcommands_now_P(PSTR(Z_PROBE_END_SCRIPT));
  592. }
  593. #else
  594. UNUSED(probe_deployed);
  595. #endif
  596. TERN_(HAS_MULTI_HOTEND, tool_change(old_tool_index));
  597. return;
  598. }
  599. void unified_bed_leveling::adjust_mesh_to_mean(const bool cflag, const float value) {
  600. float sum = 0;
  601. int n = 0;
  602. GRID_LOOP(x, y)
  603. if (!isnan(z_values[x][y])) {
  604. sum += z_values[x][y];
  605. n++;
  606. }
  607. const float mean = sum / n;
  608. //
  609. // Sum the squares of difference from mean
  610. //
  611. float sum_of_diff_squared = 0;
  612. GRID_LOOP(x, y)
  613. if (!isnan(z_values[x][y]))
  614. sum_of_diff_squared += sq(z_values[x][y] - mean);
  615. SERIAL_ECHOLNPAIR("# of samples: ", n);
  616. SERIAL_ECHOLNPAIR_F("Mean Mesh Height: ", mean, 6);
  617. const float sigma = SQRT(sum_of_diff_squared / (n + 1));
  618. SERIAL_ECHOLNPAIR_F("Standard Deviation: ", sigma, 6);
  619. if (cflag)
  620. GRID_LOOP(x, y)
  621. if (!isnan(z_values[x][y])) {
  622. z_values[x][y] -= mean + value;
  623. TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, z_values[x][y]));
  624. }
  625. }
  626. void unified_bed_leveling::shift_mesh_height() {
  627. GRID_LOOP(x, y)
  628. if (!isnan(z_values[x][y])) {
  629. z_values[x][y] += g29_constant;
  630. TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, z_values[x][y]));
  631. }
  632. }
  633. #if HAS_BED_PROBE
  634. /**
  635. * Probe all invalidated locations of the mesh that can be reached by the probe.
  636. * This attempts to fill in locations closest to the nozzle's start location first.
  637. */
  638. void unified_bed_leveling::probe_entire_mesh(const xy_pos_t &near, const bool do_ubl_mesh_map, const bool stow_probe, const bool do_furthest) {
  639. probe.deploy(); // Deploy before ui.capture() to allow for PAUSE_BEFORE_DEPLOY_STOW
  640. TERN_(HAS_LCD_MENU, ui.capture());
  641. save_ubl_active_state_and_disable(); // No bed level correction so only raw data is obtained
  642. uint8_t count = GRID_MAX_POINTS;
  643. mesh_index_pair best;
  644. do {
  645. if (do_ubl_mesh_map) display_map(g29_map_type);
  646. const int point_num = (GRID_MAX_POINTS) - count + 1;
  647. SERIAL_ECHOLNPAIR("\nProbing mesh point ", point_num, "/", int(GRID_MAX_POINTS), ".\n");
  648. TERN_(HAS_DISPLAY, ui.status_printf_P(0, PSTR(S_FMT " %i/%i"), GET_TEXT(MSG_PROBING_MESH), point_num, int(GRID_MAX_POINTS)));
  649. #if HAS_LCD_MENU
  650. if (ui.button_pressed()) {
  651. ui.quick_feedback(false); // Preserve button state for click-and-hold
  652. SERIAL_ECHOLNPGM("\nMesh only partially populated.\n");
  653. ui.wait_for_release();
  654. ui.quick_feedback();
  655. ui.release();
  656. probe.stow(); // Release UI before stow to allow for PAUSE_BEFORE_DEPLOY_STOW
  657. return restore_ubl_active_state_and_leave();
  658. }
  659. #endif
  660. best = do_furthest
  661. ? find_furthest_invalid_mesh_point()
  662. : find_closest_mesh_point_of_type(INVALID, near, true);
  663. if (best.pos.x >= 0) { // mesh point found and is reachable by probe
  664. TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(best.pos, ExtUI::PROBE_START));
  665. const float measured_z = probe.probe_at_point(
  666. best.meshpos(),
  667. stow_probe ? PROBE_PT_STOW : PROBE_PT_RAISE, g29_verbose_level
  668. );
  669. z_values[best.pos.x][best.pos.y] = measured_z;
  670. #if ENABLED(EXTENSIBLE_UI)
  671. ExtUI::onMeshUpdate(best.pos, ExtUI::PROBE_FINISH);
  672. ExtUI::onMeshUpdate(best.pos, measured_z);
  673. #endif
  674. }
  675. SERIAL_FLUSH(); // Prevent host M105 buffer overrun.
  676. } while (best.pos.x >= 0 && --count);
  677. // Release UI during stow to allow for PAUSE_BEFORE_DEPLOY_STOW
  678. TERN_(HAS_LCD_MENU, ui.release());
  679. probe.stow();
  680. TERN_(HAS_LCD_MENU, ui.capture());
  681. #ifdef Z_AFTER_PROBING
  682. probe.move_z_after_probing();
  683. #endif
  684. restore_ubl_active_state_and_leave();
  685. do_blocking_move_to_xy(
  686. constrain(near.x - probe.offset_xy.x, MESH_MIN_X, MESH_MAX_X),
  687. constrain(near.y - probe.offset_xy.y, MESH_MIN_Y, MESH_MAX_Y)
  688. );
  689. }
  690. #endif // HAS_BED_PROBE
  691. #if HAS_LCD_MENU
  692. typedef void (*clickFunc_t)();
  693. bool click_and_hold(const clickFunc_t func=nullptr) {
  694. if (ui.button_pressed()) {
  695. ui.quick_feedback(false); // Preserve button state for click-and-hold
  696. const millis_t nxt = millis() + 1500UL;
  697. while (ui.button_pressed()) { // Loop while the encoder is pressed. Uses hardware flag!
  698. idle(); // idle, of course
  699. if (ELAPSED(millis(), nxt)) { // After 1.5 seconds
  700. ui.quick_feedback();
  701. if (func) (*func)();
  702. ui.wait_for_release();
  703. return true;
  704. }
  705. }
  706. }
  707. serial_delay(15);
  708. return false;
  709. }
  710. void unified_bed_leveling::move_z_with_encoder(const float &multiplier) {
  711. ui.wait_for_release();
  712. while (!ui.button_pressed()) {
  713. idle();
  714. gcode.reset_stepper_timeout(); // Keep steppers powered
  715. if (encoder_diff) {
  716. do_blocking_move_to_z(current_position.z + float(encoder_diff) * multiplier);
  717. encoder_diff = 0;
  718. }
  719. }
  720. }
  721. float unified_bed_leveling::measure_point_with_encoder() {
  722. KEEPALIVE_STATE(PAUSED_FOR_USER);
  723. move_z_with_encoder(0.01f);
  724. return current_position.z;
  725. }
  726. static void echo_and_take_a_measurement() { SERIAL_ECHOLNPGM(" and take a measurement."); }
  727. float unified_bed_leveling::measure_business_card_thickness(float in_height) {
  728. TERN_(HAS_LCD_MENU, ui.capture());
  729. save_ubl_active_state_and_disable(); // Disable bed level correction for probing
  730. do_blocking_move_to(0.5f * (MESH_MAX_X - (MESH_MIN_X)), 0.5f * (MESH_MAX_Y - (MESH_MIN_Y)), in_height);
  731. //, _MIN(planner.settings.max_feedrate_mm_s[X_AXIS], planner.settings.max_feedrate_mm_s[Y_AXIS]) * 0.5f);
  732. planner.synchronize();
  733. SERIAL_ECHOPGM("Place shim under nozzle");
  734. LCD_MESSAGEPGM(MSG_UBL_BC_INSERT);
  735. ui.return_to_status();
  736. echo_and_take_a_measurement();
  737. const float z1 = measure_point_with_encoder();
  738. do_blocking_move_to_z(current_position.z + SIZE_OF_LITTLE_RAISE);
  739. planner.synchronize();
  740. SERIAL_ECHOPGM("Remove shim");
  741. LCD_MESSAGEPGM(MSG_UBL_BC_REMOVE);
  742. echo_and_take_a_measurement();
  743. const float z2 = measure_point_with_encoder();
  744. do_blocking_move_to_z(current_position.z + Z_CLEARANCE_BETWEEN_PROBES);
  745. const float thickness = ABS(z1 - z2);
  746. if (g29_verbose_level > 1) {
  747. SERIAL_ECHOPAIR_F("Business Card is ", thickness, 4);
  748. SERIAL_ECHOLNPGM("mm thick.");
  749. }
  750. ui.release();
  751. restore_ubl_active_state_and_leave();
  752. return thickness;
  753. }
  754. void unified_bed_leveling::manually_probe_remaining_mesh(const xy_pos_t &pos, const float &z_clearance, const float &thick, const bool do_ubl_mesh_map) {
  755. TERN_(HAS_LCD_MENU, ui.capture());
  756. save_ubl_active_state_and_disable(); // No bed level correction so only raw data is obtained
  757. do_blocking_move_to_xy_z(current_position, z_clearance);
  758. ui.return_to_status();
  759. mesh_index_pair location;
  760. const xy_int8_t &lpos = location.pos;
  761. do {
  762. location = find_closest_mesh_point_of_type(INVALID, pos);
  763. // It doesn't matter if the probe can't reach the NAN location. This is a manual probe.
  764. if (!location.valid()) continue;
  765. const xyz_pos_t ppos = {
  766. mesh_index_to_xpos(lpos.x),
  767. mesh_index_to_ypos(lpos.y),
  768. Z_CLEARANCE_BETWEEN_PROBES
  769. };
  770. if (!position_is_reachable(ppos)) break; // SHOULD NOT OCCUR (find_closest_mesh_point only returns reachable points)
  771. LCD_MESSAGEPGM(MSG_UBL_MOVING_TO_NEXT);
  772. do_blocking_move_to(ppos);
  773. do_blocking_move_to_z(z_clearance);
  774. KEEPALIVE_STATE(PAUSED_FOR_USER);
  775. TERN_(HAS_LCD_MENU, ui.capture());
  776. if (do_ubl_mesh_map) display_map(g29_map_type); // show user where we're probing
  777. serialprintPGM(parser.seen('B') ? GET_TEXT(MSG_UBL_BC_INSERT) : GET_TEXT(MSG_UBL_BC_INSERT2));
  778. const float z_step = 0.01f; // existing behavior: 0.01mm per click, occasionally step
  779. //const float z_step = planner.steps_to_mm[Z_AXIS]; // approx one step each click
  780. move_z_with_encoder(z_step);
  781. if (click_and_hold()) {
  782. SERIAL_ECHOLNPGM("\nMesh only partially populated.");
  783. do_blocking_move_to_z(Z_CLEARANCE_DEPLOY_PROBE);
  784. ui.release();
  785. return restore_ubl_active_state_and_leave();
  786. }
  787. z_values[lpos.x][lpos.y] = current_position.z - thick;
  788. TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(location, z_values[lpos.x][lpos.y]));
  789. if (g29_verbose_level > 2)
  790. SERIAL_ECHOLNPAIR_F("Mesh Point Measured at: ", z_values[lpos.x][lpos.y], 6);
  791. SERIAL_FLUSH(); // Prevent host M105 buffer overrun.
  792. } while (location.valid());
  793. if (do_ubl_mesh_map) display_map(g29_map_type); // show user where we're probing
  794. restore_ubl_active_state_and_leave();
  795. do_blocking_move_to_xy_z(pos, Z_CLEARANCE_DEPLOY_PROBE);
  796. }
  797. inline void set_message_with_feedback(PGM_P const msg_P) {
  798. ui.set_status_P(msg_P);
  799. ui.quick_feedback();
  800. }
  801. void abort_fine_tune() {
  802. ui.return_to_status();
  803. do_blocking_move_to_z(Z_CLEARANCE_BETWEEN_PROBES);
  804. set_message_with_feedback(GET_TEXT(MSG_EDITING_STOPPED));
  805. }
  806. void unified_bed_leveling::fine_tune_mesh(const xy_pos_t &pos, const bool do_ubl_mesh_map) {
  807. if (!parser.seen('R')) // fine_tune_mesh() is special. If no repetition count flag is specified
  808. g29_repetition_cnt = 1; // do exactly one mesh location. Otherwise use what the parser decided.
  809. #if ENABLED(UBL_MESH_EDIT_MOVES_Z)
  810. const float h_offset = parser.seenval('H') ? parser.value_linear_units() : 0;
  811. if (!WITHIN(h_offset, 0, 10)) {
  812. SERIAL_ECHOLNPGM("Offset out of bounds. (0 to 10mm)\n");
  813. return;
  814. }
  815. #endif
  816. mesh_index_pair location;
  817. if (!position_is_reachable(pos)) {
  818. SERIAL_ECHOLNPGM("(X,Y) outside printable radius.");
  819. return;
  820. }
  821. save_ubl_active_state_and_disable();
  822. LCD_MESSAGEPGM(MSG_UBL_FINE_TUNE_MESH);
  823. TERN_(HAS_LCD_MENU, ui.capture()); // Take over control of the LCD encoder
  824. do_blocking_move_to_xy_z(pos, Z_CLEARANCE_BETWEEN_PROBES); // Move to the given XY with probe clearance
  825. TERN_(UBL_MESH_EDIT_MOVES_Z, do_blocking_move_to_z(h_offset)); // Move Z to the given 'H' offset
  826. MeshFlags done_flags{0};
  827. const xy_int8_t &lpos = location.pos;
  828. do {
  829. location = find_closest_mesh_point_of_type(SET_IN_BITMAP, pos, false, &done_flags);
  830. if (lpos.x < 0) break; // Stop when there are no more reachable points
  831. done_flags.mark(lpos); // Mark this location as 'adjusted' so a new
  832. // location is used on the next loop
  833. const xyz_pos_t raw = {
  834. mesh_index_to_xpos(lpos.x),
  835. mesh_index_to_ypos(lpos.y),
  836. Z_CLEARANCE_BETWEEN_PROBES
  837. };
  838. if (!position_is_reachable(raw)) break; // SHOULD NOT OCCUR (find_closest_mesh_point_of_type only returns reachable)
  839. do_blocking_move_to(raw); // Move the nozzle to the edit point with probe clearance
  840. TERN_(UBL_MESH_EDIT_MOVES_Z, do_blocking_move_to_z(h_offset)); // Move Z to the given 'H' offset before editing
  841. KEEPALIVE_STATE(PAUSED_FOR_USER);
  842. if (do_ubl_mesh_map) display_map(g29_map_type); // Display the current point
  843. ui.refresh();
  844. float new_z = z_values[lpos.x][lpos.y];
  845. if (isnan(new_z)) new_z = 0; // Invalid points begin at 0
  846. new_z = FLOOR(new_z * 1000) * 0.001f; // Chop off digits after the 1000ths place
  847. lcd_mesh_edit_setup(new_z);
  848. do {
  849. new_z = lcd_mesh_edit();
  850. TERN_(UBL_MESH_EDIT_MOVES_Z, do_blocking_move_to_z(h_offset + new_z)); // Move the nozzle as the point is edited
  851. idle();
  852. SERIAL_FLUSH(); // Prevent host M105 buffer overrun.
  853. } while (!ui.button_pressed());
  854. if (!lcd_map_control) ui.return_to_status(); // Just editing a single point? Return to status
  855. if (click_and_hold(abort_fine_tune)) break; // Button held down? Abort editing
  856. z_values[lpos.x][lpos.y] = new_z; // Save the updated Z value
  857. TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(location, new_z));
  858. serial_delay(20); // No switch noise
  859. ui.refresh();
  860. } while (lpos.x >= 0 && --g29_repetition_cnt > 0);
  861. ui.release();
  862. if (do_ubl_mesh_map) display_map(g29_map_type);
  863. restore_ubl_active_state_and_leave();
  864. do_blocking_move_to_xy_z(pos, Z_CLEARANCE_BETWEEN_PROBES);
  865. LCD_MESSAGEPGM(MSG_UBL_DONE_EDITING_MESH);
  866. SERIAL_ECHOLNPGM("Done Editing Mesh");
  867. if (lcd_map_control)
  868. ui.goto_screen(_lcd_ubl_output_map_lcd);
  869. else
  870. ui.return_to_status();
  871. }
  872. #endif // HAS_LCD_MENU
  873. bool unified_bed_leveling::g29_parameter_parsing() {
  874. bool err_flag = false;
  875. TERN_(HAS_LCD_MENU, set_message_with_feedback(GET_TEXT(MSG_UBL_DOING_G29)));
  876. g29_constant = 0;
  877. g29_repetition_cnt = 0;
  878. if (parser.seen('R')) {
  879. g29_repetition_cnt = parser.has_value() ? parser.value_int() : GRID_MAX_POINTS;
  880. NOMORE(g29_repetition_cnt, GRID_MAX_POINTS);
  881. if (g29_repetition_cnt < 1) {
  882. SERIAL_ECHOLNPGM("?(R)epetition count invalid (1+).\n");
  883. return UBL_ERR;
  884. }
  885. }
  886. g29_verbose_level = parser.seen('V') ? parser.value_int() : 0;
  887. if (!WITHIN(g29_verbose_level, 0, 4)) {
  888. SERIAL_ECHOLNPGM("?(V)erbose level implausible (0-4).\n");
  889. err_flag = true;
  890. }
  891. if (parser.seen('P')) {
  892. const int pv = parser.value_int();
  893. #if !HAS_BED_PROBE
  894. if (pv == 1) {
  895. SERIAL_ECHOLNPGM("G29 P1 requires a probe.\n");
  896. err_flag = true;
  897. }
  898. else
  899. #endif
  900. {
  901. g29_phase_value = pv;
  902. if (!WITHIN(g29_phase_value, 0, 6)) {
  903. SERIAL_ECHOLNPGM("?(P)hase value invalid (0-6).\n");
  904. err_flag = true;
  905. }
  906. }
  907. }
  908. if (parser.seen('J')) {
  909. #if HAS_BED_PROBE
  910. g29_grid_size = parser.has_value() ? parser.value_int() : 0;
  911. if (g29_grid_size && !WITHIN(g29_grid_size, 2, 9)) {
  912. SERIAL_ECHOLNPGM("?Invalid grid size (J) specified (2-9).\n");
  913. err_flag = true;
  914. }
  915. #else
  916. SERIAL_ECHOLNPGM("G29 J action requires a probe.\n");
  917. err_flag = true;
  918. #endif
  919. }
  920. xy_seen.x = parser.seenval('X');
  921. float sx = xy_seen.x ? parser.value_float() : current_position.x;
  922. xy_seen.y = parser.seenval('Y');
  923. float sy = xy_seen.y ? parser.value_float() : current_position.y;
  924. if (xy_seen.x != xy_seen.y) {
  925. SERIAL_ECHOLNPGM("Both X & Y locations must be specified.\n");
  926. err_flag = true;
  927. }
  928. // If X or Y are not valid, use center of the bed values
  929. if (!WITHIN(sx, X_MIN_BED, X_MAX_BED)) sx = X_CENTER;
  930. if (!WITHIN(sy, Y_MIN_BED, Y_MAX_BED)) sy = Y_CENTER;
  931. if (err_flag) return UBL_ERR;
  932. g29_pos.set(sx, sy);
  933. /**
  934. * Activate or deactivate UBL
  935. * Note: UBL's G29 restores the state set here when done.
  936. * Leveling is being enabled here with old data, possibly
  937. * none. Error handling should disable for safety...
  938. */
  939. if (parser.seen('A')) {
  940. if (parser.seen('D')) {
  941. SERIAL_ECHOLNPGM("?Can't activate and deactivate at the same time.\n");
  942. return UBL_ERR;
  943. }
  944. set_bed_leveling_enabled(true);
  945. report_state();
  946. }
  947. else if (parser.seen('D')) {
  948. set_bed_leveling_enabled(false);
  949. report_state();
  950. }
  951. // Set global 'C' flag and its value
  952. if ((g29_c_flag = parser.seen('C')))
  953. g29_constant = parser.value_float();
  954. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  955. if (parser.seenval('F')) {
  956. const float fh = parser.value_float();
  957. if (!WITHIN(fh, 0, 100)) {
  958. SERIAL_ECHOLNPGM("?(F)ade height for Bed Level Correction not plausible.\n");
  959. return UBL_ERR;
  960. }
  961. set_z_fade_height(fh);
  962. }
  963. #endif
  964. g29_map_type = parser.intval('T');
  965. if (!WITHIN(g29_map_type, 0, 2)) {
  966. SERIAL_ECHOLNPGM("Invalid map type.\n");
  967. return UBL_ERR;
  968. }
  969. return UBL_OK;
  970. }
  971. static uint8_t ubl_state_at_invocation = 0;
  972. #if ENABLED(UBL_DEVEL_DEBUGGING)
  973. static uint8_t ubl_state_recursion_chk = 0;
  974. #endif
  975. void unified_bed_leveling::save_ubl_active_state_and_disable() {
  976. #if ENABLED(UBL_DEVEL_DEBUGGING)
  977. ubl_state_recursion_chk++;
  978. if (ubl_state_recursion_chk != 1) {
  979. SERIAL_ECHOLNPGM("save_ubl_active_state_and_disabled() called multiple times in a row.");
  980. TERN_(HAS_LCD_MENU, set_message_with_feedback(GET_TEXT(MSG_UBL_SAVE_ERROR)));
  981. return;
  982. }
  983. #endif
  984. ubl_state_at_invocation = planner.leveling_active;
  985. set_bed_leveling_enabled(false);
  986. }
  987. void unified_bed_leveling::restore_ubl_active_state_and_leave() {
  988. #if ENABLED(UBL_DEVEL_DEBUGGING)
  989. if (--ubl_state_recursion_chk) {
  990. SERIAL_ECHOLNPGM("restore_ubl_active_state_and_leave() called too many times.");
  991. TERN_(HAS_LCD_MENU, set_message_with_feedback(GET_TEXT(MSG_UBL_RESTORE_ERROR)));
  992. return;
  993. }
  994. #endif
  995. set_bed_leveling_enabled(ubl_state_at_invocation);
  996. }
  997. mesh_index_pair unified_bed_leveling::find_furthest_invalid_mesh_point() {
  998. bool found_a_NAN = false, found_a_real = false;
  999. mesh_index_pair farthest { -1, -1, -99999.99 };
  1000. GRID_LOOP(i, j) {
  1001. if (!isnan(z_values[i][j])) continue; // Skip valid mesh points
  1002. // Skip unreachable points
  1003. if (!probe.can_reach(mesh_index_to_xpos(i), mesh_index_to_ypos(j)))
  1004. continue;
  1005. found_a_NAN = true;
  1006. xy_int8_t near { -1, -1 };
  1007. float d1, d2 = 99999.9f;
  1008. GRID_LOOP(k, l) {
  1009. if (isnan(z_values[k][l])) continue;
  1010. found_a_real = true;
  1011. // Add in a random weighting factor that scrambles the probing of the
  1012. // last half of the mesh (when every unprobed mesh point is one index
  1013. // from a probed location).
  1014. d1 = HYPOT(i - k, j - l) + (1.0f / ((millis() % 47) + 13));
  1015. if (d1 < d2) { // Invalid mesh point (i,j) is closer to the defined point (k,l)
  1016. d2 = d1;
  1017. near.set(i, j);
  1018. }
  1019. }
  1020. //
  1021. // At this point d2 should have the near defined mesh point to invalid mesh point (i,j)
  1022. //
  1023. if (found_a_real && near.x >= 0 && d2 > farthest.distance) {
  1024. farthest.pos = near; // Found an invalid location farther from the defined mesh point
  1025. farthest.distance = d2;
  1026. }
  1027. } // GRID_LOOP
  1028. if (!found_a_real && found_a_NAN) { // if the mesh is totally unpopulated, start the probing
  1029. farthest.pos.set((GRID_MAX_POINTS_X) / 2, (GRID_MAX_POINTS_Y) / 2);
  1030. farthest.distance = 1;
  1031. }
  1032. return farthest;
  1033. }
  1034. mesh_index_pair unified_bed_leveling::find_closest_mesh_point_of_type(const MeshPointType type, const xy_pos_t &pos, const bool probe_relative/*=false*/, MeshFlags *done_flags/*=nullptr*/) {
  1035. mesh_index_pair closest;
  1036. closest.invalidate();
  1037. closest.distance = -99999.9f;
  1038. // Get the reference position, either nozzle or probe
  1039. const xy_pos_t ref = probe_relative ? pos + probe.offset_xy : pos;
  1040. float best_so_far = 99999.99f;
  1041. GRID_LOOP(i, j) {
  1042. if ( (type == (isnan(z_values[i][j]) ? INVALID : REAL))
  1043. || (type == SET_IN_BITMAP && !done_flags->marked(i, j))
  1044. ) {
  1045. // Found a Mesh Point of the specified type!
  1046. const xy_pos_t mpos = { mesh_index_to_xpos(i), mesh_index_to_ypos(j) };
  1047. // If using the probe as the reference there are some unreachable locations.
  1048. // Also for round beds, there are grid points outside the bed the nozzle can't reach.
  1049. // Prune them from the list and ignore them till the next Phase (manual nozzle probing).
  1050. if (!(probe_relative ? probe.can_reach(mpos) : position_is_reachable(mpos)))
  1051. continue;
  1052. // Reachable. Check if it's the best_so_far location to the nozzle.
  1053. const xy_pos_t diff = current_position - mpos;
  1054. const float distance = (ref - mpos).magnitude() + diff.magnitude() * 0.1f;
  1055. // factor in the distance from the current location for the normal case
  1056. // so the nozzle isn't running all over the bed.
  1057. if (distance < best_so_far) {
  1058. best_so_far = distance; // Found a closer location with the desired value type.
  1059. closest.pos.set(i, j);
  1060. closest.distance = best_so_far;
  1061. }
  1062. }
  1063. } // GRID_LOOP
  1064. return closest;
  1065. }
  1066. /**
  1067. * 'Smart Fill': Scan from the outward edges of the mesh towards the center.
  1068. * If an invalid location is found, use the next two points (if valid) to
  1069. * calculate a 'reasonable' value for the unprobed mesh point.
  1070. */
  1071. bool unified_bed_leveling::smart_fill_one(const uint8_t x, const uint8_t y, const int8_t xdir, const int8_t ydir) {
  1072. const float v = z_values[x][y];
  1073. if (isnan(v)) { // A NAN...
  1074. const int8_t dx = x + xdir, dy = y + ydir;
  1075. const float v1 = z_values[dx][dy];
  1076. if (!isnan(v1)) { // ...next to a pair of real values?
  1077. const float v2 = z_values[dx + xdir][dy + ydir];
  1078. if (!isnan(v2)) {
  1079. z_values[x][y] = v1 < v2 ? v1 : v1 + v1 - v2;
  1080. TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, z_values[x][y]));
  1081. return true;
  1082. }
  1083. }
  1084. }
  1085. return false;
  1086. }
  1087. typedef struct { uint8_t sx, ex, sy, ey; bool yfirst; } smart_fill_info;
  1088. void unified_bed_leveling::smart_fill_mesh() {
  1089. static const smart_fill_info
  1090. info0 PROGMEM = { 0, GRID_MAX_POINTS_X, 0, GRID_MAX_POINTS_Y - 2, false }, // Bottom of the mesh looking up
  1091. info1 PROGMEM = { 0, GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y - 1, 0, false }, // Top of the mesh looking down
  1092. info2 PROGMEM = { 0, GRID_MAX_POINTS_X - 2, 0, GRID_MAX_POINTS_Y, true }, // Left side of the mesh looking right
  1093. info3 PROGMEM = { GRID_MAX_POINTS_X - 1, 0, 0, GRID_MAX_POINTS_Y, true }; // Right side of the mesh looking left
  1094. static const smart_fill_info * const info[] PROGMEM = { &info0, &info1, &info2, &info3 };
  1095. LOOP_L_N(i, COUNT(info)) {
  1096. const smart_fill_info *f = (smart_fill_info*)pgm_read_ptr(&info[i]);
  1097. const int8_t sx = pgm_read_byte(&f->sx), sy = pgm_read_byte(&f->sy),
  1098. ex = pgm_read_byte(&f->ex), ey = pgm_read_byte(&f->ey);
  1099. if (pgm_read_byte(&f->yfirst)) {
  1100. const int8_t dir = ex > sx ? 1 : -1;
  1101. for (uint8_t y = sy; y != ey; ++y)
  1102. for (uint8_t x = sx; x != ex; x += dir)
  1103. if (smart_fill_one(x, y, dir, 0)) break;
  1104. }
  1105. else {
  1106. const int8_t dir = ey > sy ? 1 : -1;
  1107. for (uint8_t x = sx; x != ex; ++x)
  1108. for (uint8_t y = sy; y != ey; y += dir)
  1109. if (smart_fill_one(x, y, 0, dir)) break;
  1110. }
  1111. }
  1112. }
  1113. #if HAS_BED_PROBE
  1114. //#define VALIDATE_MESH_TILT
  1115. #include "../../../libs/vector_3.h"
  1116. void unified_bed_leveling::tilt_mesh_based_on_probed_grid(const bool do_3_pt_leveling) {
  1117. const float x_min = probe.min_x(), x_max = probe.max_x(),
  1118. y_min = probe.min_y(), y_max = probe.max_y(),
  1119. dx = (x_max - x_min) / (g29_grid_size - 1),
  1120. dy = (y_max - y_min) / (g29_grid_size - 1);
  1121. xy_float_t points[3];
  1122. probe.get_three_points(points);
  1123. float measured_z;
  1124. bool abort_flag = false;
  1125. #ifdef VALIDATE_MESH_TILT
  1126. float z1, z2, z3; // Needed for algorithm validation below
  1127. #endif
  1128. struct linear_fit_data lsf_results;
  1129. incremental_LSF_reset(&lsf_results);
  1130. if (do_3_pt_leveling) {
  1131. SERIAL_ECHOLNPGM("Tilting mesh (1/3)");
  1132. TERN_(HAS_DISPLAY, ui.status_printf_P(0, PSTR(S_FMT " 1/3"), GET_TEXT(MSG_LCD_TILTING_MESH)));
  1133. measured_z = probe.probe_at_point(points[0], PROBE_PT_RAISE, g29_verbose_level);
  1134. if (isnan(measured_z))
  1135. abort_flag = true;
  1136. else {
  1137. measured_z -= get_z_correction(points[0]);
  1138. #ifdef VALIDATE_MESH_TILT
  1139. z1 = measured_z;
  1140. #endif
  1141. if (g29_verbose_level > 3) {
  1142. serial_spaces(16);
  1143. SERIAL_ECHOLNPAIR("Corrected_Z=", measured_z);
  1144. }
  1145. incremental_LSF(&lsf_results, points[0], measured_z);
  1146. }
  1147. if (!abort_flag) {
  1148. SERIAL_ECHOLNPGM("Tilting mesh (2/3)");
  1149. TERN_(HAS_DISPLAY, ui.status_printf_P(0, PSTR(S_FMT " 2/3"), GET_TEXT(MSG_LCD_TILTING_MESH)));
  1150. measured_z = probe.probe_at_point(points[1], PROBE_PT_RAISE, g29_verbose_level);
  1151. #ifdef VALIDATE_MESH_TILT
  1152. z2 = measured_z;
  1153. #endif
  1154. if (isnan(measured_z))
  1155. abort_flag = true;
  1156. else {
  1157. measured_z -= get_z_correction(points[1]);
  1158. if (g29_verbose_level > 3) {
  1159. serial_spaces(16);
  1160. SERIAL_ECHOLNPAIR("Corrected_Z=", measured_z);
  1161. }
  1162. incremental_LSF(&lsf_results, points[1], measured_z);
  1163. }
  1164. }
  1165. if (!abort_flag) {
  1166. SERIAL_ECHOLNPGM("Tilting mesh (3/3)");
  1167. TERN_(HAS_DISPLAY, ui.status_printf_P(0, PSTR(S_FMT " 3/3"), GET_TEXT(MSG_LCD_TILTING_MESH)));
  1168. measured_z = probe.probe_at_point(points[2], PROBE_PT_STOW, g29_verbose_level);
  1169. #ifdef VALIDATE_MESH_TILT
  1170. z3 = measured_z;
  1171. #endif
  1172. if (isnan(measured_z))
  1173. abort_flag = true;
  1174. else {
  1175. measured_z -= get_z_correction(points[2]);
  1176. if (g29_verbose_level > 3) {
  1177. serial_spaces(16);
  1178. SERIAL_ECHOLNPAIR("Corrected_Z=", measured_z);
  1179. }
  1180. incremental_LSF(&lsf_results, points[2], measured_z);
  1181. }
  1182. }
  1183. probe.stow();
  1184. #ifdef Z_AFTER_PROBING
  1185. probe.move_z_after_probing();
  1186. #endif
  1187. if (abort_flag) {
  1188. SERIAL_ECHOLNPGM("?Error probing point. Aborting operation.");
  1189. return;
  1190. }
  1191. }
  1192. else { // !do_3_pt_leveling
  1193. bool zig_zag = false;
  1194. const uint16_t total_points = sq(g29_grid_size);
  1195. uint16_t point_num = 1;
  1196. xy_pos_t rpos;
  1197. LOOP_L_N(ix, g29_grid_size) {
  1198. rpos.x = x_min + ix * dx;
  1199. LOOP_L_N(iy, g29_grid_size) {
  1200. rpos.y = y_min + dy * (zig_zag ? g29_grid_size - 1 - iy : iy);
  1201. if (!abort_flag) {
  1202. SERIAL_ECHOLNPAIR("Tilting mesh point ", point_num, "/", total_points, "\n");
  1203. TERN_(HAS_DISPLAY, ui.status_printf_P(0, PSTR(S_FMT " %i/%i"), GET_TEXT(MSG_LCD_TILTING_MESH), point_num, total_points));
  1204. measured_z = probe.probe_at_point(rpos, parser.seen('E') ? PROBE_PT_STOW : PROBE_PT_RAISE, g29_verbose_level); // TODO: Needs error handling
  1205. abort_flag = isnan(measured_z);
  1206. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1207. if (DEBUGGING(LEVELING)) {
  1208. const xy_pos_t lpos = rpos.asLogical();
  1209. DEBUG_CHAR('(');
  1210. DEBUG_ECHO_F(rpos.x, 7);
  1211. DEBUG_CHAR(',');
  1212. DEBUG_ECHO_F(rpos.y, 7);
  1213. DEBUG_ECHOPAIR_F(") logical: (", lpos.x, 7);
  1214. DEBUG_CHAR(',');
  1215. DEBUG_ECHO_F(lpos.y, 7);
  1216. DEBUG_ECHOPAIR_F(") measured: ", measured_z, 7);
  1217. DEBUG_ECHOPAIR_F(" correction: ", get_z_correction(rpos), 7);
  1218. }
  1219. #endif
  1220. measured_z -= get_z_correction(rpos) /* + probe.offset.z */ ;
  1221. if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPAIR_F(" final >>>---> ", measured_z, 7);
  1222. if (g29_verbose_level > 3) {
  1223. serial_spaces(16);
  1224. SERIAL_ECHOLNPAIR("Corrected_Z=", measured_z);
  1225. }
  1226. incremental_LSF(&lsf_results, rpos, measured_z);
  1227. }
  1228. point_num++;
  1229. }
  1230. zig_zag ^= true;
  1231. }
  1232. }
  1233. probe.stow();
  1234. #ifdef Z_AFTER_PROBING
  1235. probe.move_z_after_probing();
  1236. #endif
  1237. if (abort_flag || finish_incremental_LSF(&lsf_results)) {
  1238. SERIAL_ECHOPGM("Could not complete LSF!");
  1239. return;
  1240. }
  1241. vector_3 normal = vector_3(lsf_results.A, lsf_results.B, 1).get_normal();
  1242. if (g29_verbose_level > 2) {
  1243. SERIAL_ECHOPAIR_F("bed plane normal = [", normal.x, 7);
  1244. SERIAL_CHAR(',');
  1245. SERIAL_ECHO_F(normal.y, 7);
  1246. SERIAL_CHAR(',');
  1247. SERIAL_ECHO_F(normal.z, 7);
  1248. SERIAL_ECHOLNPGM("]");
  1249. }
  1250. matrix_3x3 rotation = matrix_3x3::create_look_at(vector_3(lsf_results.A, lsf_results.B, 1));
  1251. GRID_LOOP(i, j) {
  1252. float mx = mesh_index_to_xpos(i),
  1253. my = mesh_index_to_ypos(j),
  1254. mz = z_values[i][j];
  1255. if (DEBUGGING(LEVELING)) {
  1256. DEBUG_ECHOPAIR_F("before rotation = [", mx, 7);
  1257. DEBUG_CHAR(',');
  1258. DEBUG_ECHO_F(my, 7);
  1259. DEBUG_CHAR(',');
  1260. DEBUG_ECHO_F(mz, 7);
  1261. DEBUG_ECHOPGM("] ---> ");
  1262. DEBUG_DELAY(20);
  1263. }
  1264. apply_rotation_xyz(rotation, mx, my, mz);
  1265. if (DEBUGGING(LEVELING)) {
  1266. DEBUG_ECHOPAIR_F("after rotation = [", mx, 7);
  1267. DEBUG_CHAR(',');
  1268. DEBUG_ECHO_F(my, 7);
  1269. DEBUG_CHAR(',');
  1270. DEBUG_ECHO_F(mz, 7);
  1271. DEBUG_ECHOLNPGM("]");
  1272. DEBUG_DELAY(20);
  1273. }
  1274. z_values[i][j] = mz - lsf_results.D;
  1275. TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(i, j, z_values[i][j]));
  1276. }
  1277. if (DEBUGGING(LEVELING)) {
  1278. rotation.debug(PSTR("rotation matrix:\n"));
  1279. DEBUG_ECHOPAIR_F("LSF Results A=", lsf_results.A, 7);
  1280. DEBUG_ECHOPAIR_F(" B=", lsf_results.B, 7);
  1281. DEBUG_ECHOLNPAIR_F(" D=", lsf_results.D, 7);
  1282. DEBUG_DELAY(55);
  1283. DEBUG_ECHOPAIR_F("bed plane normal = [", normal.x, 7);
  1284. DEBUG_CHAR(',');
  1285. DEBUG_ECHO_F(normal.y, 7);
  1286. DEBUG_CHAR(',');
  1287. DEBUG_ECHO_F(normal.z, 7);
  1288. DEBUG_ECHOLNPGM("]");
  1289. DEBUG_EOL();
  1290. /**
  1291. * Use the code below to check the validity of the mesh tilting algorithm.
  1292. * 3-Point Mesh Tilt uses the same algorithm as grid-based tilting, but only
  1293. * three points are used in the calculation. This guarantees that each probed point
  1294. * has an exact match when get_z_correction() for that location is calculated.
  1295. * The Z error between the probed point locations and the get_z_correction()
  1296. * numbers for those locations should be 0.
  1297. */
  1298. #ifdef VALIDATE_MESH_TILT
  1299. auto d_from = []{ DEBUG_ECHOPGM("D from "); };
  1300. auto normed = [&](const xy_pos_t &pos, const float &zadd) {
  1301. return normal.x * pos.x + normal.y * pos.y + zadd;
  1302. };
  1303. auto debug_pt = [](PGM_P const pre, const xy_pos_t &pos, const float &zadd) {
  1304. d_from(); serialprintPGM(pre);
  1305. DEBUG_ECHO_F(normed(pos, zadd), 6);
  1306. DEBUG_ECHOLNPAIR_F(" Z error = ", zadd - get_z_correction(pos), 6);
  1307. };
  1308. debug_pt(PSTR("1st point: "), probe_pt[0], normal.z * z1);
  1309. debug_pt(PSTR("2nd point: "), probe_pt[1], normal.z * z2);
  1310. debug_pt(PSTR("3rd point: "), probe_pt[2], normal.z * z3);
  1311. d_from(); DEBUG_ECHOPGM("safe home with Z=");
  1312. DEBUG_ECHOLNPAIR_F("0 : ", normed(safe_homing_xy, 0), 6);
  1313. d_from(); DEBUG_ECHOPGM("safe home with Z=");
  1314. DEBUG_ECHOLNPAIR_F("mesh value ", normed(safe_homing_xy, get_z_correction(safe_homing_xy)), 6);
  1315. DEBUG_ECHOPAIR(" Z error = (", Z_SAFE_HOMING_X_POINT, ",", Z_SAFE_HOMING_Y_POINT);
  1316. DEBUG_ECHOLNPAIR_F(") = ", get_z_correction(safe_homing_xy), 6);
  1317. #endif
  1318. } // DEBUGGING(LEVELING)
  1319. }
  1320. #endif // HAS_BED_PROBE
  1321. #if ENABLED(UBL_G29_P31)
  1322. void unified_bed_leveling::smart_fill_wlsf(const float &weight_factor) {
  1323. // For each undefined mesh point, compute a distance-weighted least squares fit
  1324. // from all the originally populated mesh points, weighted toward the point
  1325. // being extrapolated so that nearby points will have greater influence on
  1326. // the point being extrapolated. Then extrapolate the mesh point from WLSF.
  1327. static_assert((GRID_MAX_POINTS_Y) <= 16, "GRID_MAX_POINTS_Y too big");
  1328. uint16_t bitmap[GRID_MAX_POINTS_X] = { 0 };
  1329. struct linear_fit_data lsf_results;
  1330. SERIAL_ECHOPGM("Extrapolating mesh...");
  1331. const float weight_scaled = weight_factor * _MAX(MESH_X_DIST, MESH_Y_DIST);
  1332. GRID_LOOP(jx, jy) if (!isnan(z_values[jx][jy])) SBI(bitmap[jx], jy);
  1333. xy_pos_t ppos;
  1334. LOOP_L_N(ix, GRID_MAX_POINTS_X) {
  1335. ppos.x = mesh_index_to_xpos(ix);
  1336. LOOP_L_N(iy, GRID_MAX_POINTS_Y) {
  1337. ppos.y = mesh_index_to_ypos(iy);
  1338. if (isnan(z_values[ix][iy])) {
  1339. // undefined mesh point at (ppos.x,ppos.y), compute weighted LSF from original valid mesh points.
  1340. incremental_LSF_reset(&lsf_results);
  1341. xy_pos_t rpos;
  1342. LOOP_L_N(jx, GRID_MAX_POINTS_X) {
  1343. rpos.x = mesh_index_to_xpos(jx);
  1344. LOOP_L_N(jy, GRID_MAX_POINTS_Y) {
  1345. if (TEST(bitmap[jx], jy)) {
  1346. rpos.y = mesh_index_to_ypos(jy);
  1347. const float rz = z_values[jx][jy],
  1348. w = 1.0f + weight_scaled / (rpos - ppos).magnitude();
  1349. incremental_WLSF(&lsf_results, rpos, rz, w);
  1350. }
  1351. }
  1352. }
  1353. if (finish_incremental_LSF(&lsf_results)) {
  1354. SERIAL_ECHOLNPGM("Insufficient data");
  1355. return;
  1356. }
  1357. const float ez = -lsf_results.D - lsf_results.A * ppos.x - lsf_results.B * ppos.y;
  1358. z_values[ix][iy] = ez;
  1359. TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(ix, iy, z_values[ix][iy]));
  1360. idle(); // housekeeping
  1361. }
  1362. }
  1363. }
  1364. SERIAL_ECHOLNPGM("done");
  1365. }
  1366. #endif // UBL_G29_P31
  1367. #if ENABLED(UBL_DEVEL_DEBUGGING)
  1368. /**
  1369. * Much of the 'What?' command can be eliminated. But until we are fully debugged, it is
  1370. * good to have the extra information. Soon... we prune this to just a few items
  1371. */
  1372. void unified_bed_leveling::g29_what_command() {
  1373. report_state();
  1374. if (storage_slot == -1)
  1375. SERIAL_ECHOPGM("No Mesh Loaded.");
  1376. else
  1377. SERIAL_ECHOPAIR("Mesh ", storage_slot, " Loaded.");
  1378. SERIAL_EOL();
  1379. serial_delay(50);
  1380. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1381. SERIAL_ECHOLNPAIR_F("Fade Height M420 Z", planner.z_fade_height, 4);
  1382. #endif
  1383. adjust_mesh_to_mean(g29_c_flag, g29_constant);
  1384. #if HAS_BED_PROBE
  1385. SERIAL_ECHOLNPAIR_F("Probe Offset M851 Z", probe.offset.z, 7);
  1386. #endif
  1387. SERIAL_ECHOLNPAIR("MESH_MIN_X " STRINGIFY(MESH_MIN_X) "=", MESH_MIN_X); serial_delay(50);
  1388. SERIAL_ECHOLNPAIR("MESH_MIN_Y " STRINGIFY(MESH_MIN_Y) "=", MESH_MIN_Y); serial_delay(50);
  1389. SERIAL_ECHOLNPAIR("MESH_MAX_X " STRINGIFY(MESH_MAX_X) "=", MESH_MAX_X); serial_delay(50);
  1390. SERIAL_ECHOLNPAIR("MESH_MAX_Y " STRINGIFY(MESH_MAX_Y) "=", MESH_MAX_Y); serial_delay(50);
  1391. SERIAL_ECHOLNPAIR("GRID_MAX_POINTS_X ", GRID_MAX_POINTS_X); serial_delay(50);
  1392. SERIAL_ECHOLNPAIR("GRID_MAX_POINTS_Y ", GRID_MAX_POINTS_Y); serial_delay(50);
  1393. SERIAL_ECHOLNPAIR("MESH_X_DIST ", MESH_X_DIST);
  1394. SERIAL_ECHOLNPAIR("MESH_Y_DIST ", MESH_Y_DIST); serial_delay(50);
  1395. SERIAL_ECHOPGM("X-Axis Mesh Points at: ");
  1396. LOOP_L_N(i, GRID_MAX_POINTS_X) {
  1397. SERIAL_ECHO_F(LOGICAL_X_POSITION(mesh_index_to_xpos(i)), 3);
  1398. SERIAL_ECHOPGM(" ");
  1399. serial_delay(25);
  1400. }
  1401. SERIAL_EOL();
  1402. SERIAL_ECHOPGM("Y-Axis Mesh Points at: ");
  1403. LOOP_L_N(i, GRID_MAX_POINTS_Y) {
  1404. SERIAL_ECHO_F(LOGICAL_Y_POSITION(mesh_index_to_ypos(i)), 3);
  1405. SERIAL_ECHOPGM(" ");
  1406. serial_delay(25);
  1407. }
  1408. SERIAL_EOL();
  1409. #if HAS_KILL
  1410. SERIAL_ECHOLNPAIR("Kill pin on :", int(KILL_PIN), " state:", READ(KILL_PIN));
  1411. #endif
  1412. SERIAL_EOL();
  1413. serial_delay(50);
  1414. #if ENABLED(UBL_DEVEL_DEBUGGING)
  1415. SERIAL_ECHOLNPAIR("ubl_state_at_invocation :", ubl_state_at_invocation, "\nubl_state_recursion_chk :", ubl_state_recursion_chk);
  1416. serial_delay(50);
  1417. SERIAL_ECHOLNPAIR("Meshes go from ", hex_address((void*)settings.meshes_start_index()), " to ", hex_address((void*)settings.meshes_end_index()));
  1418. serial_delay(50);
  1419. SERIAL_ECHOLNPAIR("sizeof(ubl) : ", (int)sizeof(ubl)); SERIAL_EOL();
  1420. SERIAL_ECHOLNPAIR("z_value[][] size: ", (int)sizeof(z_values)); SERIAL_EOL();
  1421. serial_delay(25);
  1422. SERIAL_ECHOLNPAIR("EEPROM free for UBL: ", hex_address((void*)(settings.meshes_end_index() - settings.meshes_start_index())));
  1423. serial_delay(50);
  1424. SERIAL_ECHOLNPAIR("EEPROM can hold ", settings.calc_num_meshes(), " meshes.\n");
  1425. serial_delay(25);
  1426. #endif // UBL_DEVEL_DEBUGGING
  1427. if (!sanity_check()) {
  1428. echo_name();
  1429. SERIAL_ECHOLNPGM(" sanity checks passed.");
  1430. }
  1431. }
  1432. /**
  1433. * When we are fully debugged, the EEPROM dump command will get deleted also. But
  1434. * right now, it is good to have the extra information. Soon... we prune this.
  1435. */
  1436. void unified_bed_leveling::g29_eeprom_dump() {
  1437. uint8_t cccc;
  1438. SERIAL_ECHO_MSG("EEPROM Dump:");
  1439. persistentStore.access_start();
  1440. for (uint16_t i = 0; i < persistentStore.capacity(); i += 16) {
  1441. if (!(i & 0x3)) idle();
  1442. print_hex_word(i);
  1443. SERIAL_ECHOPGM(": ");
  1444. for (uint16_t j = 0; j < 16; j++) {
  1445. persistentStore.read_data(i + j, &cccc, sizeof(uint8_t));
  1446. print_hex_byte(cccc);
  1447. SERIAL_CHAR(' ');
  1448. }
  1449. SERIAL_EOL();
  1450. }
  1451. SERIAL_EOL();
  1452. persistentStore.access_finish();
  1453. }
  1454. /**
  1455. * When we are fully debugged, this may go away. But there are some valid
  1456. * use cases for the users. So we can wait and see what to do with it.
  1457. */
  1458. void unified_bed_leveling::g29_compare_current_mesh_to_stored_mesh() {
  1459. const int16_t a = settings.calc_num_meshes();
  1460. if (!a) {
  1461. SERIAL_ECHOLNPGM("?EEPROM storage not available.");
  1462. return;
  1463. }
  1464. if (!parser.has_value() || !WITHIN(g29_storage_slot, 0, a - 1)) {
  1465. SERIAL_ECHOLNPAIR("?Invalid storage slot.\n?Use 0 to ", a - 1);
  1466. return;
  1467. }
  1468. g29_storage_slot = parser.value_int();
  1469. float tmp_z_values[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y];
  1470. settings.load_mesh(g29_storage_slot, &tmp_z_values);
  1471. SERIAL_ECHOLNPAIR("Subtracting mesh in slot ", g29_storage_slot, " from current mesh.");
  1472. GRID_LOOP(x, y) {
  1473. z_values[x][y] -= tmp_z_values[x][y];
  1474. TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, z_values[x][y]));
  1475. }
  1476. }
  1477. #endif // UBL_DEVEL_DEBUGGING
  1478. #endif // AUTO_BED_LEVELING_UBL