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 67KB

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