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.

ubl_G29.cpp 69KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763
  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. save_ubl_active_state_and_disable();
  370. tilt_mesh_based_on_probed_grid(g29_grid_size == 0); // Zero size does 3-Point
  371. restore_ubl_active_state_and_leave();
  372. #if ENABLED(UBL_G29_J_RECENTER)
  373. do_blocking_move_to_xy(0.5f * ((MESH_MIN_X) + (MESH_MAX_X)), 0.5f * ((MESH_MIN_Y) + (MESH_MAX_Y)));
  374. #endif
  375. report_current_position();
  376. probe_deployed = true;
  377. }
  378. #endif // HAS_BED_PROBE
  379. if (parser.seen('P')) {
  380. if (WITHIN(g29_phase_value, 0, 1) && storage_slot == -1) {
  381. storage_slot = 0;
  382. SERIAL_ECHOLNPGM("Default storage slot 0 selected.");
  383. }
  384. switch (g29_phase_value) {
  385. case 0:
  386. //
  387. // Zero Mesh Data
  388. //
  389. reset();
  390. SERIAL_ECHOLNPGM("Mesh zeroed.");
  391. break;
  392. #if HAS_BED_PROBE
  393. case 1: {
  394. //
  395. // Invalidate Entire Mesh and Automatically Probe Mesh in areas that can be reached by the probe
  396. //
  397. if (!parser.seen('C')) {
  398. invalidate();
  399. SERIAL_ECHOLNPGM("Mesh invalidated. Probing mesh.");
  400. }
  401. if (g29_verbose_level > 1) {
  402. SERIAL_ECHOPAIR("Probing around (", g29_pos.x);
  403. SERIAL_CHAR(',');
  404. SERIAL_DECIMAL(g29_pos.y);
  405. SERIAL_ECHOLNPGM(").\n");
  406. }
  407. const xy_pos_t near_probe_xy = g29_pos + probe.offset_xy;
  408. probe_entire_mesh(near_probe_xy, parser.seen('T'), parser.seen('E'), parser.seen('U'));
  409. report_current_position();
  410. probe_deployed = true;
  411. } break;
  412. #endif // HAS_BED_PROBE
  413. case 2: {
  414. #if HAS_LCD_MENU
  415. //
  416. // Manually Probe Mesh in areas that can't be reached by the probe
  417. //
  418. SERIAL_ECHOLNPGM("Manually probing unreachable points.");
  419. do_blocking_move_to_z(Z_CLEARANCE_BETWEEN_PROBES);
  420. if (parser.seen('C') && !xy_seen) {
  421. /**
  422. * Use a good default location for the path.
  423. * The flipped > and < operators in these comparisons is intentional.
  424. * It should cause the probed points to follow a nice path on Cartesian printers.
  425. * It may make sense to have Delta printers default to the center of the bed.
  426. * Until that is decided, this can be forced with the X and Y parameters.
  427. */
  428. g29_pos.set(
  429. #if IS_KINEMATIC
  430. X_HOME_POS, Y_HOME_POS
  431. #else
  432. probe.offset_xy.x > 0 ? X_BED_SIZE : 0,
  433. probe.offset_xy.y < 0 ? Y_BED_SIZE : 0
  434. #endif
  435. );
  436. }
  437. if (parser.seen('B')) {
  438. g29_card_thickness = parser.has_value() ? parser.value_float() : measure_business_card_thickness(float(Z_CLEARANCE_BETWEEN_PROBES));
  439. if (ABS(g29_card_thickness) > 1.5f) {
  440. SERIAL_ECHOLNPGM("?Error in Business Card measurement.");
  441. return;
  442. }
  443. probe_deployed = true;
  444. }
  445. if (!position_is_reachable(g29_pos)) {
  446. SERIAL_ECHOLNPGM("XY outside printable radius.");
  447. return;
  448. }
  449. const float height = parser.floatval('H', Z_CLEARANCE_BETWEEN_PROBES);
  450. manually_probe_remaining_mesh(g29_pos, height, g29_card_thickness, parser.seen('T'));
  451. SERIAL_ECHOLNPGM("G29 P2 finished.");
  452. report_current_position();
  453. #else
  454. SERIAL_ECHOLNPGM("?P2 is only available when an LCD is present.");
  455. return;
  456. #endif
  457. } break;
  458. case 3: {
  459. /**
  460. * Populate invalid mesh areas. Proceed with caution.
  461. * Two choices are available:
  462. * - Specify a constant with the 'C' parameter.
  463. * - Allow 'G29 P3' to choose a 'reasonable' constant.
  464. */
  465. if (g29_c_flag) {
  466. if (g29_repetition_cnt >= GRID_MAX_POINTS) {
  467. set_all_mesh_points_to_value(g29_constant);
  468. }
  469. else {
  470. while (g29_repetition_cnt--) { // this only populates reachable mesh points near
  471. const mesh_index_pair closest = find_closest_mesh_point_of_type(INVALID, g29_pos);
  472. const xy_int8_t &cpos = closest.pos;
  473. if (cpos.x < 0) {
  474. // No more REAL INVALID mesh points to populate, so we ASSUME
  475. // user meant to populate ALL INVALID mesh points to value
  476. GRID_LOOP(x, y) if (isnan(z_values[x][y])) z_values[x][y] = g29_constant;
  477. break; // No more invalid Mesh Points to populate
  478. }
  479. else {
  480. z_values[cpos.x][cpos.y] = g29_constant;
  481. TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(cpos, g29_constant));
  482. }
  483. }
  484. }
  485. }
  486. else {
  487. const float cvf = parser.value_float();
  488. switch ((int)truncf(cvf * 10.0f) - 30) { // 3.1 -> 1
  489. #if ENABLED(UBL_G29_P31)
  490. case 1: {
  491. // P3.1 use least squares fit to fill missing mesh values
  492. // P3.10 zero weighting for distance, all grid points equal, best fit tilted plane
  493. // P3.11 10X weighting for nearest grid points versus farthest grid points
  494. // P3.12 100X distance weighting
  495. // P3.13 1000X distance weighting, approaches simple average of nearest points
  496. const float weight_power = (cvf - 3.10f) * 100.0f, // 3.12345 -> 2.345
  497. weight_factor = weight_power ? POW(10.0f, weight_power) : 0;
  498. smart_fill_wlsf(weight_factor);
  499. }
  500. break;
  501. #endif
  502. case 0: // P3 or P3.0
  503. default: // and anything P3.x that's not P3.1
  504. smart_fill_mesh(); // Do a 'Smart' fill using nearby known values
  505. break;
  506. }
  507. }
  508. break;
  509. }
  510. case 4: // Fine Tune (i.e., Edit) the Mesh
  511. #if HAS_LCD_MENU
  512. fine_tune_mesh(g29_pos, parser.seen('T'));
  513. #else
  514. SERIAL_ECHOLNPGM("?P4 is only available when an LCD is present.");
  515. return;
  516. #endif
  517. break;
  518. case 5: adjust_mesh_to_mean(g29_c_flag, g29_constant); break;
  519. case 6: shift_mesh_height(); break;
  520. }
  521. }
  522. #if ENABLED(UBL_DEVEL_DEBUGGING)
  523. //
  524. // Much of the 'What?' command can be eliminated. But until we are fully debugged, it is
  525. // good to have the extra information. Soon... we prune this to just a few items
  526. //
  527. if (parser.seen('W')) g29_what_command();
  528. //
  529. // When we are fully debugged, this may go away. But there are some valid
  530. // use cases for the users. So we can wait and see what to do with it.
  531. //
  532. if (parser.seen('K')) // Kompare Current Mesh Data to Specified Stored Mesh
  533. g29_compare_current_mesh_to_stored_mesh();
  534. #endif // UBL_DEVEL_DEBUGGING
  535. //
  536. // Load a Mesh from the EEPROM
  537. //
  538. if (parser.seen('L')) { // Load Current Mesh Data
  539. g29_storage_slot = parser.has_value() ? parser.value_int() : storage_slot;
  540. int16_t a = settings.calc_num_meshes();
  541. if (!a) {
  542. SERIAL_ECHOLNPGM("?EEPROM storage not available.");
  543. return;
  544. }
  545. if (!WITHIN(g29_storage_slot, 0, a - 1)) {
  546. SERIAL_ECHOLNPAIR("?Invalid storage slot.\n?Use 0 to ", a - 1);
  547. return;
  548. }
  549. settings.load_mesh(g29_storage_slot);
  550. storage_slot = g29_storage_slot;
  551. SERIAL_ECHOLNPGM("Done.");
  552. }
  553. //
  554. // Store a Mesh in the EEPROM
  555. //
  556. if (parser.seen('S')) { // Store (or Save) Current Mesh Data
  557. g29_storage_slot = parser.has_value() ? parser.value_int() : storage_slot;
  558. if (g29_storage_slot == -1) // Special case, the user wants to 'Export' the mesh to the
  559. return report_current_mesh(); // host program to be saved on the user's computer
  560. int16_t a = settings.calc_num_meshes();
  561. if (!a) {
  562. SERIAL_ECHOLNPGM("?EEPROM storage not available.");
  563. goto LEAVE;
  564. }
  565. if (!WITHIN(g29_storage_slot, 0, a - 1)) {
  566. SERIAL_ECHOLNPAIR("?Invalid storage slot.\n?Use 0 to ", a - 1);
  567. goto LEAVE;
  568. }
  569. settings.store_mesh(g29_storage_slot);
  570. storage_slot = g29_storage_slot;
  571. SERIAL_ECHOLNPGM("Done.");
  572. }
  573. if (parser.seen('T'))
  574. display_map(g29_map_type);
  575. LEAVE:
  576. #if HAS_LCD_MENU
  577. ui.reset_alert_level();
  578. ui.quick_feedback();
  579. ui.reset_status();
  580. ui.release();
  581. #endif
  582. #ifdef Z_PROBE_END_SCRIPT
  583. if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPAIR("Z Probe End Script: ", Z_PROBE_END_SCRIPT);
  584. if (probe_deployed) {
  585. planner.synchronize();
  586. gcode.process_subcommands_now_P(PSTR(Z_PROBE_END_SCRIPT));
  587. }
  588. #else
  589. UNUSED(probe_deployed);
  590. #endif
  591. TERN_(HAS_MULTI_HOTEND, tool_change(old_tool_index));
  592. return;
  593. }
  594. void unified_bed_leveling::adjust_mesh_to_mean(const bool cflag, const float value) {
  595. float sum = 0;
  596. int n = 0;
  597. GRID_LOOP(x, y)
  598. if (!isnan(z_values[x][y])) {
  599. sum += z_values[x][y];
  600. n++;
  601. }
  602. const float mean = sum / n;
  603. //
  604. // Sum the squares of difference from mean
  605. //
  606. float sum_of_diff_squared = 0;
  607. GRID_LOOP(x, y)
  608. if (!isnan(z_values[x][y]))
  609. sum_of_diff_squared += sq(z_values[x][y] - mean);
  610. SERIAL_ECHOLNPAIR("# of samples: ", n);
  611. SERIAL_ECHOLNPAIR_F("Mean Mesh Height: ", mean, 6);
  612. const float sigma = SQRT(sum_of_diff_squared / (n + 1));
  613. SERIAL_ECHOLNPAIR_F("Standard Deviation: ", sigma, 6);
  614. if (cflag)
  615. GRID_LOOP(x, y)
  616. if (!isnan(z_values[x][y])) {
  617. z_values[x][y] -= mean + value;
  618. TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, z_values[x][y]));
  619. }
  620. }
  621. void unified_bed_leveling::shift_mesh_height() {
  622. GRID_LOOP(x, y)
  623. if (!isnan(z_values[x][y])) {
  624. z_values[x][y] += g29_constant;
  625. TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, z_values[x][y]));
  626. }
  627. }
  628. #if HAS_BED_PROBE
  629. /**
  630. * Probe all invalidated locations of the mesh that can be reached by the probe.
  631. * This attempts to fill in locations closest to the nozzle's start location first.
  632. */
  633. 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) {
  634. probe.deploy(); // Deploy before ui.capture() to allow for PAUSE_BEFORE_DEPLOY_STOW
  635. TERN_(HAS_LCD_MENU, ui.capture());
  636. save_ubl_active_state_and_disable(); // No bed level correction so only raw data is obtained
  637. uint8_t count = GRID_MAX_POINTS;
  638. mesh_index_pair best;
  639. do {
  640. if (do_ubl_mesh_map) display_map(g29_map_type);
  641. const int point_num = (GRID_MAX_POINTS) - count + 1;
  642. SERIAL_ECHOLNPAIR("\nProbing mesh point ", point_num, "/", int(GRID_MAX_POINTS), ".\n");
  643. TERN_(HAS_DISPLAY, ui.status_printf_P(0, PSTR(S_FMT " %i/%i"), GET_TEXT(MSG_PROBING_MESH), point_num, int(GRID_MAX_POINTS)));
  644. #if HAS_LCD_MENU
  645. if (ui.button_pressed()) {
  646. ui.quick_feedback(false); // Preserve button state for click-and-hold
  647. SERIAL_ECHOLNPGM("\nMesh only partially populated.\n");
  648. ui.wait_for_release();
  649. ui.quick_feedback();
  650. ui.release();
  651. probe.stow(); // Release UI before stow to allow for PAUSE_BEFORE_DEPLOY_STOW
  652. return restore_ubl_active_state_and_leave();
  653. }
  654. #endif
  655. best = do_furthest
  656. ? find_furthest_invalid_mesh_point()
  657. : find_closest_mesh_point_of_type(INVALID, near, true);
  658. if (best.pos.x >= 0) { // mesh point found and is reachable by probe
  659. TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(best.pos, ExtUI::PROBE_START));
  660. const float measured_z = probe.probe_at_point(
  661. best.meshpos(),
  662. stow_probe ? PROBE_PT_STOW : PROBE_PT_RAISE, g29_verbose_level
  663. );
  664. z_values[best.pos.x][best.pos.y] = measured_z;
  665. #if ENABLED(EXTENSIBLE_UI)
  666. ExtUI::onMeshUpdate(best.pos, ExtUI::PROBE_FINISH);
  667. ExtUI::onMeshUpdate(best.pos, measured_z);
  668. #endif
  669. }
  670. SERIAL_FLUSH(); // Prevent host M105 buffer overrun.
  671. } while (best.pos.x >= 0 && --count);
  672. // Release UI during stow to allow for PAUSE_BEFORE_DEPLOY_STOW
  673. TERN_(HAS_LCD_MENU, ui.release());
  674. probe.stow();
  675. TERN_(HAS_LCD_MENU, ui.capture());
  676. #ifdef Z_AFTER_PROBING
  677. probe.move_z_after_probing();
  678. #endif
  679. restore_ubl_active_state_and_leave();
  680. do_blocking_move_to_xy(
  681. constrain(near.x - probe.offset_xy.x, MESH_MIN_X, MESH_MAX_X),
  682. constrain(near.y - probe.offset_xy.y, MESH_MIN_Y, MESH_MAX_Y)
  683. );
  684. }
  685. #endif // HAS_BED_PROBE
  686. #if HAS_LCD_MENU
  687. typedef void (*clickFunc_t)();
  688. bool click_and_hold(const clickFunc_t func=nullptr) {
  689. if (ui.button_pressed()) {
  690. ui.quick_feedback(false); // Preserve button state for click-and-hold
  691. const millis_t nxt = millis() + 1500UL;
  692. while (ui.button_pressed()) { // Loop while the encoder is pressed. Uses hardware flag!
  693. idle(); // idle, of course
  694. if (ELAPSED(millis(), nxt)) { // After 1.5 seconds
  695. ui.quick_feedback();
  696. if (func) (*func)();
  697. ui.wait_for_release();
  698. return true;
  699. }
  700. }
  701. }
  702. serial_delay(15);
  703. return false;
  704. }
  705. void unified_bed_leveling::move_z_with_encoder(const float &multiplier) {
  706. ui.wait_for_release();
  707. while (!ui.button_pressed()) {
  708. idle();
  709. gcode.reset_stepper_timeout(); // Keep steppers powered
  710. if (encoder_diff) {
  711. do_blocking_move_to_z(current_position.z + float(encoder_diff) * multiplier);
  712. encoder_diff = 0;
  713. }
  714. }
  715. }
  716. float unified_bed_leveling::measure_point_with_encoder() {
  717. KEEPALIVE_STATE(PAUSED_FOR_USER);
  718. move_z_with_encoder(0.01f);
  719. return current_position.z;
  720. }
  721. static void echo_and_take_a_measurement() { SERIAL_ECHOLNPGM(" and take a measurement."); }
  722. float unified_bed_leveling::measure_business_card_thickness(float in_height) {
  723. ui.capture();
  724. save_ubl_active_state_and_disable(); // Disable bed level correction for probing
  725. do_blocking_move_to(0.5f * (MESH_MAX_X - (MESH_MIN_X)), 0.5f * (MESH_MAX_Y - (MESH_MIN_Y)), in_height);
  726. //, _MIN(planner.settings.max_feedrate_mm_s[X_AXIS], planner.settings.max_feedrate_mm_s[Y_AXIS]) * 0.5f);
  727. planner.synchronize();
  728. SERIAL_ECHOPGM("Place shim under nozzle");
  729. LCD_MESSAGEPGM(MSG_UBL_BC_INSERT);
  730. ui.return_to_status();
  731. echo_and_take_a_measurement();
  732. const float z1 = measure_point_with_encoder();
  733. do_blocking_move_to_z(current_position.z + SIZE_OF_LITTLE_RAISE);
  734. planner.synchronize();
  735. SERIAL_ECHOPGM("Remove shim");
  736. LCD_MESSAGEPGM(MSG_UBL_BC_REMOVE);
  737. echo_and_take_a_measurement();
  738. const float z2 = measure_point_with_encoder();
  739. do_blocking_move_to_z(current_position.z + Z_CLEARANCE_BETWEEN_PROBES);
  740. const float thickness = ABS(z1 - z2);
  741. if (g29_verbose_level > 1) {
  742. SERIAL_ECHOPAIR_F("Business Card is ", thickness, 4);
  743. SERIAL_ECHOLNPGM("mm thick.");
  744. }
  745. restore_ubl_active_state_and_leave();
  746. return thickness;
  747. }
  748. 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) {
  749. ui.capture();
  750. save_ubl_active_state_and_disable(); // No bed level correction so only raw data is obtained
  751. do_blocking_move_to_xy_z(current_position, z_clearance);
  752. ui.return_to_status();
  753. mesh_index_pair location;
  754. const xy_int8_t &lpos = location.pos;
  755. do {
  756. location = find_closest_mesh_point_of_type(INVALID, pos);
  757. // It doesn't matter if the probe can't reach the NAN location. This is a manual probe.
  758. if (!location.valid()) continue;
  759. const xyz_pos_t ppos = {
  760. mesh_index_to_xpos(lpos.x),
  761. mesh_index_to_ypos(lpos.y),
  762. Z_CLEARANCE_BETWEEN_PROBES
  763. };
  764. if (!position_is_reachable(ppos)) break; // SHOULD NOT OCCUR (find_closest_mesh_point only returns reachable points)
  765. LCD_MESSAGEPGM(MSG_UBL_MOVING_TO_NEXT);
  766. do_blocking_move_to(ppos);
  767. do_blocking_move_to_z(z_clearance);
  768. KEEPALIVE_STATE(PAUSED_FOR_USER);
  769. ui.capture();
  770. if (do_ubl_mesh_map) display_map(g29_map_type); // show user where we're probing
  771. serialprintPGM(parser.seen('B') ? GET_TEXT(MSG_UBL_BC_INSERT) : GET_TEXT(MSG_UBL_BC_INSERT2));
  772. const float z_step = 0.01f; // existing behavior: 0.01mm per click, occasionally step
  773. //const float z_step = planner.steps_to_mm[Z_AXIS]; // approx one step each click
  774. move_z_with_encoder(z_step);
  775. if (click_and_hold()) {
  776. SERIAL_ECHOLNPGM("\nMesh only partially populated.");
  777. do_blocking_move_to_z(Z_CLEARANCE_DEPLOY_PROBE);
  778. return restore_ubl_active_state_and_leave();
  779. }
  780. z_values[lpos.x][lpos.y] = current_position.z - thick;
  781. TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(location, z_values[lpos.x][lpos.y]));
  782. if (g29_verbose_level > 2)
  783. SERIAL_ECHOLNPAIR_F("Mesh Point Measured at: ", z_values[lpos.x][lpos.y], 6);
  784. SERIAL_FLUSH(); // Prevent host M105 buffer overrun.
  785. } while (location.valid());
  786. if (do_ubl_mesh_map) display_map(g29_map_type); // show user where we're probing
  787. restore_ubl_active_state_and_leave();
  788. do_blocking_move_to_xy_z(pos, Z_CLEARANCE_DEPLOY_PROBE);
  789. }
  790. inline void set_message_with_feedback(PGM_P const msg_P) {
  791. ui.set_status_P(msg_P);
  792. ui.quick_feedback();
  793. }
  794. void abort_fine_tune() {
  795. ui.return_to_status();
  796. do_blocking_move_to_z(Z_CLEARANCE_BETWEEN_PROBES);
  797. set_message_with_feedback(GET_TEXT(MSG_EDITING_STOPPED));
  798. }
  799. void unified_bed_leveling::fine_tune_mesh(const xy_pos_t &pos, const bool do_ubl_mesh_map) {
  800. if (!parser.seen('R')) // fine_tune_mesh() is special. If no repetition count flag is specified
  801. g29_repetition_cnt = 1; // do exactly one mesh location. Otherwise use what the parser decided.
  802. #if ENABLED(UBL_MESH_EDIT_MOVES_Z)
  803. const float h_offset = parser.seenval('H') ? parser.value_linear_units() : 0;
  804. if (!WITHIN(h_offset, 0, 10)) {
  805. SERIAL_ECHOLNPGM("Offset out of bounds. (0 to 10mm)\n");
  806. return;
  807. }
  808. #endif
  809. mesh_index_pair location;
  810. if (!position_is_reachable(pos)) {
  811. SERIAL_ECHOLNPGM("(X,Y) outside printable radius.");
  812. return;
  813. }
  814. save_ubl_active_state_and_disable();
  815. LCD_MESSAGEPGM(MSG_UBL_FINE_TUNE_MESH);
  816. ui.capture(); // Take over control of the LCD encoder
  817. do_blocking_move_to_xy_z(pos, Z_CLEARANCE_BETWEEN_PROBES); // Move to the given XY with probe clearance
  818. TERN_(UBL_MESH_EDIT_MOVES_Z, do_blocking_move_to_z(h_offset)); // Move Z to the given 'H' offset
  819. MeshFlags done_flags{0};
  820. const xy_int8_t &lpos = location.pos;
  821. do {
  822. location = find_closest_mesh_point_of_type(SET_IN_BITMAP, pos, false, &done_flags);
  823. if (lpos.x < 0) break; // Stop when there are no more reachable points
  824. done_flags.mark(lpos); // Mark this location as 'adjusted' so a new
  825. // location is used on the next loop
  826. const xyz_pos_t raw = {
  827. mesh_index_to_xpos(lpos.x),
  828. mesh_index_to_ypos(lpos.y),
  829. Z_CLEARANCE_BETWEEN_PROBES
  830. };
  831. if (!position_is_reachable(raw)) break; // SHOULD NOT OCCUR (find_closest_mesh_point_of_type only returns reachable)
  832. do_blocking_move_to(raw); // Move the nozzle to the edit point with probe clearance
  833. TERN_(UBL_MESH_EDIT_MOVES_Z, do_blocking_move_to_z(h_offset)); // Move Z to the given 'H' offset before editing
  834. KEEPALIVE_STATE(PAUSED_FOR_USER);
  835. if (do_ubl_mesh_map) display_map(g29_map_type); // Display the current point
  836. ui.refresh();
  837. float new_z = z_values[lpos.x][lpos.y];
  838. if (isnan(new_z)) new_z = 0; // Invalid points begin at 0
  839. new_z = FLOOR(new_z * 1000) * 0.001f; // Chop off digits after the 1000ths place
  840. lcd_mesh_edit_setup(new_z);
  841. do {
  842. new_z = lcd_mesh_edit();
  843. TERN_(UBL_MESH_EDIT_MOVES_Z, do_blocking_move_to_z(h_offset + new_z)); // Move the nozzle as the point is edited
  844. idle();
  845. SERIAL_FLUSH(); // Prevent host M105 buffer overrun.
  846. } while (!ui.button_pressed());
  847. if (!lcd_map_control) ui.return_to_status(); // Just editing a single point? Return to status
  848. if (click_and_hold(abort_fine_tune)) break; // Button held down? Abort editing
  849. z_values[lpos.x][lpos.y] = new_z; // Save the updated Z value
  850. TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(location, new_z));
  851. serial_delay(20); // No switch noise
  852. ui.refresh();
  853. } while (lpos.x >= 0 && --g29_repetition_cnt > 0);
  854. if (do_ubl_mesh_map) display_map(g29_map_type);
  855. restore_ubl_active_state_and_leave();
  856. do_blocking_move_to_xy_z(pos, Z_CLEARANCE_BETWEEN_PROBES);
  857. LCD_MESSAGEPGM(MSG_UBL_DONE_EDITING_MESH);
  858. SERIAL_ECHOLNPGM("Done Editing Mesh");
  859. if (lcd_map_control)
  860. ui.goto_screen(_lcd_ubl_output_map_lcd);
  861. else
  862. ui.return_to_status();
  863. }
  864. #endif // HAS_LCD_MENU
  865. bool unified_bed_leveling::g29_parameter_parsing() {
  866. bool err_flag = false;
  867. TERN_(HAS_LCD_MENU, set_message_with_feedback(GET_TEXT(MSG_UBL_DOING_G29)));
  868. g29_constant = 0;
  869. g29_repetition_cnt = 0;
  870. if (parser.seen('R')) {
  871. g29_repetition_cnt = parser.has_value() ? parser.value_int() : GRID_MAX_POINTS;
  872. NOMORE(g29_repetition_cnt, GRID_MAX_POINTS);
  873. if (g29_repetition_cnt < 1) {
  874. SERIAL_ECHOLNPGM("?(R)epetition count invalid (1+).\n");
  875. return UBL_ERR;
  876. }
  877. }
  878. g29_verbose_level = parser.seen('V') ? parser.value_int() : 0;
  879. if (!WITHIN(g29_verbose_level, 0, 4)) {
  880. SERIAL_ECHOLNPGM("?(V)erbose level implausible (0-4).\n");
  881. err_flag = true;
  882. }
  883. if (parser.seen('P')) {
  884. const int pv = parser.value_int();
  885. #if !HAS_BED_PROBE
  886. if (pv == 1) {
  887. SERIAL_ECHOLNPGM("G29 P1 requires a probe.\n");
  888. err_flag = true;
  889. }
  890. else
  891. #endif
  892. {
  893. g29_phase_value = pv;
  894. if (!WITHIN(g29_phase_value, 0, 6)) {
  895. SERIAL_ECHOLNPGM("?(P)hase value invalid (0-6).\n");
  896. err_flag = true;
  897. }
  898. }
  899. }
  900. if (parser.seen('J')) {
  901. #if HAS_BED_PROBE
  902. g29_grid_size = parser.has_value() ? parser.value_int() : 0;
  903. if (g29_grid_size && !WITHIN(g29_grid_size, 2, 9)) {
  904. SERIAL_ECHOLNPGM("?Invalid grid size (J) specified (2-9).\n");
  905. err_flag = true;
  906. }
  907. #else
  908. SERIAL_ECHOLNPGM("G29 J action requires a probe.\n");
  909. err_flag = true;
  910. #endif
  911. }
  912. xy_seen.x = parser.seenval('X');
  913. float sx = xy_seen.x ? parser.value_float() : current_position.x;
  914. xy_seen.y = parser.seenval('Y');
  915. float sy = xy_seen.y ? parser.value_float() : current_position.y;
  916. if (xy_seen.x != xy_seen.y) {
  917. SERIAL_ECHOLNPGM("Both X & Y locations must be specified.\n");
  918. err_flag = true;
  919. }
  920. // If X or Y are not valid, use center of the bed values
  921. if (!WITHIN(sx, X_MIN_BED, X_MAX_BED)) sx = X_CENTER;
  922. if (!WITHIN(sy, Y_MIN_BED, Y_MAX_BED)) sy = Y_CENTER;
  923. if (err_flag) return UBL_ERR;
  924. g29_pos.set(sx, sy);
  925. /**
  926. * Activate or deactivate UBL
  927. * Note: UBL's G29 restores the state set here when done.
  928. * Leveling is being enabled here with old data, possibly
  929. * none. Error handling should disable for safety...
  930. */
  931. if (parser.seen('A')) {
  932. if (parser.seen('D')) {
  933. SERIAL_ECHOLNPGM("?Can't activate and deactivate at the same time.\n");
  934. return UBL_ERR;
  935. }
  936. set_bed_leveling_enabled(true);
  937. report_state();
  938. }
  939. else if (parser.seen('D')) {
  940. set_bed_leveling_enabled(false);
  941. report_state();
  942. }
  943. // Set global 'C' flag and its value
  944. if ((g29_c_flag = parser.seen('C')))
  945. g29_constant = parser.value_float();
  946. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  947. if (parser.seenval('F')) {
  948. const float fh = parser.value_float();
  949. if (!WITHIN(fh, 0, 100)) {
  950. SERIAL_ECHOLNPGM("?(F)ade height for Bed Level Correction not plausible.\n");
  951. return UBL_ERR;
  952. }
  953. set_z_fade_height(fh);
  954. }
  955. #endif
  956. g29_map_type = parser.intval('T');
  957. if (!WITHIN(g29_map_type, 0, 2)) {
  958. SERIAL_ECHOLNPGM("Invalid map type.\n");
  959. return UBL_ERR;
  960. }
  961. return UBL_OK;
  962. }
  963. static uint8_t ubl_state_at_invocation = 0;
  964. #if ENABLED(UBL_DEVEL_DEBUGGING)
  965. static uint8_t ubl_state_recursion_chk = 0;
  966. #endif
  967. void unified_bed_leveling::save_ubl_active_state_and_disable() {
  968. #if ENABLED(UBL_DEVEL_DEBUGGING)
  969. ubl_state_recursion_chk++;
  970. if (ubl_state_recursion_chk != 1) {
  971. SERIAL_ECHOLNPGM("save_ubl_active_state_and_disabled() called multiple times in a row.");
  972. TERN_(HAS_LCD_MENU, set_message_with_feedback(GET_TEXT(MSG_UBL_SAVE_ERROR)));
  973. return;
  974. }
  975. #endif
  976. ubl_state_at_invocation = planner.leveling_active;
  977. set_bed_leveling_enabled(false);
  978. }
  979. void unified_bed_leveling::restore_ubl_active_state_and_leave() {
  980. TERN_(HAS_LCD_MENU, ui.release());
  981. #if ENABLED(UBL_DEVEL_DEBUGGING)
  982. if (--ubl_state_recursion_chk) {
  983. SERIAL_ECHOLNPGM("restore_ubl_active_state_and_leave() called too many times.");
  984. TERN_(HAS_LCD_MENU, set_message_with_feedback(GET_TEXT(MSG_UBL_RESTORE_ERROR)));
  985. return;
  986. }
  987. #endif
  988. set_bed_leveling_enabled(ubl_state_at_invocation);
  989. }
  990. mesh_index_pair unified_bed_leveling::find_furthest_invalid_mesh_point() {
  991. bool found_a_NAN = false, found_a_real = false;
  992. mesh_index_pair farthest { -1, -1, -99999.99 };
  993. GRID_LOOP(i, j) {
  994. if (!isnan(z_values[i][j])) continue; // Skip valid mesh points
  995. // Skip unreachable points
  996. if (!probe.can_reach(mesh_index_to_xpos(i), mesh_index_to_ypos(j)))
  997. continue;
  998. found_a_NAN = true;
  999. xy_int8_t near { -1, -1 };
  1000. float d1, d2 = 99999.9f;
  1001. GRID_LOOP(k, l) {
  1002. if (isnan(z_values[k][l])) continue;
  1003. found_a_real = true;
  1004. // Add in a random weighting factor that scrambles the probing of the
  1005. // last half of the mesh (when every unprobed mesh point is one index
  1006. // from a probed location).
  1007. d1 = HYPOT(i - k, j - l) + (1.0f / ((millis() % 47) + 13));
  1008. if (d1 < d2) { // Invalid mesh point (i,j) is closer to the defined point (k,l)
  1009. d2 = d1;
  1010. near.set(i, j);
  1011. }
  1012. }
  1013. //
  1014. // At this point d2 should have the near defined mesh point to invalid mesh point (i,j)
  1015. //
  1016. if (found_a_real && near.x >= 0 && d2 > farthest.distance) {
  1017. farthest.pos = near; // Found an invalid location farther from the defined mesh point
  1018. farthest.distance = d2;
  1019. }
  1020. } // GRID_LOOP
  1021. if (!found_a_real && found_a_NAN) { // if the mesh is totally unpopulated, start the probing
  1022. farthest.pos.set((GRID_MAX_POINTS_X) / 2, (GRID_MAX_POINTS_Y) / 2);
  1023. farthest.distance = 1;
  1024. }
  1025. return farthest;
  1026. }
  1027. 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*/) {
  1028. mesh_index_pair closest;
  1029. closest.invalidate();
  1030. closest.distance = -99999.9f;
  1031. // Get the reference position, either nozzle or probe
  1032. const xy_pos_t ref = probe_relative ? pos + probe.offset_xy : pos;
  1033. float best_so_far = 99999.99f;
  1034. GRID_LOOP(i, j) {
  1035. if ( (type == (isnan(z_values[i][j]) ? INVALID : REAL))
  1036. || (type == SET_IN_BITMAP && !done_flags->marked(i, j))
  1037. ) {
  1038. // Found a Mesh Point of the specified type!
  1039. const xy_pos_t mpos = { mesh_index_to_xpos(i), mesh_index_to_ypos(j) };
  1040. // If using the probe as the reference there are some unreachable locations.
  1041. // Also for round beds, there are grid points outside the bed the nozzle can't reach.
  1042. // Prune them from the list and ignore them till the next Phase (manual nozzle probing).
  1043. if (!(probe_relative ? probe.can_reach(mpos) : position_is_reachable(mpos)))
  1044. continue;
  1045. // Reachable. Check if it's the best_so_far location to the nozzle.
  1046. const xy_pos_t diff = current_position - mpos;
  1047. const float distance = (ref - mpos).magnitude() + diff.magnitude() * 0.1f;
  1048. // factor in the distance from the current location for the normal case
  1049. // so the nozzle isn't running all over the bed.
  1050. if (distance < best_so_far) {
  1051. best_so_far = distance; // Found a closer location with the desired value type.
  1052. closest.pos.set(i, j);
  1053. closest.distance = best_so_far;
  1054. }
  1055. }
  1056. } // GRID_LOOP
  1057. return closest;
  1058. }
  1059. /**
  1060. * 'Smart Fill': Scan from the outward edges of the mesh towards the center.
  1061. * If an invalid location is found, use the next two points (if valid) to
  1062. * calculate a 'reasonable' value for the unprobed mesh point.
  1063. */
  1064. bool unified_bed_leveling::smart_fill_one(const uint8_t x, const uint8_t y, const int8_t xdir, const int8_t ydir) {
  1065. const float v = z_values[x][y];
  1066. if (isnan(v)) { // A NAN...
  1067. const int8_t dx = x + xdir, dy = y + ydir;
  1068. const float v1 = z_values[dx][dy];
  1069. if (!isnan(v1)) { // ...next to a pair of real values?
  1070. const float v2 = z_values[dx + xdir][dy + ydir];
  1071. if (!isnan(v2)) {
  1072. z_values[x][y] = v1 < v2 ? v1 : v1 + v1 - v2;
  1073. TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, z_values[x][y]));
  1074. return true;
  1075. }
  1076. }
  1077. }
  1078. return false;
  1079. }
  1080. typedef struct { uint8_t sx, ex, sy, ey; bool yfirst; } smart_fill_info;
  1081. void unified_bed_leveling::smart_fill_mesh() {
  1082. static const smart_fill_info
  1083. info0 PROGMEM = { 0, GRID_MAX_POINTS_X, 0, GRID_MAX_POINTS_Y - 2, false }, // Bottom of the mesh looking up
  1084. info1 PROGMEM = { 0, GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y - 1, 0, false }, // Top of the mesh looking down
  1085. info2 PROGMEM = { 0, GRID_MAX_POINTS_X - 2, 0, GRID_MAX_POINTS_Y, true }, // Left side of the mesh looking right
  1086. info3 PROGMEM = { GRID_MAX_POINTS_X - 1, 0, 0, GRID_MAX_POINTS_Y, true }; // Right side of the mesh looking left
  1087. static const smart_fill_info * const info[] PROGMEM = { &info0, &info1, &info2, &info3 };
  1088. LOOP_L_N(i, COUNT(info)) {
  1089. const smart_fill_info *f = (smart_fill_info*)pgm_read_ptr(&info[i]);
  1090. const int8_t sx = pgm_read_byte(&f->sx), sy = pgm_read_byte(&f->sy),
  1091. ex = pgm_read_byte(&f->ex), ey = pgm_read_byte(&f->ey);
  1092. if (pgm_read_byte(&f->yfirst)) {
  1093. const int8_t dir = ex > sx ? 1 : -1;
  1094. for (uint8_t y = sy; y != ey; ++y)
  1095. for (uint8_t x = sx; x != ex; x += dir)
  1096. if (smart_fill_one(x, y, dir, 0)) break;
  1097. }
  1098. else {
  1099. const int8_t dir = ey > sy ? 1 : -1;
  1100. for (uint8_t x = sx; x != ex; ++x)
  1101. for (uint8_t y = sy; y != ey; y += dir)
  1102. if (smart_fill_one(x, y, 0, dir)) break;
  1103. }
  1104. }
  1105. }
  1106. #if HAS_BED_PROBE
  1107. //#define VALIDATE_MESH_TILT
  1108. #include "../../../libs/vector_3.h"
  1109. void unified_bed_leveling::tilt_mesh_based_on_probed_grid(const bool do_3_pt_leveling) {
  1110. const float x_min = probe.min_x(), x_max = probe.max_x(),
  1111. y_min = probe.min_y(), y_max = probe.max_y(),
  1112. dx = (x_max - x_min) / (g29_grid_size - 1),
  1113. dy = (y_max - y_min) / (g29_grid_size - 1);
  1114. xy_float_t points[3];
  1115. probe.get_three_points(points);
  1116. float measured_z;
  1117. bool abort_flag = false;
  1118. #ifdef VALIDATE_MESH_TILT
  1119. float z1, z2, z3; // Needed for algorithm validation below
  1120. #endif
  1121. struct linear_fit_data lsf_results;
  1122. incremental_LSF_reset(&lsf_results);
  1123. if (do_3_pt_leveling) {
  1124. SERIAL_ECHOLNPGM("Tilting mesh (1/3)");
  1125. TERN_(HAS_DISPLAY, ui.status_printf_P(0, PSTR(S_FMT " 1/3"), GET_TEXT(MSG_LCD_TILTING_MESH)));
  1126. measured_z = probe.probe_at_point(points[0], PROBE_PT_RAISE, g29_verbose_level);
  1127. if (isnan(measured_z))
  1128. abort_flag = true;
  1129. else {
  1130. measured_z -= get_z_correction(points[0]);
  1131. #ifdef VALIDATE_MESH_TILT
  1132. z1 = measured_z;
  1133. #endif
  1134. if (g29_verbose_level > 3) {
  1135. serial_spaces(16);
  1136. SERIAL_ECHOLNPAIR("Corrected_Z=", measured_z);
  1137. }
  1138. incremental_LSF(&lsf_results, points[0], measured_z);
  1139. }
  1140. if (!abort_flag) {
  1141. SERIAL_ECHOLNPGM("Tilting mesh (2/3)");
  1142. TERN_(HAS_DISPLAY, ui.status_printf_P(0, PSTR(S_FMT " 2/3"), GET_TEXT(MSG_LCD_TILTING_MESH)));
  1143. measured_z = probe.probe_at_point(points[1], PROBE_PT_RAISE, g29_verbose_level);
  1144. #ifdef VALIDATE_MESH_TILT
  1145. z2 = measured_z;
  1146. #endif
  1147. if (isnan(measured_z))
  1148. abort_flag = true;
  1149. else {
  1150. measured_z -= get_z_correction(points[1]);
  1151. if (g29_verbose_level > 3) {
  1152. serial_spaces(16);
  1153. SERIAL_ECHOLNPAIR("Corrected_Z=", measured_z);
  1154. }
  1155. incremental_LSF(&lsf_results, points[1], measured_z);
  1156. }
  1157. }
  1158. if (!abort_flag) {
  1159. SERIAL_ECHOLNPGM("Tilting mesh (3/3)");
  1160. TERN_(HAS_DISPLAY, ui.status_printf_P(0, PSTR(S_FMT " 3/3"), GET_TEXT(MSG_LCD_TILTING_MESH)));
  1161. measured_z = probe.probe_at_point(points[2], PROBE_PT_STOW, g29_verbose_level);
  1162. #ifdef VALIDATE_MESH_TILT
  1163. z3 = measured_z;
  1164. #endif
  1165. if (isnan(measured_z))
  1166. abort_flag = true;
  1167. else {
  1168. measured_z -= get_z_correction(points[2]);
  1169. if (g29_verbose_level > 3) {
  1170. serial_spaces(16);
  1171. SERIAL_ECHOLNPAIR("Corrected_Z=", measured_z);
  1172. }
  1173. incremental_LSF(&lsf_results, points[2], measured_z);
  1174. }
  1175. }
  1176. probe.stow();
  1177. #ifdef Z_AFTER_PROBING
  1178. probe.move_z_after_probing();
  1179. #endif
  1180. if (abort_flag) {
  1181. SERIAL_ECHOLNPGM("?Error probing point. Aborting operation.");
  1182. return;
  1183. }
  1184. }
  1185. else { // !do_3_pt_leveling
  1186. bool zig_zag = false;
  1187. const uint16_t total_points = sq(g29_grid_size);
  1188. uint16_t point_num = 1;
  1189. xy_pos_t rpos;
  1190. LOOP_L_N(ix, g29_grid_size) {
  1191. rpos.x = x_min + ix * dx;
  1192. LOOP_L_N(iy, g29_grid_size) {
  1193. rpos.y = y_min + dy * (zig_zag ? g29_grid_size - 1 - iy : iy);
  1194. if (!abort_flag) {
  1195. SERIAL_ECHOLNPAIR("Tilting mesh point ", point_num, "/", total_points, "\n");
  1196. TERN_(HAS_DISPLAY, ui.status_printf_P(0, PSTR(S_FMT " %i/%i"), GET_TEXT(MSG_LCD_TILTING_MESH), point_num, total_points));
  1197. measured_z = probe.probe_at_point(rpos, parser.seen('E') ? PROBE_PT_STOW : PROBE_PT_RAISE, g29_verbose_level); // TODO: Needs error handling
  1198. abort_flag = isnan(measured_z);
  1199. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1200. if (DEBUGGING(LEVELING)) {
  1201. const xy_pos_t lpos = rpos.asLogical();
  1202. DEBUG_CHAR('(');
  1203. DEBUG_ECHO_F(rpos.x, 7);
  1204. DEBUG_CHAR(',');
  1205. DEBUG_ECHO_F(rpos.y, 7);
  1206. DEBUG_ECHOPAIR_F(") logical: (", lpos.x, 7);
  1207. DEBUG_CHAR(',');
  1208. DEBUG_ECHO_F(lpos.y, 7);
  1209. DEBUG_ECHOPAIR_F(") measured: ", measured_z, 7);
  1210. DEBUG_ECHOPAIR_F(" correction: ", get_z_correction(rpos), 7);
  1211. }
  1212. #endif
  1213. measured_z -= get_z_correction(rpos) /* + probe.offset.z */ ;
  1214. if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPAIR_F(" final >>>---> ", measured_z, 7);
  1215. if (g29_verbose_level > 3) {
  1216. serial_spaces(16);
  1217. SERIAL_ECHOLNPAIR("Corrected_Z=", measured_z);
  1218. }
  1219. incremental_LSF(&lsf_results, rpos, measured_z);
  1220. }
  1221. point_num++;
  1222. }
  1223. zig_zag ^= true;
  1224. }
  1225. }
  1226. probe.stow();
  1227. #ifdef Z_AFTER_PROBING
  1228. probe.move_z_after_probing();
  1229. #endif
  1230. if (abort_flag || finish_incremental_LSF(&lsf_results)) {
  1231. SERIAL_ECHOPGM("Could not complete LSF!");
  1232. return;
  1233. }
  1234. vector_3 normal = vector_3(lsf_results.A, lsf_results.B, 1).get_normal();
  1235. if (g29_verbose_level > 2) {
  1236. SERIAL_ECHOPAIR_F("bed plane normal = [", normal.x, 7);
  1237. SERIAL_CHAR(',');
  1238. SERIAL_ECHO_F(normal.y, 7);
  1239. SERIAL_CHAR(',');
  1240. SERIAL_ECHO_F(normal.z, 7);
  1241. SERIAL_ECHOLNPGM("]");
  1242. }
  1243. matrix_3x3 rotation = matrix_3x3::create_look_at(vector_3(lsf_results.A, lsf_results.B, 1));
  1244. GRID_LOOP(i, j) {
  1245. float mx = mesh_index_to_xpos(i),
  1246. my = mesh_index_to_ypos(j),
  1247. mz = z_values[i][j];
  1248. if (DEBUGGING(LEVELING)) {
  1249. DEBUG_ECHOPAIR_F("before rotation = [", mx, 7);
  1250. DEBUG_CHAR(',');
  1251. DEBUG_ECHO_F(my, 7);
  1252. DEBUG_CHAR(',');
  1253. DEBUG_ECHO_F(mz, 7);
  1254. DEBUG_ECHOPGM("] ---> ");
  1255. DEBUG_DELAY(20);
  1256. }
  1257. apply_rotation_xyz(rotation, mx, my, mz);
  1258. if (DEBUGGING(LEVELING)) {
  1259. DEBUG_ECHOPAIR_F("after rotation = [", mx, 7);
  1260. DEBUG_CHAR(',');
  1261. DEBUG_ECHO_F(my, 7);
  1262. DEBUG_CHAR(',');
  1263. DEBUG_ECHO_F(mz, 7);
  1264. DEBUG_ECHOLNPGM("]");
  1265. DEBUG_DELAY(20);
  1266. }
  1267. z_values[i][j] = mz - lsf_results.D;
  1268. TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(i, j, z_values[i][j]));
  1269. }
  1270. if (DEBUGGING(LEVELING)) {
  1271. rotation.debug(PSTR("rotation matrix:\n"));
  1272. DEBUG_ECHOPAIR_F("LSF Results A=", lsf_results.A, 7);
  1273. DEBUG_ECHOPAIR_F(" B=", lsf_results.B, 7);
  1274. DEBUG_ECHOLNPAIR_F(" D=", lsf_results.D, 7);
  1275. DEBUG_DELAY(55);
  1276. DEBUG_ECHOPAIR_F("bed plane normal = [", normal.x, 7);
  1277. DEBUG_CHAR(',');
  1278. DEBUG_ECHO_F(normal.y, 7);
  1279. DEBUG_CHAR(',');
  1280. DEBUG_ECHO_F(normal.z, 7);
  1281. DEBUG_ECHOLNPGM("]");
  1282. DEBUG_EOL();
  1283. /**
  1284. * Use the code below to check the validity of the mesh tilting algorithm.
  1285. * 3-Point Mesh Tilt uses the same algorithm as grid-based tilting, but only
  1286. * three points are used in the calculation. This guarantees that each probed point
  1287. * has an exact match when get_z_correction() for that location is calculated.
  1288. * The Z error between the probed point locations and the get_z_correction()
  1289. * numbers for those locations should be 0.
  1290. */
  1291. #ifdef VALIDATE_MESH_TILT
  1292. auto d_from = []{ DEBUG_ECHOPGM("D from "); };
  1293. auto normed = [&](const xy_pos_t &pos, const float &zadd) {
  1294. return normal.x * pos.x + normal.y * pos.y + zadd;
  1295. };
  1296. auto debug_pt = [](PGM_P const pre, const xy_pos_t &pos, const float &zadd) {
  1297. d_from(); serialprintPGM(pre);
  1298. DEBUG_ECHO_F(normed(pos, zadd), 6);
  1299. DEBUG_ECHOLNPAIR_F(" Z error = ", zadd - get_z_correction(pos), 6);
  1300. };
  1301. debug_pt(PSTR("1st point: "), probe_pt[0], normal.z * z1);
  1302. debug_pt(PSTR("2nd point: "), probe_pt[1], normal.z * z2);
  1303. debug_pt(PSTR("3rd point: "), probe_pt[2], normal.z * z3);
  1304. d_from(); DEBUG_ECHOPGM("safe home with Z=");
  1305. DEBUG_ECHOLNPAIR_F("0 : ", normed(safe_homing_xy, 0), 6);
  1306. d_from(); DEBUG_ECHOPGM("safe home with Z=");
  1307. DEBUG_ECHOLNPAIR_F("mesh value ", normed(safe_homing_xy, get_z_correction(safe_homing_xy)), 6);
  1308. DEBUG_ECHOPAIR(" Z error = (", Z_SAFE_HOMING_X_POINT, ",", Z_SAFE_HOMING_Y_POINT);
  1309. DEBUG_ECHOLNPAIR_F(") = ", get_z_correction(safe_homing_xy), 6);
  1310. #endif
  1311. } // DEBUGGING(LEVELING)
  1312. }
  1313. #endif // HAS_BED_PROBE
  1314. #if ENABLED(UBL_G29_P31)
  1315. void unified_bed_leveling::smart_fill_wlsf(const float &weight_factor) {
  1316. // For each undefined mesh point, compute a distance-weighted least squares fit
  1317. // from all the originally populated mesh points, weighted toward the point
  1318. // being extrapolated so that nearby points will have greater influence on
  1319. // the point being extrapolated. Then extrapolate the mesh point from WLSF.
  1320. static_assert((GRID_MAX_POINTS_Y) <= 16, "GRID_MAX_POINTS_Y too big");
  1321. uint16_t bitmap[GRID_MAX_POINTS_X] = { 0 };
  1322. struct linear_fit_data lsf_results;
  1323. SERIAL_ECHOPGM("Extrapolating mesh...");
  1324. const float weight_scaled = weight_factor * _MAX(MESH_X_DIST, MESH_Y_DIST);
  1325. GRID_LOOP(jx, jy) if (!isnan(z_values[jx][jy])) SBI(bitmap[jx], jy);
  1326. xy_pos_t ppos;
  1327. LOOP_L_N(ix, GRID_MAX_POINTS_X) {
  1328. ppos.x = mesh_index_to_xpos(ix);
  1329. LOOP_L_N(iy, GRID_MAX_POINTS_Y) {
  1330. ppos.y = mesh_index_to_ypos(iy);
  1331. if (isnan(z_values[ix][iy])) {
  1332. // undefined mesh point at (ppos.x,ppos.y), compute weighted LSF from original valid mesh points.
  1333. incremental_LSF_reset(&lsf_results);
  1334. xy_pos_t rpos;
  1335. LOOP_L_N(jx, GRID_MAX_POINTS_X) {
  1336. rpos.x = mesh_index_to_xpos(jx);
  1337. LOOP_L_N(jy, GRID_MAX_POINTS_Y) {
  1338. if (TEST(bitmap[jx], jy)) {
  1339. rpos.y = mesh_index_to_ypos(jy);
  1340. const float rz = z_values[jx][jy],
  1341. w = 1.0f + weight_scaled / (rpos - ppos).magnitude();
  1342. incremental_WLSF(&lsf_results, rpos, rz, w);
  1343. }
  1344. }
  1345. }
  1346. if (finish_incremental_LSF(&lsf_results)) {
  1347. SERIAL_ECHOLNPGM("Insufficient data");
  1348. return;
  1349. }
  1350. const float ez = -lsf_results.D - lsf_results.A * ppos.x - lsf_results.B * ppos.y;
  1351. z_values[ix][iy] = ez;
  1352. TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(ix, iy, z_values[ix][iy]));
  1353. idle(); // housekeeping
  1354. }
  1355. }
  1356. }
  1357. SERIAL_ECHOLNPGM("done");
  1358. }
  1359. #endif // UBL_G29_P31
  1360. #if ENABLED(UBL_DEVEL_DEBUGGING)
  1361. /**
  1362. * Much of the 'What?' command can be eliminated. But until we are fully debugged, it is
  1363. * good to have the extra information. Soon... we prune this to just a few items
  1364. */
  1365. void unified_bed_leveling::g29_what_command() {
  1366. report_state();
  1367. if (storage_slot == -1)
  1368. SERIAL_ECHOPGM("No Mesh Loaded.");
  1369. else
  1370. SERIAL_ECHOPAIR("Mesh ", storage_slot, " Loaded.");
  1371. SERIAL_EOL();
  1372. serial_delay(50);
  1373. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1374. SERIAL_ECHOLNPAIR_F("Fade Height M420 Z", planner.z_fade_height, 4);
  1375. #endif
  1376. adjust_mesh_to_mean(g29_c_flag, g29_constant);
  1377. #if HAS_BED_PROBE
  1378. SERIAL_ECHOLNPAIR_F("Probe Offset M851 Z", probe.offset.z, 7);
  1379. #endif
  1380. SERIAL_ECHOLNPAIR("MESH_MIN_X " STRINGIFY(MESH_MIN_X) "=", MESH_MIN_X); serial_delay(50);
  1381. SERIAL_ECHOLNPAIR("MESH_MIN_Y " STRINGIFY(MESH_MIN_Y) "=", MESH_MIN_Y); serial_delay(50);
  1382. SERIAL_ECHOLNPAIR("MESH_MAX_X " STRINGIFY(MESH_MAX_X) "=", MESH_MAX_X); serial_delay(50);
  1383. SERIAL_ECHOLNPAIR("MESH_MAX_Y " STRINGIFY(MESH_MAX_Y) "=", MESH_MAX_Y); serial_delay(50);
  1384. SERIAL_ECHOLNPAIR("GRID_MAX_POINTS_X ", GRID_MAX_POINTS_X); serial_delay(50);
  1385. SERIAL_ECHOLNPAIR("GRID_MAX_POINTS_Y ", GRID_MAX_POINTS_Y); serial_delay(50);
  1386. SERIAL_ECHOLNPAIR("MESH_X_DIST ", MESH_X_DIST);
  1387. SERIAL_ECHOLNPAIR("MESH_Y_DIST ", MESH_Y_DIST); serial_delay(50);
  1388. SERIAL_ECHOPGM("X-Axis Mesh Points at: ");
  1389. LOOP_L_N(i, GRID_MAX_POINTS_X) {
  1390. SERIAL_ECHO_F(LOGICAL_X_POSITION(mesh_index_to_xpos(i)), 3);
  1391. SERIAL_ECHOPGM(" ");
  1392. serial_delay(25);
  1393. }
  1394. SERIAL_EOL();
  1395. SERIAL_ECHOPGM("Y-Axis Mesh Points at: ");
  1396. LOOP_L_N(i, GRID_MAX_POINTS_Y) {
  1397. SERIAL_ECHO_F(LOGICAL_Y_POSITION(mesh_index_to_ypos(i)), 3);
  1398. SERIAL_ECHOPGM(" ");
  1399. serial_delay(25);
  1400. }
  1401. SERIAL_EOL();
  1402. #if HAS_KILL
  1403. SERIAL_ECHOLNPAIR("Kill pin on :", int(KILL_PIN), " state:", int(kill_state()));
  1404. #endif
  1405. SERIAL_EOL();
  1406. serial_delay(50);
  1407. #if ENABLED(UBL_DEVEL_DEBUGGING)
  1408. SERIAL_ECHOLNPAIR("ubl_state_at_invocation :", ubl_state_at_invocation, "\nubl_state_recursion_chk :", ubl_state_recursion_chk);
  1409. serial_delay(50);
  1410. SERIAL_ECHOLNPAIR("Meshes go from ", hex_address((void*)settings.meshes_start_index()), " to ", hex_address((void*)settings.meshes_end_index()));
  1411. serial_delay(50);
  1412. SERIAL_ECHOLNPAIR("sizeof(ubl) : ", (int)sizeof(ubl)); SERIAL_EOL();
  1413. SERIAL_ECHOLNPAIR("z_value[][] size: ", (int)sizeof(z_values)); SERIAL_EOL();
  1414. serial_delay(25);
  1415. SERIAL_ECHOLNPAIR("EEPROM free for UBL: ", hex_address((void*)(settings.meshes_end_index() - settings.meshes_start_index())));
  1416. serial_delay(50);
  1417. SERIAL_ECHOLNPAIR("EEPROM can hold ", settings.calc_num_meshes(), " meshes.\n");
  1418. serial_delay(25);
  1419. #endif // UBL_DEVEL_DEBUGGING
  1420. if (!sanity_check()) {
  1421. echo_name();
  1422. SERIAL_ECHOLNPGM(" sanity checks passed.");
  1423. }
  1424. }
  1425. /**
  1426. * When we are fully debugged, the EEPROM dump command will get deleted also. But
  1427. * right now, it is good to have the extra information. Soon... we prune this.
  1428. */
  1429. void unified_bed_leveling::g29_eeprom_dump() {
  1430. uint8_t cccc;
  1431. SERIAL_ECHO_MSG("EEPROM Dump:");
  1432. persistentStore.access_start();
  1433. for (uint16_t i = 0; i < persistentStore.capacity(); i += 16) {
  1434. if (!(i & 0x3)) idle();
  1435. print_hex_word(i);
  1436. SERIAL_ECHOPGM(": ");
  1437. for (uint16_t j = 0; j < 16; j++) {
  1438. persistentStore.read_data(i + j, &cccc, sizeof(uint8_t));
  1439. print_hex_byte(cccc);
  1440. SERIAL_CHAR(' ');
  1441. }
  1442. SERIAL_EOL();
  1443. }
  1444. SERIAL_EOL();
  1445. persistentStore.access_finish();
  1446. }
  1447. /**
  1448. * When we are fully debugged, this may go away. But there are some valid
  1449. * use cases for the users. So we can wait and see what to do with it.
  1450. */
  1451. void unified_bed_leveling::g29_compare_current_mesh_to_stored_mesh() {
  1452. const int16_t a = settings.calc_num_meshes();
  1453. if (!a) {
  1454. SERIAL_ECHOLNPGM("?EEPROM storage not available.");
  1455. return;
  1456. }
  1457. if (!parser.has_value() || !WITHIN(g29_storage_slot, 0, a - 1)) {
  1458. SERIAL_ECHOLNPAIR("?Invalid storage slot.\n?Use 0 to ", a - 1);
  1459. return;
  1460. }
  1461. g29_storage_slot = parser.value_int();
  1462. float tmp_z_values[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y];
  1463. settings.load_mesh(g29_storage_slot, &tmp_z_values);
  1464. SERIAL_ECHOLNPAIR("Subtracting mesh in slot ", g29_storage_slot, " from current mesh.");
  1465. GRID_LOOP(x, y) {
  1466. z_values[x][y] -= tmp_z_values[x][y];
  1467. TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, z_values[x][y]));
  1468. }
  1469. }
  1470. #endif // UBL_DEVEL_DEBUGGING
  1471. #endif // AUTO_BED_LEVELING_UBL