planner.h 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  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. * planner.h
  24. *
  25. * Buffer movement commands and manage the acceleration profile plan
  26. *
  27. * Derived from Grbl
  28. * Copyright (c) 2009-2011 Simen Svale Skogsrud
  29. */
  30. #ifndef PLANNER_H
  31. #define PLANNER_H
  32. #include "types.h"
  33. #include "enum.h"
  34. #include "Marlin.h"
  35. #if ABL_PLANAR
  36. #include "vector_3.h"
  37. #endif
  38. enum BlockFlagBit : char {
  39. // Recalculate trapezoids on entry junction. For optimization.
  40. BLOCK_BIT_RECALCULATE,
  41. // Nominal speed always reached.
  42. // i.e., The segment is long enough, so the nominal speed is reachable if accelerating
  43. // from a safe speed (in consideration of jerking from zero speed).
  44. BLOCK_BIT_NOMINAL_LENGTH,
  45. // The block is segment 2+ of a longer move
  46. BLOCK_BIT_CONTINUED,
  47. // Sync the stepper counts from the block
  48. BLOCK_BIT_SYNC_POSITION
  49. };
  50. enum BlockFlag : char {
  51. BLOCK_FLAG_RECALCULATE = _BV(BLOCK_BIT_RECALCULATE),
  52. BLOCK_FLAG_NOMINAL_LENGTH = _BV(BLOCK_BIT_NOMINAL_LENGTH),
  53. BLOCK_FLAG_CONTINUED = _BV(BLOCK_BIT_CONTINUED),
  54. BLOCK_FLAG_SYNC_POSITION = _BV(BLOCK_BIT_SYNC_POSITION)
  55. };
  56. /**
  57. * struct block_t
  58. *
  59. * A single entry in the planner buffer.
  60. * Tracks linear movement over multiple axes.
  61. *
  62. * The "nominal" values are as-specified by gcode, and
  63. * may never actually be reached due to acceleration limits.
  64. */
  65. typedef struct {
  66. volatile uint8_t flag; // Block flags (See BlockFlag enum above) - Modified by ISR and main thread!
  67. #if ENABLED(UNREGISTERED_MOVE_SUPPORT)
  68. bool count_it;
  69. #endif
  70. // Fields used by the motion planner to manage acceleration
  71. float nominal_speed_sqr, // The nominal speed for this block in (mm/sec)^2
  72. entry_speed_sqr, // Entry speed at previous-current junction in (mm/sec)^2
  73. max_entry_speed_sqr, // Maximum allowable junction entry speed in (mm/sec)^2
  74. millimeters, // The total travel of this block in mm
  75. acceleration; // acceleration mm/sec^2
  76. union {
  77. // Data used by all move blocks
  78. struct {
  79. // Fields used by the Bresenham algorithm for tracing the line
  80. uint32_t steps[NUM_AXIS]; // Step count along each axis
  81. };
  82. // Data used by all sync blocks
  83. struct {
  84. int32_t position[NUM_AXIS]; // New position to force when this sync block is executed
  85. };
  86. };
  87. uint32_t step_event_count; // The number of step events required to complete this block
  88. uint8_t active_extruder; // The extruder to move (if E move)
  89. #if ENABLED(MIXING_EXTRUDER)
  90. uint32_t mix_steps[MIXING_STEPPERS]; // Scaled steps[E_AXIS] for the mixing steppers
  91. #endif
  92. // Settings for the trapezoid generator
  93. uint32_t accelerate_until, // The index of the step event on which to stop acceleration
  94. decelerate_after; // The index of the step event on which to start decelerating
  95. #if ENABLED(S_CURVE_ACCELERATION)
  96. uint32_t cruise_rate, // The actual cruise rate to use, between end of the acceleration phase and start of deceleration phase
  97. acceleration_time, // Acceleration time and deceleration time in STEP timer counts
  98. deceleration_time,
  99. acceleration_time_inverse, // Inverse of acceleration and deceleration periods, expressed as integer. Scale depends on CPU being used
  100. deceleration_time_inverse;
  101. #else
  102. uint32_t acceleration_rate; // The acceleration rate used for acceleration calculation
  103. #endif
  104. uint8_t direction_bits; // The direction bit set for this block (refers to *_DIRECTION_BIT in config.h)
  105. // Advance extrusion
  106. #if ENABLED(LIN_ADVANCE)
  107. bool use_advance_lead;
  108. uint16_t advance_speed, // STEP timer value for extruder speed offset ISR
  109. max_adv_steps, // max. advance steps to get cruising speed pressure (not always nominal_speed!)
  110. final_adv_steps; // advance steps due to exit speed
  111. float e_D_ratio;
  112. #endif
  113. uint32_t nominal_rate, // The nominal step rate for this block in step_events/sec
  114. initial_rate, // The jerk-adjusted step rate at start of block
  115. final_rate, // The minimal rate at exit
  116. acceleration_steps_per_s2; // acceleration steps/sec^2
  117. #if FAN_COUNT > 0
  118. uint16_t fan_speed[FAN_COUNT];
  119. #endif
  120. #if ENABLED(BARICUDA)
  121. uint8_t valve_pressure, e_to_p_pressure;
  122. #endif
  123. uint32_t segment_time_us;
  124. } block_t;
  125. #define HAS_POSITION_FLOAT (ENABLED(LIN_ADVANCE) || HAS_FEEDRATE_SCALING)
  126. #define BLOCK_MOD(n) ((n)&(BLOCK_BUFFER_SIZE-1))
  127. class Planner {
  128. public:
  129. /**
  130. * The move buffer, calculated in stepper steps
  131. *
  132. * block_buffer is a ring buffer...
  133. *
  134. * head,tail : indexes for write,read
  135. * head==tail : the buffer is empty
  136. * head!=tail : blocks are in the buffer
  137. * head==(tail-1)%size : the buffer is full
  138. *
  139. * Writer of head is Planner::buffer_segment().
  140. * Reader of tail is Stepper::isr(). Always consider tail busy / read-only
  141. */
  142. static block_t block_buffer[BLOCK_BUFFER_SIZE];
  143. static volatile uint8_t block_buffer_head, // Index of the next block to be pushed
  144. block_buffer_nonbusy, // Index of the first non busy block
  145. block_buffer_planned, // Index of the optimally planned block
  146. block_buffer_tail; // Index of the busy block, if any
  147. static uint16_t cleaning_buffer_counter; // A counter to disable queuing of blocks
  148. static uint8_t delay_before_delivering; // This counter delays delivery of blocks when queue becomes empty to allow the opportunity of merging blocks
  149. #if ENABLED(DISTINCT_E_FACTORS)
  150. static uint8_t last_extruder; // Respond to extruder change
  151. #endif
  152. static int16_t flow_percentage[EXTRUDERS]; // Extrusion factor for each extruder
  153. static float e_factor[EXTRUDERS]; // The flow percentage and volumetric multiplier combine to scale E movement
  154. #if DISABLED(NO_VOLUMETRICS)
  155. static float filament_size[EXTRUDERS], // diameter of filament (in millimeters), typically around 1.75 or 2.85, 0 disables the volumetric calculations for the extruder
  156. volumetric_area_nominal, // Nominal cross-sectional area
  157. volumetric_multiplier[EXTRUDERS]; // Reciprocal of cross-sectional area of filament (in mm^2). Pre-calculated to reduce computation in the planner
  158. // May be auto-adjusted by a filament width sensor
  159. #endif
  160. static uint32_t max_acceleration_mm_per_s2[NUM_AXIS_N], // (mm/s^2) M201 XYZE
  161. max_acceleration_steps_per_s2[NUM_AXIS_N], // (steps/s^2) Derived from mm_per_s2
  162. min_segment_time_us; // (µs) M205 Q
  163. static float max_feedrate_mm_s[NUM_AXIS_N], // (mm/s) M203 XYZE - Max speeds
  164. axis_steps_per_mm[NUM_AXIS_N], // (steps) M92 XYZE - Steps per millimeter
  165. steps_to_mm[NUM_AXIS_N], // (mm) Millimeters per step
  166. min_feedrate_mm_s, // (mm/s) M205 S - Minimum linear feedrate
  167. acceleration, // (mm/s^2) M204 S - Normal acceleration. DEFAULT ACCELERATION for all printing moves.
  168. retract_acceleration, // (mm/s^2) M204 R - Retract acceleration. Filament pull-back and push-forward while standing still in the other axes
  169. travel_acceleration, // (mm/s^2) M204 T - Travel acceleration. DEFAULT ACCELERATION for all NON printing moves.
  170. min_travel_feedrate_mm_s; // (mm/s) M205 T - Minimum travel feedrate
  171. #if ENABLED(JUNCTION_DEVIATION)
  172. static float junction_deviation_mm; // (mm) M205 J
  173. #if ENABLED(LIN_ADVANCE)
  174. #if ENABLED(DISTINCT_E_FACTORS)
  175. static float max_e_jerk[EXTRUDERS]; // Calculated from junction_deviation_mm
  176. #else
  177. static float max_e_jerk;
  178. #endif
  179. #endif
  180. #else
  181. static float max_jerk[NUM_AXIS]; // (mm/s^2) M205 XYZE - The largest speed change requiring no acceleration.
  182. #endif
  183. #if ENABLED(LINE_BUILDUP_COMPENSATION_FEATURE)
  184. /*
  185. * Parameters for calculating target[]
  186. * See buildup compensation theory:
  187. * https://vitana.se/opr3d/tbear/2017.html#hangprinter_project_29
  188. */
  189. static float k0[MOV_AXIS],
  190. k1[MOV_AXIS],
  191. k2[MOV_AXIS],
  192. sqrtk1[MOV_AXIS];
  193. #endif
  194. #if HAS_LEVELING
  195. static bool leveling_active; // Flag that bed leveling is enabled
  196. #if ABL_PLANAR
  197. static matrix_3x3 bed_level_matrix; // Transform to compensate for bed level
  198. #endif
  199. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  200. static float z_fade_height, inverse_z_fade_height;
  201. #endif
  202. #else
  203. static constexpr bool leveling_active = false;
  204. #endif
  205. #if ENABLED(LIN_ADVANCE)
  206. static float extruder_advance_K;
  207. #endif
  208. #if HAS_POSITION_FLOAT
  209. static float position_float[NUM_AXIS];
  210. #endif
  211. #if ENABLED(SKEW_CORRECTION)
  212. #if ENABLED(SKEW_CORRECTION_GCODE)
  213. static float xy_skew_factor;
  214. #else
  215. static constexpr float xy_skew_factor = XY_SKEW_FACTOR;
  216. #endif
  217. #if ENABLED(SKEW_CORRECTION_FOR_Z)
  218. #if ENABLED(SKEW_CORRECTION_GCODE)
  219. static float xz_skew_factor, yz_skew_factor;
  220. #else
  221. static constexpr float xz_skew_factor = XZ_SKEW_FACTOR, yz_skew_factor = YZ_SKEW_FACTOR;
  222. #endif
  223. #else
  224. static constexpr float xz_skew_factor = 0, yz_skew_factor = 0;
  225. #endif
  226. #endif
  227. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  228. static bool abort_on_endstop_hit;
  229. #endif
  230. private:
  231. /**
  232. * The current position of the tool in absolute steps
  233. * Recalculated if any axis_steps_per_mm are changed by gcode
  234. */
  235. static int32_t position[NUM_AXIS];
  236. /**
  237. * Speed of previous path line segment
  238. */
  239. static float previous_speed[NUM_AXIS];
  240. /**
  241. * Nominal speed of previous path line segment (mm/s)^2
  242. */
  243. static float previous_nominal_speed_sqr;
  244. /**
  245. * Limit where 64bit math is necessary for acceleration calculation
  246. */
  247. static uint32_t cutoff_long;
  248. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  249. static float last_fade_z;
  250. #endif
  251. #if ENABLED(DISABLE_INACTIVE_EXTRUDER)
  252. /**
  253. * Counters to manage disabling inactive extruders
  254. */
  255. static uint8_t g_uc_extruder_last_move[EXTRUDERS];
  256. #endif // DISABLE_INACTIVE_EXTRUDER
  257. #ifdef XY_FREQUENCY_LIMIT
  258. // Used for the frequency limit
  259. #define MAX_FREQ_TIME_US (uint32_t)(1000000.0 / XY_FREQUENCY_LIMIT)
  260. // Old direction bits. Used for speed calculations
  261. static unsigned char old_direction_bits;
  262. // Segment times (in µs). Used for speed calculations
  263. static uint32_t axis_segment_time_us[2][3];
  264. #endif
  265. #if ENABLED(ULTRA_LCD)
  266. volatile static uint32_t block_buffer_runtime_us; //Theoretical block buffer runtime in µs
  267. #endif
  268. public:
  269. /**
  270. * Instance Methods
  271. */
  272. Planner();
  273. void init();
  274. /**
  275. * Static (class) Methods
  276. */
  277. static void reset_acceleration_rates();
  278. static void refresh_positioning();
  279. FORCE_INLINE static void refresh_e_factor(const uint8_t e) {
  280. e_factor[e] = (flow_percentage[e] * 0.01f
  281. #if DISABLED(NO_VOLUMETRICS)
  282. * volumetric_multiplier[e]
  283. #endif
  284. );
  285. }
  286. // Manage fans, paste pressure, etc.
  287. static void check_axes_activity();
  288. // Update multipliers based on new diameter measurements
  289. static void calculate_volumetric_multipliers();
  290. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  291. void calculate_volumetric_for_width_sensor(const int8_t encoded_ratio);
  292. #endif
  293. #if DISABLED(NO_VOLUMETRICS)
  294. FORCE_INLINE static void set_filament_size(const uint8_t e, const float &v) {
  295. filament_size[e] = v;
  296. // make sure all extruders have some sane value for the filament size
  297. for (uint8_t i = 0; i < COUNT(filament_size); i++)
  298. if (!filament_size[i]) filament_size[i] = DEFAULT_NOMINAL_FILAMENT_DIA;
  299. }
  300. #endif
  301. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  302. /**
  303. * Get the Z leveling fade factor based on the given Z height,
  304. * re-calculating only when needed.
  305. *
  306. * Returns 1.0 if planner.z_fade_height is 0.0.
  307. * Returns 0.0 if Z is past the specified 'Fade Height'.
  308. */
  309. inline static float fade_scaling_factor_for_z(const float &rz) {
  310. static float z_fade_factor = 1;
  311. if (z_fade_height) {
  312. if (rz >= z_fade_height) return 0;
  313. if (last_fade_z != rz) {
  314. last_fade_z = rz;
  315. z_fade_factor = 1 - rz * inverse_z_fade_height;
  316. }
  317. return z_fade_factor;
  318. }
  319. return 1;
  320. }
  321. FORCE_INLINE static void force_fade_recalc() { last_fade_z = -999.999f; }
  322. FORCE_INLINE static void set_z_fade_height(const float &zfh) {
  323. z_fade_height = zfh > 0 ? zfh : 0;
  324. inverse_z_fade_height = RECIPROCAL(z_fade_height);
  325. force_fade_recalc();
  326. }
  327. FORCE_INLINE static bool leveling_active_at_z(const float &rz) {
  328. return !z_fade_height || rz < z_fade_height;
  329. }
  330. #else
  331. FORCE_INLINE static float fade_scaling_factor_for_z(const float &rz) {
  332. UNUSED(rz);
  333. return 1;
  334. }
  335. FORCE_INLINE static bool leveling_active_at_z(const float &rz) { UNUSED(rz); return true; }
  336. #endif
  337. #if ENABLED(SKEW_CORRECTION)
  338. FORCE_INLINE static void skew(float &cx, float &cy, const float &cz) {
  339. if (WITHIN(cx, X_MIN_POS + 1, X_MAX_POS) && WITHIN(cy, Y_MIN_POS + 1, Y_MAX_POS)) {
  340. const float sx = cx - cy * xy_skew_factor - cz * (xz_skew_factor - (xy_skew_factor * yz_skew_factor)),
  341. sy = cy - cz * yz_skew_factor;
  342. if (WITHIN(sx, X_MIN_POS, X_MAX_POS) && WITHIN(sy, Y_MIN_POS, Y_MAX_POS)) {
  343. cx = sx; cy = sy;
  344. }
  345. }
  346. }
  347. FORCE_INLINE static void unskew(float &cx, float &cy, const float &cz) {
  348. if (WITHIN(cx, X_MIN_POS, X_MAX_POS) && WITHIN(cy, Y_MIN_POS, Y_MAX_POS)) {
  349. const float sx = cx + cy * xy_skew_factor + cz * xz_skew_factor,
  350. sy = cy + cz * yz_skew_factor;
  351. if (WITHIN(sx, X_MIN_POS, X_MAX_POS) && WITHIN(sy, Y_MIN_POS, Y_MAX_POS)) {
  352. cx = sx; cy = sy;
  353. }
  354. }
  355. }
  356. #endif // SKEW_CORRECTION
  357. #if PLANNER_LEVELING || HAS_UBL_AND_CURVES
  358. /**
  359. * Apply leveling to transform a cartesian position
  360. * as it will be given to the planner and steppers.
  361. */
  362. static void apply_leveling(float &rx, float &ry, float &rz);
  363. FORCE_INLINE static void apply_leveling(float (&raw)[XYZ]) { apply_leveling(raw[X_AXIS], raw[Y_AXIS], raw[Z_AXIS]); }
  364. #endif
  365. #if PLANNER_LEVELING
  366. #define ARG_X float rx
  367. #define ARG_Y float ry
  368. #define ARG_Z float rz
  369. #if ENABLED(HANGPRINTER)
  370. #define ARG_E1 float re1
  371. #endif
  372. static void unapply_leveling(float raw[XYZ]);
  373. #else
  374. #define ARG_X const float &rx
  375. #define ARG_Y const float &ry
  376. #define ARG_Z const float &rz
  377. #if ENABLED(HANGPRINTER)
  378. #define ARG_E1 const float &re1
  379. #endif
  380. #endif
  381. // Number of moves currently in the planner including the busy block, if any
  382. FORCE_INLINE static uint8_t movesplanned() { return BLOCK_MOD(block_buffer_head - block_buffer_tail); }
  383. // Number of nonbusy moves currently in the planner
  384. FORCE_INLINE static uint8_t nonbusy_movesplanned() { return BLOCK_MOD(block_buffer_head - block_buffer_nonbusy); }
  385. // Remove all blocks from the buffer
  386. FORCE_INLINE static void clear_block_buffer() { block_buffer_nonbusy = block_buffer_planned = block_buffer_head = block_buffer_tail = 0; }
  387. // Check if movement queue is full
  388. FORCE_INLINE static bool is_full() { return block_buffer_tail == next_block_index(block_buffer_head); }
  389. // Get count of movement slots free
  390. FORCE_INLINE static uint8_t moves_free() { return BLOCK_BUFFER_SIZE - 1 - movesplanned(); }
  391. /**
  392. * Planner::get_next_free_block
  393. *
  394. * - Get the next head indices (passed by reference)
  395. * - Wait for the number of spaces to open up in the planner
  396. * - Return the first head block
  397. */
  398. FORCE_INLINE static block_t* get_next_free_block(uint8_t &next_buffer_head, const uint8_t count=1) {
  399. // Wait until there are enough slots free
  400. while (moves_free() < count) { idle(); }
  401. // Return the first available block
  402. next_buffer_head = next_block_index(block_buffer_head);
  403. return &block_buffer[block_buffer_head];
  404. }
  405. /**
  406. * Planner::_buffer_steps
  407. *
  408. * Add a new linear movement to the buffer (in terms of steps).
  409. *
  410. * target - target position in steps units
  411. * fr_mm_s - (target) speed of the move
  412. * extruder - target extruder
  413. * millimeters - the length of the movement, if known
  414. * count_it - apply this move to the counters (UNREGISTERED_MOVE_SUPPORT)
  415. *
  416. * Returns true if movement was buffered, false otherwise
  417. */
  418. static bool _buffer_steps(const int32_t (&target)[NUM_AXIS]
  419. #if HAS_POSITION_FLOAT
  420. , const float (&target_float)[NUM_AXIS]
  421. #endif
  422. , float fr_mm_s, const uint8_t extruder, const float &millimeters=0.0
  423. #if ENABLED(UNREGISTERED_MOVE_SUPPORT)
  424. , const bool count_it=true
  425. #endif
  426. );
  427. /**
  428. * Planner::_populate_block
  429. *
  430. * Fills a new linear movement in the block (in terms of steps).
  431. *
  432. * target - target position in steps units
  433. * fr_mm_s - (target) speed of the move
  434. * extruder - target extruder
  435. * millimeters - the length of the movement, if known
  436. * count_it - apply this move to the counters (UNREGISTERED_MOVE_SUPPORT)
  437. *
  438. * Returns true is movement is acceptable, false otherwise
  439. */
  440. static bool _populate_block(block_t * const block, bool split_move,
  441. const int32_t (&target)[NUM_AXIS]
  442. #if HAS_POSITION_FLOAT
  443. , const float (&target_float)[NUM_AXIS]
  444. #endif
  445. , float fr_mm_s, const uint8_t extruder, const float &millimeters=0.0
  446. #if ENABLED(UNREGISTERED_MOVE_SUPPORT)
  447. , const bool count_it=true
  448. #endif
  449. );
  450. /**
  451. * Planner::buffer_sync_block
  452. * Add a block to the buffer that just updates the position
  453. */
  454. static void buffer_sync_block();
  455. /**
  456. * Planner::buffer_segment
  457. *
  458. * Add a new linear movement to the buffer in axis units.
  459. *
  460. * Leveling and kinematics should be applied ahead of calling this.
  461. *
  462. * a,b,c,e - target positions in mm and/or degrees
  463. * (a, b, c, d, e for Hangprinter)
  464. * fr_mm_s - (target) speed of the move
  465. * extruder - target extruder
  466. * millimeters - the length of the movement, if known
  467. * count_it - remember this move in its counters (UNREGISTERED_MOVE_SUPPORT)
  468. */
  469. static bool buffer_segment(const float &a, const float &b, const float &c,
  470. #if ENABLED(HANGPRINTER)
  471. const float &d,
  472. #endif
  473. const float &e, const float &fr_mm_s, const uint8_t extruder, const float &millimeters=0.0
  474. #if ENABLED(UNREGISTERED_MOVE_SUPPORT)
  475. , bool count_it=true
  476. #endif
  477. );
  478. static void _set_position_mm(const float &a, const float &b, const float &c,
  479. #if ENABLED(HANGPRINTER)
  480. const float &d,
  481. #endif
  482. const float &e
  483. );
  484. /**
  485. * Add a new linear movement to the buffer.
  486. * The target is NOT translated to delta/scara
  487. *
  488. * Leveling will be applied to input on cartesians.
  489. * Kinematic machines should call buffer_line_kinematic (for leveled moves).
  490. * (Cartesians may also call buffer_line_kinematic.)
  491. *
  492. * rx,ry,rz,e - target position in mm or degrees
  493. * (rx, ry, rz, re1 for Hangprinter)
  494. * fr_mm_s - (target) speed of the move (mm/s)
  495. * extruder - target extruder
  496. * millimeters - the length of the movement, if known
  497. */
  498. FORCE_INLINE static bool buffer_line(ARG_X, ARG_Y, ARG_Z,
  499. #if ENABLED(HANGPRINTER)
  500. ARG_E1,
  501. #endif
  502. const float &e, const float &fr_mm_s, const uint8_t extruder, const float millimeters = 0.0
  503. ) {
  504. #if PLANNER_LEVELING && IS_CARTESIAN
  505. apply_leveling(rx, ry, rz);
  506. #endif
  507. return buffer_segment(rx, ry, rz,
  508. #if ENABLED(HANGPRINTER)
  509. re1,
  510. #endif
  511. e, fr_mm_s, extruder, millimeters
  512. );
  513. }
  514. /**
  515. * Add a new linear movement to the buffer.
  516. * The target is cartesian, it's translated to delta/scara if
  517. * needed.
  518. *
  519. * cart - x,y,z,e CARTESIAN target in mm
  520. * fr_mm_s - (target) speed of the move (mm/s)
  521. * extruder - target extruder
  522. * millimeters - the length of the movement, if known
  523. */
  524. FORCE_INLINE static bool buffer_line_kinematic(const float (&cart)[XYZE], const float &fr_mm_s, const uint8_t extruder, const float millimeters = 0.0) {
  525. #if PLANNER_LEVELING
  526. float raw[XYZ] = { cart[X_AXIS], cart[Y_AXIS], cart[Z_AXIS] };
  527. apply_leveling(raw);
  528. #else
  529. const float (&raw)[XYZE] = cart;
  530. #endif
  531. #if IS_KINEMATIC
  532. inverse_kinematics(raw);
  533. return buffer_segment(
  534. #if ENABLED(HANGPRINTER)
  535. line_lengths[A_AXIS], line_lengths[B_AXIS], line_lengths[C_AXIS], line_lengths[D_AXIS]
  536. #else
  537. delta[A_AXIS], delta[B_AXIS], delta[C_AXIS]
  538. #endif
  539. , cart[E_CART], fr_mm_s, extruder, millimeters
  540. );
  541. #else
  542. return buffer_segment(raw[X_AXIS], raw[Y_AXIS], raw[Z_AXIS], cart[E_CART], fr_mm_s, extruder, millimeters);
  543. #endif
  544. }
  545. /**
  546. * Set the planner.position and individual stepper positions.
  547. * Used by G92, G28, G29, and other procedures.
  548. *
  549. * Multiplies by axis_steps_per_mm[] and does necessary conversion
  550. * for COREXY / COREXZ / COREYZ to set the corresponding stepper positions.
  551. *
  552. * Clears previous speed values.
  553. */
  554. FORCE_INLINE static void set_position_mm(ARG_X, ARG_Y, ARG_Z,
  555. #if ENABLED(HANGPRINTER)
  556. ARG_E1,
  557. #endif
  558. const float &e
  559. ) {
  560. #if PLANNER_LEVELING && IS_CARTESIAN
  561. apply_leveling(rx, ry, rz);
  562. #endif
  563. _set_position_mm(rx, ry, rz,
  564. #if ENABLED(HANGPRINTER)
  565. re1,
  566. #endif
  567. e
  568. );
  569. }
  570. static void set_position_mm_kinematic(const float (&cart)[XYZE]);
  571. static void set_position_mm(const AxisEnum axis, const float &v);
  572. FORCE_INLINE static void set_z_position_mm(const float &z) { set_position_mm(Z_AXIS, z); }
  573. FORCE_INLINE static void set_e_position_mm(const float &e) { set_position_mm(E_AXIS, e); }
  574. /**
  575. * Get an axis position according to stepper position(s)
  576. * For CORE machines apply translation from ABC to XYZ.
  577. */
  578. static float get_axis_position_mm(const AxisEnum axis);
  579. // SCARA AB axes are in degrees, not mm
  580. #if IS_SCARA
  581. FORCE_INLINE static float get_axis_position_degrees(const AxisEnum axis) { return get_axis_position_mm(axis); }
  582. #endif
  583. // Called to force a quick stop of the machine (for example, when an emergency
  584. // stop is required, or when endstops are hit)
  585. static void quick_stop();
  586. // Called when an endstop is triggered. Causes the machine to stop inmediately
  587. static void endstop_triggered(const AxisEnum axis);
  588. // Triggered position of an axis in mm (not core-savvy)
  589. static float triggered_position_mm(const AxisEnum axis);
  590. // Block until all buffered steps are executed / cleaned
  591. static void synchronize();
  592. // Wait for moves to finish and disable all steppers
  593. static void finish_and_disable();
  594. // Periodic tick to handle cleaning timeouts
  595. // Called from the Temperature ISR at ~1kHz
  596. static void tick() {
  597. if (cleaning_buffer_counter) {
  598. --cleaning_buffer_counter;
  599. #if ENABLED(SD_FINISHED_STEPPERRELEASE) && defined(SD_FINISHED_RELEASECOMMAND)
  600. if (!cleaning_buffer_counter) enqueue_and_echo_commands_P(PSTR(SD_FINISHED_RELEASECOMMAND));
  601. #endif
  602. }
  603. }
  604. /**
  605. * Does the buffer have any blocks queued?
  606. */
  607. FORCE_INLINE static bool has_blocks_queued() { return (block_buffer_head != block_buffer_tail); }
  608. /**
  609. * The current block. NULL if the buffer is empty.
  610. * This also marks the block as busy.
  611. * WARNING: Called from Stepper ISR context!
  612. */
  613. static block_t* get_current_block() {
  614. // Get the number of moves in the planner queue so far
  615. const uint8_t nr_moves = movesplanned();
  616. // If there are any moves queued ...
  617. if (nr_moves) {
  618. // If there is still delay of delivery of blocks running, decrement it
  619. if (delay_before_delivering) {
  620. --delay_before_delivering;
  621. // If the number of movements queued is less than 3, and there is still time
  622. // to wait, do not deliver anything
  623. if (nr_moves < 3 && delay_before_delivering) return NULL;
  624. delay_before_delivering = 0;
  625. }
  626. // If we are here, there is no excuse to deliver the block
  627. block_t * const block = &block_buffer[block_buffer_tail];
  628. // No trapezoid calculated? Don't execute yet.
  629. if (TEST(block->flag, BLOCK_BIT_RECALCULATE)) return NULL;
  630. #if ENABLED(ULTRA_LCD)
  631. block_buffer_runtime_us -= block->segment_time_us; // We can't be sure how long an active block will take, so don't count it.
  632. #endif
  633. // As this block is busy, advance the nonbusy block pointer
  634. block_buffer_nonbusy = next_block_index(block_buffer_tail);
  635. // Push block_buffer_planned pointer, if encountered.
  636. if (block_buffer_tail == block_buffer_planned)
  637. block_buffer_planned = block_buffer_nonbusy;
  638. // Return the block
  639. return block;
  640. }
  641. // The queue became empty
  642. #if ENABLED(ULTRA_LCD)
  643. clear_block_buffer_runtime(); // paranoia. Buffer is empty now - so reset accumulated time to zero.
  644. #endif
  645. return NULL;
  646. }
  647. /**
  648. * "Discard" the block and "release" the memory.
  649. * Called when the current block is no longer needed.
  650. * NB: There MUST be a current block to call this function!!
  651. */
  652. FORCE_INLINE static void discard_current_block() {
  653. if (has_blocks_queued())
  654. block_buffer_tail = next_block_index(block_buffer_tail);
  655. }
  656. #if ENABLED(ULTRA_LCD)
  657. static uint16_t block_buffer_runtime() {
  658. bool was_enabled = STEPPER_ISR_ENABLED();
  659. if (was_enabled) DISABLE_STEPPER_DRIVER_INTERRUPT();
  660. millis_t bbru = block_buffer_runtime_us;
  661. if (was_enabled) ENABLE_STEPPER_DRIVER_INTERRUPT();
  662. // To translate µs to ms a division by 1000 would be required.
  663. // We introduce 2.4% error here by dividing by 1024.
  664. // Doesn't matter because block_buffer_runtime_us is already too small an estimation.
  665. bbru >>= 10;
  666. // limit to about a minute.
  667. NOMORE(bbru, 0xFFFFul);
  668. return bbru;
  669. }
  670. static void clear_block_buffer_runtime() {
  671. bool was_enabled = STEPPER_ISR_ENABLED();
  672. if (was_enabled) DISABLE_STEPPER_DRIVER_INTERRUPT();
  673. block_buffer_runtime_us = 0;
  674. if (was_enabled) ENABLE_STEPPER_DRIVER_INTERRUPT();
  675. }
  676. #endif
  677. #if ENABLED(AUTOTEMP)
  678. static float autotemp_min, autotemp_max, autotemp_factor;
  679. static bool autotemp_enabled;
  680. static void getHighESpeed();
  681. static void autotemp_M104_M109();
  682. #endif
  683. #if ENABLED(JUNCTION_DEVIATION)
  684. FORCE_INLINE static void recalculate_max_e_jerk() {
  685. #define GET_MAX_E_JERK(N) SQRT(SQRT(0.5) * junction_deviation_mm * (N) * RECIPROCAL(1.0 - SQRT(0.5)))
  686. #if ENABLED(LIN_ADVANCE)
  687. #if ENABLED(DISTINCT_E_FACTORS)
  688. for (uint8_t i = 0; i < EXTRUDERS; i++)
  689. max_e_jerk[i] = GET_MAX_E_JERK(max_acceleration_mm_per_s2[E_AXIS + i]);
  690. #else
  691. max_e_jerk = GET_MAX_E_JERK(max_acceleration_mm_per_s2[E_AXIS]);
  692. #endif
  693. #endif
  694. }
  695. #endif
  696. private:
  697. /**
  698. * Get the index of the next / previous block in the ring buffer
  699. */
  700. static constexpr uint8_t next_block_index(const uint8_t block_index) { return BLOCK_MOD(block_index + 1); }
  701. static constexpr uint8_t prev_block_index(const uint8_t block_index) { return BLOCK_MOD(block_index - 1); }
  702. /**
  703. * Calculate the distance (not time) it takes to accelerate
  704. * from initial_rate to target_rate using the given acceleration:
  705. */
  706. static float estimate_acceleration_distance(const float &initial_rate, const float &target_rate, const float &accel) {
  707. if (accel == 0) return 0; // accel was 0, set acceleration distance to 0
  708. return (sq(target_rate) - sq(initial_rate)) / (accel * 2);
  709. }
  710. /**
  711. * Return the point at which you must start braking (at the rate of -'accel') if
  712. * you start at 'initial_rate', accelerate (until reaching the point), and want to end at
  713. * 'final_rate' after traveling 'distance'.
  714. *
  715. * This is used to compute the intersection point between acceleration and deceleration
  716. * in cases where the "trapezoid" has no plateau (i.e., never reaches maximum speed)
  717. */
  718. static float intersection_distance(const float &initial_rate, const float &final_rate, const float &accel, const float &distance) {
  719. if (accel == 0) return 0; // accel was 0, set intersection distance to 0
  720. return (accel * 2 * distance - sq(initial_rate) + sq(final_rate)) / (accel * 4);
  721. }
  722. /**
  723. * Calculate the maximum allowable speed squared at this point, in order
  724. * to reach 'target_velocity_sqr' using 'acceleration' within a given
  725. * 'distance'.
  726. */
  727. static float max_allowable_speed_sqr(const float &accel, const float &target_velocity_sqr, const float &distance) {
  728. return target_velocity_sqr - 2 * accel * distance;
  729. }
  730. #if ENABLED(S_CURVE_ACCELERATION)
  731. /**
  732. * Calculate the speed reached given initial speed, acceleration and distance
  733. */
  734. static float final_speed(const float &initial_velocity, const float &accel, const float &distance) {
  735. return SQRT(sq(initial_velocity) + 2 * accel * distance);
  736. }
  737. #endif
  738. static void calculate_trapezoid_for_block(block_t* const block, const float &entry_factor, const float &exit_factor);
  739. static void reverse_pass_kernel(block_t* const current, const block_t * const next);
  740. static void forward_pass_kernel(const block_t * const previous, block_t* const current, uint8_t block_index);
  741. static void reverse_pass();
  742. static void forward_pass();
  743. static void recalculate_trapezoids();
  744. static void recalculate();
  745. #if ENABLED(JUNCTION_DEVIATION)
  746. FORCE_INLINE static void normalize_junction_vector(float (&vector)[XYZE]) {
  747. float magnitude_sq = 0;
  748. LOOP_XYZE(idx) if (vector[idx]) magnitude_sq += sq(vector[idx]);
  749. const float inv_magnitude = RSQRT(magnitude_sq);
  750. LOOP_XYZE(idx) vector[idx] *= inv_magnitude;
  751. }
  752. FORCE_INLINE static float limit_value_by_axis_maximum(const float &max_value, float (&unit_vec)[XYZE]) {
  753. float limit_value = max_value;
  754. LOOP_XYZE(idx) if (unit_vec[idx]) // Avoid divide by zero
  755. NOMORE(limit_value, ABS(max_acceleration_mm_per_s2[idx] / unit_vec[idx]));
  756. return limit_value;
  757. }
  758. #endif // JUNCTION_DEVIATION
  759. };
  760. #define PLANNER_XY_FEEDRATE() (MIN(planner.max_feedrate_mm_s[X_AXIS], planner.max_feedrate_mm_s[Y_AXIS]))
  761. extern Planner planner;
  762. #endif // PLANNER_H