Subversion Repositories Tronxy-X3A-Marlin

Rev

Details | Last modification | View Log | RSS feed

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