My Marlin configs for Fabrikator Mini and CTC i3 Pro B
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

planner.h 38KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
  4. *
  5. * Based on Sprinter and grbl.
  6. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. *
  21. */
  22. #pragma once
  23. /**
  24. * planner.h
  25. *
  26. * Buffer movement commands and manage the acceleration profile plan
  27. *
  28. * Derived from Grbl
  29. * Copyright (c) 2009-2011 Simen Svale Skogsrud
  30. */
  31. #include "../MarlinCore.h"
  32. #if ENABLED(JD_HANDLE_SMALL_SEGMENTS)
  33. // Enable this option for perfect accuracy but maximum
  34. // computation. Should be fine on ARM processors.
  35. //#define JD_USE_MATH_ACOS
  36. // Disable this option to save 120 bytes of PROGMEM,
  37. // but incur increased computation and a reduction
  38. // in accuracy.
  39. #define JD_USE_LOOKUP_TABLE
  40. #endif
  41. #include "motion.h"
  42. #include "../gcode/queue.h"
  43. #if ENABLED(DELTA)
  44. #include "delta.h"
  45. #elif ENABLED(POLARGRAPH)
  46. #include "polargraph.h"
  47. #endif
  48. #if ABL_PLANAR
  49. #include "../libs/vector_3.h" // for matrix_3x3
  50. #endif
  51. #if ENABLED(FWRETRACT)
  52. #include "../feature/fwretract.h"
  53. #endif
  54. #if ENABLED(MIXING_EXTRUDER)
  55. #include "../feature/mixing.h"
  56. #endif
  57. #if HAS_CUTTER
  58. #include "../feature/spindle_laser_types.h"
  59. #endif
  60. #if ENABLED(DIRECT_STEPPING)
  61. #include "../feature/direct_stepping.h"
  62. #endif
  63. #if ENABLED(EXTERNAL_CLOSED_LOOP_CONTROLLER)
  64. #include "../feature/closedloop.h"
  65. #endif
  66. // Feedrate for manual moves
  67. #ifdef MANUAL_FEEDRATE
  68. constexpr xyze_feedrate_t _mf = MANUAL_FEEDRATE,
  69. manual_feedrate_mm_s = LOGICAL_AXIS_ARRAY(_mf.e / 60.0f,
  70. _mf.x / 60.0f, _mf.y / 60.0f, _mf.z / 60.0f,
  71. _mf.i / 60.0f, _mf.j / 60.0f, _mf.k / 60.0f,
  72. _mf.u / 60.0f, _mf.v / 60.0f, _mf.w / 60.0f);
  73. #endif
  74. #if IS_KINEMATIC && HAS_JUNCTION_DEVIATION
  75. #define HAS_DIST_MM_ARG 1
  76. #endif
  77. /**
  78. * Planner block flags as boolean bit fields
  79. */
  80. enum BlockFlagBit {
  81. // Recalculate trapezoids on entry junction. For optimization.
  82. BLOCK_BIT_RECALCULATE,
  83. // Nominal speed always reached.
  84. // i.e., The segment is long enough, so the nominal speed is reachable if accelerating
  85. // from a safe speed (in consideration of jerking from zero speed).
  86. BLOCK_BIT_NOMINAL_LENGTH,
  87. // The block is segment 2+ of a longer move
  88. BLOCK_BIT_CONTINUED,
  89. // Sync the stepper counts from the block
  90. BLOCK_BIT_SYNC_POSITION
  91. // Direct stepping page
  92. OPTARG(DIRECT_STEPPING, BLOCK_BIT_PAGE)
  93. // Sync the fan speeds from the block
  94. OPTARG(LASER_SYNCHRONOUS_M106_M107, BLOCK_BIT_SYNC_FANS)
  95. // Sync laser power from a queued block
  96. OPTARG(LASER_POWER_SYNC, BLOCK_BIT_LASER_PWR)
  97. };
  98. /**
  99. * Planner block flags as boolean bit fields
  100. */
  101. typedef struct {
  102. union {
  103. uint8_t bits;
  104. struct {
  105. bool recalculate:1;
  106. bool nominal_length:1;
  107. bool continued:1;
  108. bool sync_position:1;
  109. #if ENABLED(DIRECT_STEPPING)
  110. bool page:1;
  111. #endif
  112. #if ENABLED(LASER_SYNCHRONOUS_M106_M107)
  113. bool sync_fans:1;
  114. #endif
  115. #if ENABLED(LASER_POWER_SYNC)
  116. bool sync_laser_pwr:1;
  117. #endif
  118. };
  119. };
  120. void clear() volatile { bits = 0; }
  121. void apply(const uint8_t f) volatile { bits |= f; }
  122. void apply(const BlockFlagBit b) volatile { SBI(bits, b); }
  123. void reset(const BlockFlagBit b) volatile { bits = _BV(b); }
  124. void set_nominal(const bool n) volatile { recalculate = true; if (n) nominal_length = true; }
  125. } block_flags_t;
  126. #if ENABLED(LASER_FEATURE)
  127. typedef struct {
  128. bool isEnabled:1; // Set to engage the inline laser power output.
  129. bool dir:1;
  130. bool isPowered:1; // Set on any parsed G1, G2, G3, or G5 powered move, cleared on G0 and G28.
  131. bool isSyncPower:1; // Set on a M3 sync based set laser power, used to determine active trap power
  132. bool Reserved:4;
  133. } power_status_t;
  134. typedef struct {
  135. power_status_t status; // See planner settings for meaning
  136. uint8_t power; // Ditto; When in trapezoid mode this is nominal power
  137. #if ENABLED(LASER_POWER_TRAP)
  138. float trap_ramp_active_pwr; // Laser power level during active trapezoid smoothing
  139. float trap_ramp_entry_incr; // Acceleration per step laser power increment (trap entry)
  140. float trap_ramp_exit_decr; // Deceleration per step laser power decrement (trap exit)
  141. #endif
  142. } block_laser_t;
  143. #endif
  144. /**
  145. * struct block_t
  146. *
  147. * A single entry in the planner buffer.
  148. * Tracks linear movement over multiple axes.
  149. *
  150. * The "nominal" values are as-specified by G-code, and
  151. * may never actually be reached due to acceleration limits.
  152. */
  153. typedef struct PlannerBlock {
  154. volatile block_flags_t flag; // Block flags
  155. bool is_fan_sync() { return TERN0(LASER_SYNCHRONOUS_M106_M107, flag.sync_fans); }
  156. bool is_pwr_sync() { return TERN0(LASER_POWER_SYNC, flag.sync_laser_pwr); }
  157. bool is_sync() { return flag.sync_position || is_fan_sync() || is_pwr_sync(); }
  158. bool is_page() { return TERN0(DIRECT_STEPPING, flag.page); }
  159. bool is_move() { return !(is_sync() || is_page()); }
  160. // Fields used by the motion planner to manage acceleration
  161. float nominal_speed, // The nominal speed for this block in (mm/sec)
  162. entry_speed_sqr, // Entry speed at previous-current junction in (mm/sec)^2
  163. max_entry_speed_sqr, // Maximum allowable junction entry speed in (mm/sec)^2
  164. millimeters, // The total travel of this block in mm
  165. acceleration; // acceleration mm/sec^2
  166. union {
  167. abce_ulong_t steps; // Step count along each axis
  168. abce_long_t position; // New position to force when this sync block is executed
  169. };
  170. uint32_t step_event_count; // The number of step events required to complete this block
  171. #if HAS_MULTI_EXTRUDER
  172. uint8_t extruder; // The extruder to move (if E move)
  173. #else
  174. static constexpr uint8_t extruder = 0;
  175. #endif
  176. #if ENABLED(MIXING_EXTRUDER)
  177. mixer_comp_t b_color[MIXING_STEPPERS]; // Normalized color for the mixing steppers
  178. #endif
  179. // Settings for the trapezoid generator
  180. uint32_t accelerate_until, // The index of the step event on which to stop acceleration
  181. decelerate_after; // The index of the step event on which to start decelerating
  182. #if ENABLED(S_CURVE_ACCELERATION)
  183. uint32_t cruise_rate, // The actual cruise rate to use, between end of the acceleration phase and start of deceleration phase
  184. acceleration_time, // Acceleration time and deceleration time in STEP timer counts
  185. deceleration_time,
  186. acceleration_time_inverse, // Inverse of acceleration and deceleration periods, expressed as integer. Scale depends on CPU being used
  187. deceleration_time_inverse;
  188. #else
  189. uint32_t acceleration_rate; // The acceleration rate used for acceleration calculation
  190. #endif
  191. axis_bits_t direction_bits; // The direction bit set for this block (refers to *_DIRECTION_BIT in config.h)
  192. // Advance extrusion
  193. #if ENABLED(LIN_ADVANCE)
  194. uint32_t la_advance_rate; // The rate at which steps are added whilst accelerating
  195. uint8_t la_scaling; // Scale ISR frequency down and step frequency up by 2 ^ la_scaling
  196. uint16_t max_adv_steps, // Max advance steps to get cruising speed pressure
  197. final_adv_steps; // Advance steps for exit speed pressure
  198. #endif
  199. uint32_t nominal_rate, // The nominal step rate for this block in step_events/sec
  200. initial_rate, // The jerk-adjusted step rate at start of block
  201. final_rate, // The minimal rate at exit
  202. acceleration_steps_per_s2; // acceleration steps/sec^2
  203. #if ENABLED(DIRECT_STEPPING)
  204. page_idx_t page_idx; // Page index used for direct stepping
  205. #endif
  206. #if HAS_CUTTER
  207. cutter_power_t cutter_power; // Power level for Spindle, Laser, etc.
  208. #endif
  209. #if HAS_FAN
  210. uint8_t fan_speed[FAN_COUNT];
  211. #endif
  212. #if ENABLED(BARICUDA)
  213. uint8_t valve_pressure, e_to_p_pressure;
  214. #endif
  215. #if HAS_WIRED_LCD
  216. uint32_t segment_time_us;
  217. #endif
  218. #if ENABLED(POWER_LOSS_RECOVERY)
  219. uint32_t sdpos;
  220. xyze_pos_t start_position;
  221. #endif
  222. #if ENABLED(LASER_FEATURE)
  223. block_laser_t laser;
  224. #endif
  225. void reset() { memset((char*)this, 0, sizeof(*this)); }
  226. } block_t;
  227. #if ANY(LIN_ADVANCE, SCARA_FEEDRATE_SCALING, GRADIENT_MIX, LCD_SHOW_E_TOTAL, POWER_LOSS_RECOVERY)
  228. #define HAS_POSITION_FLOAT 1
  229. #endif
  230. #define BLOCK_MOD(n) ((n)&(BLOCK_BUFFER_SIZE-1))
  231. #if ENABLED(LASER_FEATURE)
  232. typedef struct {
  233. /**
  234. * Laser status flags
  235. */
  236. power_status_t status;
  237. /**
  238. * Laser power: 0 or 255 in case of PWM-less laser,
  239. * or the OCR (oscillator count register) value;
  240. * Using OCR instead of raw power, because it avoids
  241. * floating point operations during the move loop.
  242. */
  243. volatile uint8_t power;
  244. } laser_state_t;
  245. #endif
  246. typedef struct {
  247. uint32_t max_acceleration_mm_per_s2[DISTINCT_AXES], // (mm/s^2) M201 XYZE
  248. min_segment_time_us; // (µs) M205 B
  249. float axis_steps_per_mm[DISTINCT_AXES]; // (steps) M92 XYZE - Steps per millimeter
  250. feedRate_t max_feedrate_mm_s[DISTINCT_AXES]; // (mm/s) M203 XYZE - Max speeds
  251. float acceleration, // (mm/s^2) M204 S - Normal acceleration. DEFAULT ACCELERATION for all printing moves.
  252. retract_acceleration, // (mm/s^2) M204 R - Retract acceleration. Filament pull-back and push-forward while standing still in the other axes
  253. travel_acceleration; // (mm/s^2) M204 T - Travel acceleration. DEFAULT ACCELERATION for all NON printing moves.
  254. feedRate_t min_feedrate_mm_s, // (mm/s) M205 S - Minimum linear feedrate
  255. min_travel_feedrate_mm_s; // (mm/s) M205 T - Minimum travel feedrate
  256. } planner_settings_t;
  257. #if ENABLED(IMPROVE_HOMING_RELIABILITY)
  258. struct motion_state_t {
  259. TERN(DELTA, xyz_ulong_t, xy_ulong_t) acceleration;
  260. #if HAS_CLASSIC_JERK
  261. TERN(DELTA, xyz_float_t, xy_float_t) jerk_state;
  262. #endif
  263. };
  264. #endif
  265. #if DISABLED(SKEW_CORRECTION)
  266. #define XY_SKEW_FACTOR 0
  267. #define XZ_SKEW_FACTOR 0
  268. #define YZ_SKEW_FACTOR 0
  269. #endif
  270. typedef struct {
  271. #if ENABLED(SKEW_CORRECTION_GCODE)
  272. float xy;
  273. #if ENABLED(SKEW_CORRECTION_FOR_Z)
  274. float xz, yz;
  275. #else
  276. const float xz = XZ_SKEW_FACTOR, yz = YZ_SKEW_FACTOR;
  277. #endif
  278. #else
  279. const float xy = XY_SKEW_FACTOR,
  280. xz = XZ_SKEW_FACTOR, yz = YZ_SKEW_FACTOR;
  281. #endif
  282. } skew_factor_t;
  283. #if ENABLED(DISABLE_INACTIVE_EXTRUDER)
  284. typedef IF<(BLOCK_BUFFER_SIZE > 64), uint16_t, uint8_t>::type last_move_t;
  285. #endif
  286. #if ENABLED(ARC_SUPPORT)
  287. #define HINTS_CURVE_RADIUS
  288. #define HINTS_SAFE_EXIT_SPEED
  289. #endif
  290. struct PlannerHints {
  291. float millimeters = 0.0; // Move Length, if known, else 0.
  292. #if ENABLED(SCARA_FEEDRATE_SCALING)
  293. float inv_duration = 0.0; // Reciprocal of the move duration, if known
  294. #endif
  295. #if ENABLED(HINTS_CURVE_RADIUS)
  296. float curve_radius = 0.0; // Radius of curvature of the motion path - to calculate cornering speed
  297. #else
  298. static constexpr float curve_radius = 0.0;
  299. #endif
  300. #if ENABLED(HINTS_SAFE_EXIT_SPEED)
  301. float safe_exit_speed_sqr = 0.0; // Square of the speed considered "safe" at the end of the segment
  302. // i.e., at or below the exit speed of the segment that the planner
  303. // would calculate if it knew the as-yet-unbuffered path
  304. #endif
  305. PlannerHints(const_float_t mm=0.0f) : millimeters(mm) {}
  306. };
  307. class Planner {
  308. public:
  309. /**
  310. * The move buffer, calculated in stepper steps
  311. *
  312. * block_buffer is a ring buffer...
  313. *
  314. * head,tail : indexes for write,read
  315. * head==tail : the buffer is empty
  316. * head!=tail : blocks are in the buffer
  317. * head==(tail-1)%size : the buffer is full
  318. *
  319. * Writer of head is Planner::buffer_segment().
  320. * Reader of tail is Stepper::isr(). Always consider tail busy / read-only
  321. */
  322. static block_t block_buffer[BLOCK_BUFFER_SIZE];
  323. static volatile uint8_t block_buffer_head, // Index of the next block to be pushed
  324. block_buffer_nonbusy, // Index of the first non busy block
  325. block_buffer_planned, // Index of the optimally planned block
  326. block_buffer_tail; // Index of the busy block, if any
  327. static uint16_t cleaning_buffer_counter; // A counter to disable queuing of blocks
  328. static uint8_t delay_before_delivering; // This counter delays delivery of blocks when queue becomes empty to allow the opportunity of merging blocks
  329. #if ENABLED(DISTINCT_E_FACTORS)
  330. static uint8_t last_extruder; // Respond to extruder change
  331. #endif
  332. #if ENABLED(DIRECT_STEPPING)
  333. static uint32_t last_page_step_rate; // Last page step rate given
  334. static xyze_bool_t last_page_dir; // Last page direction given
  335. #endif
  336. #if HAS_EXTRUDERS
  337. static int16_t flow_percentage[EXTRUDERS]; // Extrusion factor for each extruder
  338. static float e_factor[EXTRUDERS]; // The flow percentage and volumetric multiplier combine to scale E movement
  339. #endif
  340. #if DISABLED(NO_VOLUMETRICS)
  341. 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
  342. volumetric_area_nominal, // Nominal cross-sectional area
  343. volumetric_multiplier[EXTRUDERS]; // Reciprocal of cross-sectional area of filament (in mm^2). Pre-calculated to reduce computation in the planner
  344. // May be auto-adjusted by a filament width sensor
  345. #endif
  346. #if ENABLED(VOLUMETRIC_EXTRUDER_LIMIT)
  347. static float volumetric_extruder_limit[EXTRUDERS], // Maximum mm^3/sec the extruder can handle
  348. volumetric_extruder_feedrate_limit[EXTRUDERS]; // Feedrate limit (mm/s) calculated from volume limit
  349. #endif
  350. static planner_settings_t settings;
  351. #if ENABLED(LASER_FEATURE)
  352. static laser_state_t laser_inline;
  353. #endif
  354. static uint32_t max_acceleration_steps_per_s2[DISTINCT_AXES]; // (steps/s^2) Derived from mm_per_s2
  355. static float mm_per_step[DISTINCT_AXES]; // Millimeters per step
  356. #if HAS_JUNCTION_DEVIATION
  357. static float junction_deviation_mm; // (mm) M205 J
  358. #if HAS_LINEAR_E_JERK
  359. static float max_e_jerk[DISTINCT_E]; // Calculated from junction_deviation_mm
  360. #endif
  361. #endif
  362. #if HAS_CLASSIC_JERK
  363. // (mm/s^2) M205 XYZ(E) - The largest speed change requiring no acceleration.
  364. static TERN(HAS_LINEAR_E_JERK, xyz_pos_t, xyze_pos_t) max_jerk;
  365. #endif
  366. #if HAS_LEVELING
  367. static bool leveling_active; // Flag that bed leveling is enabled
  368. #if ABL_PLANAR
  369. static matrix_3x3 bed_level_matrix; // Transform to compensate for bed level
  370. #endif
  371. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  372. static float z_fade_height, inverse_z_fade_height;
  373. #endif
  374. #else
  375. static constexpr bool leveling_active = false;
  376. #endif
  377. #if ENABLED(LIN_ADVANCE)
  378. static float extruder_advance_K[DISTINCT_E];
  379. #endif
  380. /**
  381. * The current position of the tool in absolute steps
  382. * Recalculated if any axis_steps_per_mm are changed by G-code
  383. */
  384. static xyze_long_t position;
  385. #if HAS_POSITION_FLOAT
  386. static xyze_pos_t position_float;
  387. #endif
  388. #if IS_KINEMATIC
  389. static xyze_pos_t position_cart;
  390. #endif
  391. static skew_factor_t skew_factor;
  392. #if ENABLED(SD_ABORT_ON_ENDSTOP_HIT)
  393. static bool abort_on_endstop_hit;
  394. #endif
  395. #ifdef XY_FREQUENCY_LIMIT
  396. static int8_t xy_freq_limit_hz; // Minimum XY frequency setting
  397. static float xy_freq_min_speed_factor; // Minimum speed factor setting
  398. static int32_t xy_freq_min_interval_us; // Minimum segment time based on xy_freq_limit_hz
  399. static void refresh_frequency_limit() {
  400. //xy_freq_min_interval_us = xy_freq_limit_hz ?: LROUND(1000000.0f / xy_freq_limit_hz);
  401. if (xy_freq_limit_hz)
  402. xy_freq_min_interval_us = LROUND(1000000.0f / xy_freq_limit_hz);
  403. }
  404. static void set_min_speed_factor_u8(const uint8_t v255) {
  405. xy_freq_min_speed_factor = float(ui8_to_percent(v255)) / 100;
  406. }
  407. static void set_frequency_limit(const uint8_t hz) {
  408. xy_freq_limit_hz = constrain(hz, 0, 100);
  409. refresh_frequency_limit();
  410. }
  411. #endif
  412. private:
  413. /**
  414. * Speed of previous path line segment
  415. */
  416. static xyze_float_t previous_speed;
  417. /**
  418. * Nominal speed of previous path line segment (mm/s)^2
  419. */
  420. static float previous_nominal_speed;
  421. /**
  422. * Limit where 64bit math is necessary for acceleration calculation
  423. */
  424. static uint32_t acceleration_long_cutoff;
  425. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  426. static float last_fade_z;
  427. #endif
  428. #if ENABLED(DISABLE_INACTIVE_EXTRUDER)
  429. // Counters to manage disabling inactive extruder steppers
  430. static last_move_t g_uc_extruder_last_move[E_STEPPERS];
  431. #endif
  432. #if HAS_WIRED_LCD
  433. volatile static uint32_t block_buffer_runtime_us; // Theoretical block buffer runtime in µs
  434. #endif
  435. public:
  436. /**
  437. * Instance Methods
  438. */
  439. Planner();
  440. void init();
  441. /**
  442. * Static (class) Methods
  443. */
  444. // Recalculate steps/s^2 accelerations based on mm/s^2 settings
  445. static void refresh_acceleration_rates();
  446. /**
  447. * Recalculate 'position' and 'mm_per_step'.
  448. * Must be called whenever settings.axis_steps_per_mm changes!
  449. */
  450. static void refresh_positioning();
  451. // For an axis set the Maximum Acceleration in mm/s^2
  452. static void set_max_acceleration(const AxisEnum axis, float inMaxAccelMMS2);
  453. // For an axis set the Maximum Feedrate in mm/s
  454. static void set_max_feedrate(const AxisEnum axis, float inMaxFeedrateMMS);
  455. // For an axis set the Maximum Jerk (instant change) in mm/s
  456. #if HAS_CLASSIC_JERK
  457. static void set_max_jerk(const AxisEnum axis, float inMaxJerkMMS);
  458. #else
  459. static void set_max_jerk(const AxisEnum, const_float_t) {}
  460. #endif
  461. #if HAS_EXTRUDERS
  462. FORCE_INLINE static void refresh_e_factor(const uint8_t e) {
  463. e_factor[e] = flow_percentage[e] * 0.01f * TERN(NO_VOLUMETRICS, 1.0f, volumetric_multiplier[e]);
  464. }
  465. static void set_flow(const uint8_t e, const int16_t flow) {
  466. flow_percentage[e] = flow;
  467. refresh_e_factor(e);
  468. }
  469. #endif
  470. // Manage fans, paste pressure, etc.
  471. static void check_axes_activity();
  472. // Apply fan speeds
  473. #if HAS_FAN
  474. static void sync_fan_speeds(uint8_t (&fan_speed)[FAN_COUNT]);
  475. #if FAN_KICKSTART_TIME
  476. static void kickstart_fan(uint8_t (&fan_speed)[FAN_COUNT], const millis_t &ms, const uint8_t f);
  477. #else
  478. FORCE_INLINE static void kickstart_fan(uint8_t (&)[FAN_COUNT], const millis_t &, const uint8_t) {}
  479. #endif
  480. #endif
  481. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  482. void apply_filament_width_sensor(const int8_t encoded_ratio);
  483. static float volumetric_percent(const bool vol) {
  484. return 100.0f * (vol
  485. ? volumetric_area_nominal / volumetric_multiplier[FILAMENT_SENSOR_EXTRUDER_NUM]
  486. : volumetric_multiplier[FILAMENT_SENSOR_EXTRUDER_NUM]
  487. );
  488. }
  489. #endif
  490. #if ENABLED(IMPROVE_HOMING_RELIABILITY)
  491. void enable_stall_prevention(const bool onoff);
  492. #endif
  493. #if DISABLED(NO_VOLUMETRICS)
  494. // Update multipliers based on new diameter measurements
  495. static void calculate_volumetric_multipliers();
  496. #if ENABLED(VOLUMETRIC_EXTRUDER_LIMIT)
  497. // Update pre calculated extruder feedrate limits based on volumetric values
  498. static void calculate_volumetric_extruder_limit(const uint8_t e);
  499. static void calculate_volumetric_extruder_limits();
  500. #endif
  501. FORCE_INLINE static void set_filament_size(const uint8_t e, const_float_t v) {
  502. filament_size[e] = v;
  503. if (v > 0) volumetric_area_nominal = CIRCLE_AREA(v * 0.5); //TODO: should it be per extruder
  504. // make sure all extruders have some sane value for the filament size
  505. LOOP_L_N(i, COUNT(filament_size))
  506. if (!filament_size[i]) filament_size[i] = DEFAULT_NOMINAL_FILAMENT_DIA;
  507. }
  508. #endif
  509. #if ENABLED(VOLUMETRIC_EXTRUDER_LIMIT)
  510. FORCE_INLINE static void set_volumetric_extruder_limit(const uint8_t e, const_float_t v) {
  511. volumetric_extruder_limit[e] = v;
  512. calculate_volumetric_extruder_limit(e);
  513. }
  514. #endif
  515. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  516. /**
  517. * Get the Z leveling fade factor based on the given Z height,
  518. * re-calculating only when needed.
  519. *
  520. * Returns 1.0 if planner.z_fade_height is 0.0.
  521. * Returns 0.0 if Z is past the specified 'Fade Height'.
  522. */
  523. static float fade_scaling_factor_for_z(const_float_t rz) {
  524. static float z_fade_factor = 1;
  525. if (!z_fade_height || rz <= 0) return 1;
  526. if (rz >= z_fade_height) return 0;
  527. if (last_fade_z != rz) {
  528. last_fade_z = rz;
  529. z_fade_factor = 1 - rz * inverse_z_fade_height;
  530. }
  531. return z_fade_factor;
  532. }
  533. FORCE_INLINE static void force_fade_recalc() { last_fade_z = -999.999f; }
  534. FORCE_INLINE static void set_z_fade_height(const_float_t zfh) {
  535. z_fade_height = zfh > 0 ? zfh : 0;
  536. inverse_z_fade_height = RECIPROCAL(z_fade_height);
  537. force_fade_recalc();
  538. }
  539. FORCE_INLINE static bool leveling_active_at_z(const_float_t rz) {
  540. return !z_fade_height || rz < z_fade_height;
  541. }
  542. #else
  543. FORCE_INLINE static float fade_scaling_factor_for_z(const_float_t) { return 1; }
  544. FORCE_INLINE static bool leveling_active_at_z(const_float_t) { return true; }
  545. #endif
  546. #if ENABLED(SKEW_CORRECTION)
  547. FORCE_INLINE static void skew(float &cx, float &cy, const_float_t cz) {
  548. if (COORDINATE_OKAY(cx, X_MIN_POS + 1, X_MAX_POS) && COORDINATE_OKAY(cy, Y_MIN_POS + 1, Y_MAX_POS)) {
  549. const float sx = cx - cy * skew_factor.xy - cz * (skew_factor.xz - (skew_factor.xy * skew_factor.yz)),
  550. sy = cy - cz * skew_factor.yz;
  551. if (COORDINATE_OKAY(sx, X_MIN_POS, X_MAX_POS) && COORDINATE_OKAY(sy, Y_MIN_POS, Y_MAX_POS)) {
  552. cx = sx; cy = sy;
  553. }
  554. }
  555. }
  556. FORCE_INLINE static void skew(xyz_pos_t &raw) { skew(raw.x, raw.y, raw.z); }
  557. FORCE_INLINE static void unskew(float &cx, float &cy, const_float_t cz) {
  558. if (COORDINATE_OKAY(cx, X_MIN_POS, X_MAX_POS) && COORDINATE_OKAY(cy, Y_MIN_POS, Y_MAX_POS)) {
  559. const float sx = cx + cy * skew_factor.xy + cz * skew_factor.xz,
  560. sy = cy + cz * skew_factor.yz;
  561. if (COORDINATE_OKAY(sx, X_MIN_POS, X_MAX_POS) && COORDINATE_OKAY(sy, Y_MIN_POS, Y_MAX_POS)) {
  562. cx = sx; cy = sy;
  563. }
  564. }
  565. }
  566. FORCE_INLINE static void unskew(xyz_pos_t &raw) { unskew(raw.x, raw.y, raw.z); }
  567. #endif // SKEW_CORRECTION
  568. #if HAS_LEVELING
  569. /**
  570. * Apply leveling to transform a cartesian position
  571. * as it will be given to the planner and steppers.
  572. */
  573. static void apply_leveling(xyz_pos_t &raw);
  574. static void unapply_leveling(xyz_pos_t &raw);
  575. FORCE_INLINE static void force_unapply_leveling(xyz_pos_t &raw) {
  576. leveling_active = true;
  577. unapply_leveling(raw);
  578. leveling_active = false;
  579. }
  580. #else
  581. FORCE_INLINE static void apply_leveling(xyz_pos_t&) {}
  582. FORCE_INLINE static void unapply_leveling(xyz_pos_t&) {}
  583. #endif
  584. #if ENABLED(FWRETRACT)
  585. static void apply_retract(float &rz, float &e);
  586. FORCE_INLINE static void apply_retract(xyze_pos_t &raw) { apply_retract(raw.z, raw.e); }
  587. static void unapply_retract(float &rz, float &e);
  588. FORCE_INLINE static void unapply_retract(xyze_pos_t &raw) { unapply_retract(raw.z, raw.e); }
  589. #endif
  590. #if HAS_POSITION_MODIFIERS
  591. FORCE_INLINE static void apply_modifiers(xyze_pos_t &pos, bool leveling=ENABLED(PLANNER_LEVELING)) {
  592. TERN_(SKEW_CORRECTION, skew(pos));
  593. if (leveling) apply_leveling(pos);
  594. TERN_(FWRETRACT, apply_retract(pos));
  595. }
  596. FORCE_INLINE static void unapply_modifiers(xyze_pos_t &pos, bool leveling=ENABLED(PLANNER_LEVELING)) {
  597. TERN_(FWRETRACT, unapply_retract(pos));
  598. if (leveling) unapply_leveling(pos);
  599. TERN_(SKEW_CORRECTION, unskew(pos));
  600. }
  601. #endif // HAS_POSITION_MODIFIERS
  602. // Number of moves currently in the planner including the busy block, if any
  603. FORCE_INLINE static uint8_t movesplanned() { return BLOCK_MOD(block_buffer_head - block_buffer_tail); }
  604. // Number of nonbusy moves currently in the planner
  605. FORCE_INLINE static uint8_t nonbusy_movesplanned() { return BLOCK_MOD(block_buffer_head - block_buffer_nonbusy); }
  606. // Remove all blocks from the buffer
  607. FORCE_INLINE static void clear_block_buffer() { block_buffer_nonbusy = block_buffer_planned = block_buffer_head = block_buffer_tail = 0; }
  608. // Check if movement queue is full
  609. FORCE_INLINE static bool is_full() { return block_buffer_tail == next_block_index(block_buffer_head); }
  610. // Get count of movement slots free
  611. FORCE_INLINE static uint8_t moves_free() { return BLOCK_BUFFER_SIZE - 1 - movesplanned(); }
  612. /**
  613. * Planner::get_next_free_block
  614. *
  615. * - Get the next head indices (passed by reference)
  616. * - Wait for the number of spaces to open up in the planner
  617. * - Return the first head block
  618. */
  619. FORCE_INLINE static block_t* get_next_free_block(uint8_t &next_buffer_head, const uint8_t count=1) {
  620. // Wait until there are enough slots free
  621. while (moves_free() < count) { idle(); }
  622. // Return the first available block
  623. next_buffer_head = next_block_index(block_buffer_head);
  624. return &block_buffer[block_buffer_head];
  625. }
  626. /**
  627. * Planner::_buffer_steps
  628. *
  629. * Add a new linear movement to the buffer (in terms of steps).
  630. *
  631. * target - target position in steps units
  632. * fr_mm_s - (target) speed of the move
  633. * extruder - target extruder
  634. * hints - parameters to aid planner calculations
  635. *
  636. * Returns true if movement was buffered, false otherwise
  637. */
  638. static bool _buffer_steps(const xyze_long_t &target
  639. OPTARG(HAS_POSITION_FLOAT, const xyze_pos_t &target_float)
  640. OPTARG(HAS_DIST_MM_ARG, const xyze_float_t &cart_dist_mm)
  641. , feedRate_t fr_mm_s, const uint8_t extruder, const PlannerHints &hints
  642. );
  643. /**
  644. * @brief Populate a block in preparation for insertion
  645. * @details Populate the fields of a new linear movement block
  646. * that will be added to the queue and processed soon
  647. * by the Stepper ISR.
  648. *
  649. * @param block A block to populate
  650. * @param target Target position in steps units
  651. * @param target_float Target position in native mm
  652. * @param cart_dist_mm The pre-calculated move lengths for all axes, in mm
  653. * @param fr_mm_s (target) speed of the move
  654. * @param extruder target extruder
  655. * @param hints parameters to aid planner calculations
  656. *
  657. * @return true if movement is acceptable, false otherwise
  658. */
  659. static bool _populate_block(block_t * const block, const xyze_long_t &target
  660. OPTARG(HAS_POSITION_FLOAT, const xyze_pos_t &target_float)
  661. OPTARG(HAS_DIST_MM_ARG, const xyze_float_t &cart_dist_mm)
  662. , feedRate_t fr_mm_s, const uint8_t extruder, const PlannerHints &hints
  663. );
  664. /**
  665. * Planner::buffer_sync_block
  666. * Add a block to the buffer that just updates the position
  667. * @param sync_flag sets a condition bit to process additional items
  668. * such as sync fan pwm or sync M3/M4 laser power into a queued block
  669. */
  670. static void buffer_sync_block(const BlockFlagBit flag=BLOCK_BIT_SYNC_POSITION);
  671. #if IS_KINEMATIC
  672. private:
  673. // Allow do_homing_move to access internal functions, such as buffer_segment.
  674. friend void do_homing_move(const AxisEnum, const float, const feedRate_t, const bool);
  675. #endif
  676. /**
  677. * Planner::buffer_segment
  678. *
  679. * Add a new linear movement to the buffer in axis units.
  680. *
  681. * Leveling and kinematics should be applied ahead of calling this.
  682. *
  683. * a,b,c,e - target positions in mm and/or degrees
  684. * fr_mm_s - (target) speed of the move
  685. * extruder - optional target extruder (otherwise active_extruder)
  686. * hints - optional parameters to aid planner calculations
  687. */
  688. static bool buffer_segment(const abce_pos_t &abce
  689. OPTARG(HAS_DIST_MM_ARG, const xyze_float_t &cart_dist_mm)
  690. , const_feedRate_t fr_mm_s
  691. , const uint8_t extruder=active_extruder
  692. , const PlannerHints &hints=PlannerHints()
  693. );
  694. public:
  695. /**
  696. * Add a new linear movement to the buffer.
  697. * The target is cartesian. It's translated to
  698. * delta/scara if needed.
  699. *
  700. * cart - target position in mm or degrees
  701. * fr_mm_s - (target) speed of the move (mm/s)
  702. * extruder - optional target extruder (otherwise active_extruder)
  703. * hints - optional parameters to aid planner calculations
  704. */
  705. static bool buffer_line(const xyze_pos_t &cart, const_feedRate_t fr_mm_s
  706. , const uint8_t extruder=active_extruder
  707. , const PlannerHints &hints=PlannerHints()
  708. );
  709. #if ENABLED(DIRECT_STEPPING)
  710. static void buffer_page(const page_idx_t page_idx, const uint8_t extruder, const uint16_t num_steps);
  711. #endif
  712. /**
  713. * Set the planner.position and individual stepper positions.
  714. * Used by G92, G28, G29, and other procedures.
  715. *
  716. * The supplied position is in the cartesian coordinate space and is
  717. * translated in to machine space as needed. Modifiers such as leveling
  718. * and skew are also applied.
  719. *
  720. * Multiplies by axis_steps_per_mm[] and does necessary conversion
  721. * for COREXY / COREXZ / COREYZ to set the corresponding stepper positions.
  722. *
  723. * Clears previous speed values.
  724. */
  725. static void set_position_mm(const xyze_pos_t &xyze);
  726. #if HAS_EXTRUDERS
  727. static void set_e_position_mm(const_float_t e);
  728. #endif
  729. /**
  730. * Set the planner.position and individual stepper positions.
  731. *
  732. * The supplied position is in machine space, and no additional
  733. * conversions are applied.
  734. */
  735. static void set_machine_position_mm(const abce_pos_t &abce);
  736. /**
  737. * Get an axis position according to stepper position(s)
  738. * For CORE machines apply translation from ABC to XYZ.
  739. */
  740. static float get_axis_position_mm(const AxisEnum axis);
  741. static abce_pos_t get_axis_positions_mm() {
  742. const abce_pos_t out = LOGICAL_AXIS_ARRAY(
  743. get_axis_position_mm(E_AXIS),
  744. get_axis_position_mm(A_AXIS), get_axis_position_mm(B_AXIS), get_axis_position_mm(C_AXIS),
  745. get_axis_position_mm(I_AXIS), get_axis_position_mm(J_AXIS), get_axis_position_mm(K_AXIS),
  746. get_axis_position_mm(U_AXIS), get_axis_position_mm(V_AXIS), get_axis_position_mm(W_AXIS)
  747. );
  748. return out;
  749. }
  750. // SCARA AB axes are in degrees, not mm
  751. #if IS_SCARA
  752. FORCE_INLINE static float get_axis_position_degrees(const AxisEnum axis) { return get_axis_position_mm(axis); }
  753. #endif
  754. // Called to force a quick stop of the machine (for example, when
  755. // a Full Shutdown is required, or when endstops are hit)
  756. static void quick_stop();
  757. #if ENABLED(REALTIME_REPORTING_COMMANDS)
  758. // Force a quick pause of the machine (e.g., when a pause is required in the middle of move).
  759. // NOTE: Hard-stops will lose steps so encoders are highly recommended if using these!
  760. static void quick_pause();
  761. static void quick_resume();
  762. #endif
  763. // Called when an endstop is triggered. Causes the machine to stop immediately
  764. static void endstop_triggered(const AxisEnum axis);
  765. // Triggered position of an axis in mm (not core-savvy)
  766. static float triggered_position_mm(const AxisEnum axis);
  767. // Blocks are queued, or we're running out moves, or the closed loop controller is waiting
  768. static bool busy() {
  769. return (has_blocks_queued() || cleaning_buffer_counter
  770. || TERN0(EXTERNAL_CLOSED_LOOP_CONTROLLER, CLOSED_LOOP_WAITING())
  771. );
  772. }
  773. // Block until all buffered steps are executed / cleaned
  774. static void synchronize();
  775. // Wait for moves to finish and disable all steppers
  776. static void finish_and_disable();
  777. // Periodic handler to manage the cleaning buffer counter
  778. // Called from the Temperature ISR at ~1kHz
  779. static void isr() { if (cleaning_buffer_counter) --cleaning_buffer_counter; }
  780. /**
  781. * Does the buffer have any blocks queued?
  782. */
  783. FORCE_INLINE static bool has_blocks_queued() { return (block_buffer_head != block_buffer_tail); }
  784. /**
  785. * Get the current block for processing
  786. * and mark the block as busy.
  787. * Return nullptr if the buffer is empty
  788. * or if there is a first-block delay.
  789. *
  790. * WARNING: Called from Stepper ISR context!
  791. */
  792. static block_t* get_current_block();
  793. /**
  794. * "Release" the current block so its slot can be reused.
  795. * Called when the current block is no longer needed.
  796. */
  797. FORCE_INLINE static void release_current_block() {
  798. if (has_blocks_queued())
  799. block_buffer_tail = next_block_index(block_buffer_tail);
  800. }
  801. #if HAS_WIRED_LCD
  802. static uint16_t block_buffer_runtime();
  803. static void clear_block_buffer_runtime();
  804. #endif
  805. #if ENABLED(AUTOTEMP)
  806. static celsius_t autotemp_min, autotemp_max;
  807. static float autotemp_factor;
  808. static bool autotemp_enabled;
  809. static void autotemp_update();
  810. static void autotemp_M104_M109();
  811. static void autotemp_task();
  812. #endif
  813. #if HAS_LINEAR_E_JERK
  814. FORCE_INLINE static void recalculate_max_e_jerk() {
  815. const float prop = junction_deviation_mm * SQRT(0.5) / (1.0f - SQRT(0.5));
  816. EXTRUDER_LOOP()
  817. max_e_jerk[E_INDEX_N(e)] = SQRT(prop * settings.max_acceleration_mm_per_s2[E_INDEX_N(e)]);
  818. }
  819. #endif
  820. private:
  821. #if ENABLED(AUTOTEMP)
  822. #if ENABLED(AUTOTEMP_PROPORTIONAL)
  823. static void _autotemp_update_from_hotend();
  824. #else
  825. static void _autotemp_update_from_hotend() {}
  826. #endif
  827. #endif
  828. /**
  829. * Get the index of the next / previous block in the ring buffer
  830. */
  831. static constexpr uint8_t next_block_index(const uint8_t block_index) { return BLOCK_MOD(block_index + 1); }
  832. static constexpr uint8_t prev_block_index(const uint8_t block_index) { return BLOCK_MOD(block_index - 1); }
  833. /**
  834. * Calculate the maximum allowable speed squared at this point, in order
  835. * to reach 'target_velocity_sqr' using 'acceleration' within a given
  836. * 'distance'.
  837. */
  838. static float max_allowable_speed_sqr(const_float_t accel, const_float_t target_velocity_sqr, const_float_t distance) {
  839. return target_velocity_sqr - 2 * accel * distance;
  840. }
  841. #if EITHER(S_CURVE_ACCELERATION, LIN_ADVANCE)
  842. /**
  843. * Calculate the speed reached given initial speed, acceleration and distance
  844. */
  845. static float final_speed(const_float_t initial_velocity, const_float_t accel, const_float_t distance) {
  846. return SQRT(sq(initial_velocity) + 2 * accel * distance);
  847. }
  848. #endif
  849. static void calculate_trapezoid_for_block(block_t * const block, const_float_t entry_factor, const_float_t exit_factor);
  850. static void reverse_pass_kernel(block_t * const current, const block_t * const next OPTARG(ARC_SUPPORT, const_float_t safe_exit_speed_sqr));
  851. static void forward_pass_kernel(const block_t * const previous, block_t * const current, uint8_t block_index);
  852. static void reverse_pass(TERN_(ARC_SUPPORT, const_float_t safe_exit_speed_sqr));
  853. static void forward_pass();
  854. static void recalculate_trapezoids(TERN_(ARC_SUPPORT, const_float_t safe_exit_speed_sqr));
  855. static void recalculate(TERN_(ARC_SUPPORT, const_float_t safe_exit_speed_sqr));
  856. #if HAS_JUNCTION_DEVIATION
  857. FORCE_INLINE static void normalize_junction_vector(xyze_float_t &vector) {
  858. float magnitude_sq = 0;
  859. LOOP_LOGICAL_AXES(idx) if (vector[idx]) magnitude_sq += sq(vector[idx]);
  860. vector *= RSQRT(magnitude_sq);
  861. }
  862. FORCE_INLINE static float limit_value_by_axis_maximum(const_float_t max_value, xyze_float_t &unit_vec) {
  863. float limit_value = max_value;
  864. LOOP_LOGICAL_AXES(idx) {
  865. if (unit_vec[idx]) {
  866. if (limit_value * ABS(unit_vec[idx]) > settings.max_acceleration_mm_per_s2[idx])
  867. limit_value = ABS(settings.max_acceleration_mm_per_s2[idx] / unit_vec[idx]);
  868. }
  869. }
  870. return limit_value;
  871. }
  872. #endif // HAS_JUNCTION_DEVIATION
  873. };
  874. #define PLANNER_XY_FEEDRATE() _MIN(planner.settings.max_feedrate_mm_s[X_AXIS], planner.settings.max_feedrate_mm_s[Y_AXIS])
  875. extern Planner planner;