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

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