My Marlin configs for Fabrikator Mini and CTC i3 Pro B
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

planner.cpp 115KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (C) 2019 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.cpp
  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. * The ring buffer implementation gleaned from the wiring_serial library by David A. Mellis.
  31. *
  32. *
  33. * Reasoning behind the mathematics in this module (in the key of 'Mathematica'):
  34. *
  35. * s == speed, a == acceleration, t == time, d == distance
  36. *
  37. * Basic definitions:
  38. * Speed[s_, a_, t_] := s + (a*t)
  39. * Travel[s_, a_, t_] := Integrate[Speed[s, a, t], t]
  40. *
  41. * Distance to reach a specific speed with a constant acceleration:
  42. * Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, d, t]
  43. * d -> (m^2 - s^2)/(2 a) --> estimate_acceleration_distance()
  44. *
  45. * Speed after a given distance of travel with constant acceleration:
  46. * Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, m, t]
  47. * m -> Sqrt[2 a d + s^2]
  48. *
  49. * DestinationSpeed[s_, a_, d_] := Sqrt[2 a d + s^2]
  50. *
  51. * When to start braking (di) to reach a specified destination speed (s2) after accelerating
  52. * from initial speed s1 without ever stopping at a plateau:
  53. * Solve[{DestinationSpeed[s1, a, di] == DestinationSpeed[s2, a, d - di]}, di]
  54. * di -> (2 a d - s1^2 + s2^2)/(4 a) --> intersection_distance()
  55. *
  56. * IntersectionDistance[s1_, s2_, a_, d_] := (2 a d - s1^2 + s2^2)/(4 a)
  57. *
  58. * --
  59. *
  60. * The fast inverse function needed for Bézier interpolation for AVR
  61. * was designed, written and tested by Eduardo José Tagle on April/2018
  62. */
  63. #include "planner.h"
  64. #include "stepper.h"
  65. #include "motion.h"
  66. #include "temperature.h"
  67. #include "../lcd/ultralcd.h"
  68. #include "../core/language.h"
  69. #include "../gcode/parser.h"
  70. #include "../Marlin.h"
  71. #if HAS_LEVELING
  72. #include "../feature/bedlevel/bedlevel.h"
  73. #endif
  74. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  75. #include "../feature/filwidth.h"
  76. #endif
  77. #if ENABLED(BARICUDA)
  78. #include "../feature/baricuda.h"
  79. #endif
  80. #if ENABLED(MIXING_EXTRUDER)
  81. #include "../feature/mixing.h"
  82. #endif
  83. #if ENABLED(AUTO_POWER_CONTROL)
  84. #include "../feature/power.h"
  85. #endif
  86. // Delay for delivery of first block to the stepper ISR, if the queue contains 2 or
  87. // fewer movements. The delay is measured in milliseconds, and must be less than 250ms
  88. #define BLOCK_DELAY_FOR_1ST_MOVE 100
  89. Planner planner;
  90. // public:
  91. /**
  92. * A ring buffer of moves described in steps
  93. */
  94. block_t Planner::block_buffer[BLOCK_BUFFER_SIZE];
  95. volatile uint8_t Planner::block_buffer_head, // Index of the next block to be pushed
  96. Planner::block_buffer_nonbusy, // Index of the first non-busy block
  97. Planner::block_buffer_planned, // Index of the optimally planned block
  98. Planner::block_buffer_tail; // Index of the busy block, if any
  99. uint16_t Planner::cleaning_buffer_counter; // A counter to disable queuing of blocks
  100. uint8_t Planner::delay_before_delivering; // This counter delays delivery of blocks when queue becomes empty to allow the opportunity of merging blocks
  101. planner_settings_t Planner::settings; // Initialized by settings.load()
  102. uint32_t Planner::max_acceleration_steps_per_s2[XYZE_N]; // (steps/s^2) Derived from mm_per_s2
  103. float Planner::steps_to_mm[XYZE_N]; // (mm) Millimeters per step
  104. #if ENABLED(JUNCTION_DEVIATION)
  105. float Planner::junction_deviation_mm; // (mm) M205 J
  106. #if ENABLED(LIN_ADVANCE)
  107. #if ENABLED(DISTINCT_E_FACTORS)
  108. float Planner::max_e_jerk[EXTRUDERS]; // Calculated from junction_deviation_mm
  109. #else
  110. float Planner::max_e_jerk;
  111. #endif
  112. #endif
  113. #endif
  114. #if HAS_CLASSIC_JERK
  115. #if ENABLED(JUNCTION_DEVIATION) && ENABLED(LIN_ADVANCE)
  116. float Planner::max_jerk[XYZ]; // (mm/s^2) M205 XYZ - The largest speed change requiring no acceleration.
  117. #else
  118. float Planner::max_jerk[XYZE]; // (mm/s^2) M205 XYZE - The largest speed change requiring no acceleration.
  119. #endif
  120. #endif
  121. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  122. bool Planner::abort_on_endstop_hit = false;
  123. #endif
  124. #if ENABLED(DISTINCT_E_FACTORS)
  125. uint8_t Planner::last_extruder = 0; // Respond to extruder change
  126. #endif
  127. int16_t Planner::flow_percentage[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(100); // Extrusion factor for each extruder
  128. float Planner::e_factor[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(1.0f); // The flow percentage and volumetric multiplier combine to scale E movement
  129. #if DISABLED(NO_VOLUMETRICS)
  130. float Planner::filament_size[EXTRUDERS], // diameter of filament (in millimeters), typically around 1.75 or 2.85, 0 disables the volumetric calculations for the extruder
  131. Planner::volumetric_area_nominal = CIRCLE_AREA(float(DEFAULT_NOMINAL_FILAMENT_DIA) * 0.5f), // Nominal cross-sectional area
  132. Planner::volumetric_multiplier[EXTRUDERS]; // Reciprocal of cross-sectional area of filament (in mm^2). Pre-calculated to reduce computation in the planner
  133. #endif
  134. #if HAS_LEVELING
  135. bool Planner::leveling_active = false; // Flag that auto bed leveling is enabled
  136. #if ABL_PLANAR
  137. matrix_3x3 Planner::bed_level_matrix; // Transform to compensate for bed level
  138. #endif
  139. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  140. float Planner::z_fade_height, // Initialized by settings.load()
  141. Planner::inverse_z_fade_height,
  142. Planner::last_fade_z;
  143. #endif
  144. #else
  145. constexpr bool Planner::leveling_active;
  146. #endif
  147. skew_factor_t Planner::skew_factor; // Initialized by settings.load()
  148. #if ENABLED(AUTOTEMP)
  149. float Planner::autotemp_max = 250,
  150. Planner::autotemp_min = 210,
  151. Planner::autotemp_factor = 0.1f;
  152. bool Planner::autotemp_enabled = false;
  153. #endif
  154. // private:
  155. int32_t Planner::position[NUM_AXIS] = { 0 };
  156. uint32_t Planner::cutoff_long;
  157. float Planner::previous_speed[NUM_AXIS],
  158. Planner::previous_nominal_speed_sqr;
  159. #if ENABLED(DISABLE_INACTIVE_EXTRUDER)
  160. uint8_t Planner::g_uc_extruder_last_move[EXTRUDERS] = { 0 };
  161. #endif
  162. #ifdef XY_FREQUENCY_LIMIT
  163. // Old direction bits. Used for speed calculations
  164. unsigned char Planner::old_direction_bits = 0;
  165. // Segment times (in µs). Used for speed calculations
  166. uint32_t Planner::axis_segment_time_us[2][3] = { { MAX_FREQ_TIME_US + 1, 0, 0 }, { MAX_FREQ_TIME_US + 1, 0, 0 } };
  167. #endif
  168. #if ENABLED(LIN_ADVANCE)
  169. float Planner::extruder_advance_K[EXTRUDERS]; // Initialized by settings.load()
  170. #endif
  171. #if HAS_POSITION_FLOAT
  172. float Planner::position_float[XYZE]; // Needed for accurate maths. Steps cannot be used!
  173. #endif
  174. #if IS_KINEMATIC
  175. float Planner::position_cart[XYZE];
  176. #endif
  177. #if ENABLED(ULTRA_LCD)
  178. volatile uint32_t Planner::block_buffer_runtime_us = 0;
  179. #endif
  180. /**
  181. * Class and Instance Methods
  182. */
  183. Planner::Planner() { init(); }
  184. void Planner::init() {
  185. ZERO(position);
  186. #if HAS_POSITION_FLOAT
  187. ZERO(position_float);
  188. #endif
  189. #if IS_KINEMATIC
  190. ZERO(position_cart);
  191. #endif
  192. ZERO(previous_speed);
  193. previous_nominal_speed_sqr = 0;
  194. #if ABL_PLANAR
  195. bed_level_matrix.set_to_identity();
  196. #endif
  197. clear_block_buffer();
  198. delay_before_delivering = 0;
  199. }
  200. #if ENABLED(S_CURVE_ACCELERATION)
  201. #ifdef __AVR__
  202. /**
  203. * This routine returns 0x1000000 / d, getting the inverse as fast as possible.
  204. * A fast-converging iterative Newton-Raphson method can reach full precision in
  205. * just 1 iteration, and takes 211 cycles (worst case; the mean case is less, up
  206. * to 30 cycles for small divisors), instead of the 500 cycles a normal division
  207. * would take.
  208. *
  209. * Inspired by the following page:
  210. * https://stackoverflow.com/questions/27801397/newton-raphson-division-with-big-integers
  211. *
  212. * Suppose we want to calculate floor(2 ^ k / B) where B is a positive integer
  213. * Then, B must be <= 2^k, otherwise, the quotient is 0.
  214. *
  215. * The Newton - Raphson iteration for x = B / 2 ^ k yields:
  216. * q[n + 1] = q[n] * (2 - q[n] * B / 2 ^ k)
  217. *
  218. * This can be rearranged to:
  219. * q[n + 1] = q[n] * (2 ^ (k + 1) - q[n] * B) >> k
  220. *
  221. * Each iteration requires only integer multiplications and bit shifts.
  222. * It doesn't necessarily converge to floor(2 ^ k / B) but in the worst case
  223. * it eventually alternates between floor(2 ^ k / B) and ceil(2 ^ k / B).
  224. * So it checks for this case and extracts floor(2 ^ k / B).
  225. *
  226. * A simple but important optimization for this approach is to truncate
  227. * multiplications (i.e., calculate only the higher bits of the product) in the
  228. * early iterations of the Newton - Raphson method. This is done so the results
  229. * of the early iterations are far from the quotient. Then it doesn't matter if
  230. * they are done inaccurately.
  231. * It's important to pick a good starting value for x. Knowing how many
  232. * digits the divisor has, it can be estimated:
  233. *
  234. * 2^k / x = 2 ^ log2(2^k / x)
  235. * 2^k / x = 2 ^(log2(2^k)-log2(x))
  236. * 2^k / x = 2 ^(k*log2(2)-log2(x))
  237. * 2^k / x = 2 ^ (k-log2(x))
  238. * 2^k / x >= 2 ^ (k-floor(log2(x)))
  239. * floor(log2(x)) is simply the index of the most significant bit set.
  240. *
  241. * If this estimation can be improved even further the number of iterations can be
  242. * reduced a lot, saving valuable execution time.
  243. * The paper "Software Integer Division" by Thomas L.Rodeheffer, Microsoft
  244. * Research, Silicon Valley,August 26, 2008, available at
  245. * https://www.microsoft.com/en-us/research/wp-content/uploads/2008/08/tr-2008-141.pdf
  246. * suggests, for its integer division algorithm, using a table to supply the first
  247. * 8 bits of precision, then, due to the quadratic convergence nature of the
  248. * Newton-Raphon iteration, just 2 iterations should be enough to get maximum
  249. * precision of the division.
  250. * By precomputing values of inverses for small denominator values, just one
  251. * Newton-Raphson iteration is enough to reach full precision.
  252. * This code uses the top 9 bits of the denominator as index.
  253. *
  254. * The AVR assembly function implements this C code using the data below:
  255. *
  256. * // For small divisors, it is best to directly retrieve the results
  257. * if (d <= 110) return pgm_read_dword(&small_inv_tab[d]);
  258. *
  259. * // Compute initial estimation of 0x1000000/x -
  260. * // Get most significant bit set on divider
  261. * uint8_t idx = 0;
  262. * uint32_t nr = d;
  263. * if (!(nr & 0xFF0000)) {
  264. * nr <<= 8; idx += 8;
  265. * if (!(nr & 0xFF0000)) { nr <<= 8; idx += 8; }
  266. * }
  267. * if (!(nr & 0xF00000)) { nr <<= 4; idx += 4; }
  268. * if (!(nr & 0xC00000)) { nr <<= 2; idx += 2; }
  269. * if (!(nr & 0x800000)) { nr <<= 1; idx += 1; }
  270. *
  271. * // Isolate top 9 bits of the denominator, to be used as index into the initial estimation table
  272. * uint32_t tidx = nr >> 15, // top 9 bits. bit8 is always set
  273. * ie = inv_tab[tidx & 0xFF] + 256, // Get the table value. bit9 is always set
  274. * x = idx <= 8 ? (ie >> (8 - idx)) : (ie << (idx - 8)); // Position the estimation at the proper place
  275. *
  276. * x = uint32_t((x * uint64_t(_BV(25) - x * d)) >> 24); // Refine estimation by newton-raphson. 1 iteration is enough
  277. * const uint32_t r = _BV(24) - x * d; // Estimate remainder
  278. * if (r >= d) x++; // Check whether to adjust result
  279. * return uint32_t(x); // x holds the proper estimation
  280. *
  281. */
  282. static uint32_t get_period_inverse(uint32_t d) {
  283. static const uint8_t inv_tab[256] PROGMEM = {
  284. 255,253,252,250,248,246,244,242,240,238,236,234,233,231,229,227,
  285. 225,224,222,220,218,217,215,213,212,210,208,207,205,203,202,200,
  286. 199,197,195,194,192,191,189,188,186,185,183,182,180,179,178,176,
  287. 175,173,172,170,169,168,166,165,164,162,161,160,158,157,156,154,
  288. 153,152,151,149,148,147,146,144,143,142,141,139,138,137,136,135,
  289. 134,132,131,130,129,128,127,126,125,123,122,121,120,119,118,117,
  290. 116,115,114,113,112,111,110,109,108,107,106,105,104,103,102,101,
  291. 100,99,98,97,96,95,94,93,92,91,90,89,88,88,87,86,
  292. 85,84,83,82,81,80,80,79,78,77,76,75,74,74,73,72,
  293. 71,70,70,69,68,67,66,66,65,64,63,62,62,61,60,59,
  294. 59,58,57,56,56,55,54,53,53,52,51,50,50,49,48,48,
  295. 47,46,46,45,44,43,43,42,41,41,40,39,39,38,37,37,
  296. 36,35,35,34,33,33,32,32,31,30,30,29,28,28,27,27,
  297. 26,25,25,24,24,23,22,22,21,21,20,19,19,18,18,17,
  298. 17,16,15,15,14,14,13,13,12,12,11,10,10,9,9,8,
  299. 8,7,7,6,6,5,5,4,4,3,3,2,2,1,0,0
  300. };
  301. // For small denominators, it is cheaper to directly store the result.
  302. // For bigger ones, just ONE Newton-Raphson iteration is enough to get
  303. // maximum precision we need
  304. static const uint32_t small_inv_tab[111] PROGMEM = {
  305. 16777216,16777216,8388608,5592405,4194304,3355443,2796202,2396745,2097152,1864135,1677721,1525201,1398101,1290555,1198372,1118481,
  306. 1048576,986895,932067,883011,838860,798915,762600,729444,699050,671088,645277,621378,599186,578524,559240,541200,
  307. 524288,508400,493447,479349,466033,453438,441505,430185,419430,409200,399457,390167,381300,372827,364722,356962,
  308. 349525,342392,335544,328965,322638,316551,310689,305040,299593,294337,289262,284359,279620,275036,270600,266305,
  309. 262144,258111,254200,250406,246723,243148,239674,236298,233016,229824,226719,223696,220752,217885,215092,212369,
  310. 209715,207126,204600,202135,199728,197379,195083,192841,190650,188508,186413,184365,182361,180400,178481,176602,
  311. 174762,172960,171196,169466,167772,166111,164482,162885,161319,159783,158275,156796,155344,153919,152520
  312. };
  313. // For small divisors, it is best to directly retrieve the results
  314. if (d <= 110) return pgm_read_dword(&small_inv_tab[d]);
  315. uint8_t r8 = d & 0xFF,
  316. r9 = (d >> 8) & 0xFF,
  317. r10 = (d >> 16) & 0xFF,
  318. r2,r3,r4,r5,r6,r7,r11,r12,r13,r14,r15,r16,r17,r18;
  319. const uint8_t* ptab = inv_tab;
  320. __asm__ __volatile__(
  321. // %8:%7:%6 = interval
  322. // r31:r30: MUST be those registers, and they must point to the inv_tab
  323. A("clr %13") // %13 = 0
  324. // Now we must compute
  325. // result = 0xFFFFFF / d
  326. // %8:%7:%6 = interval
  327. // %16:%15:%14 = nr
  328. // %13 = 0
  329. // A plain division of 24x24 bits should take 388 cycles to complete. We will
  330. // use Newton-Raphson for the calculation, and will strive to get way less cycles
  331. // for the same result - Using C division, it takes 500cycles to complete .
  332. A("clr %3") // idx = 0
  333. A("mov %14,%6")
  334. A("mov %15,%7")
  335. A("mov %16,%8") // nr = interval
  336. A("tst %16") // nr & 0xFF0000 == 0 ?
  337. A("brne 2f") // No, skip this
  338. A("mov %16,%15")
  339. A("mov %15,%14") // nr <<= 8, %14 not needed
  340. A("subi %3,-8") // idx += 8
  341. A("tst %16") // nr & 0xFF0000 == 0 ?
  342. A("brne 2f") // No, skip this
  343. A("mov %16,%15") // nr <<= 8, %14 not needed
  344. A("clr %15") // We clear %14
  345. A("subi %3,-8") // idx += 8
  346. // here %16 != 0 and %16:%15 contains at least 9 MSBits, or both %16:%15 are 0
  347. L("2")
  348. A("cpi %16,0x10") // (nr & 0xF00000) == 0 ?
  349. A("brcc 3f") // No, skip this
  350. A("swap %15") // Swap nibbles
  351. A("swap %16") // Swap nibbles. Low nibble is 0
  352. A("mov %14, %15")
  353. A("andi %14,0x0F") // Isolate low nibble
  354. A("andi %15,0xF0") // Keep proper nibble in %15
  355. A("or %16, %14") // %16:%15 <<= 4
  356. A("subi %3,-4") // idx += 4
  357. L("3")
  358. A("cpi %16,0x40") // (nr & 0xC00000) == 0 ?
  359. A("brcc 4f") // No, skip this
  360. A("add %15,%15")
  361. A("adc %16,%16")
  362. A("add %15,%15")
  363. A("adc %16,%16") // %16:%15 <<= 2
  364. A("subi %3,-2") // idx += 2
  365. L("4")
  366. A("cpi %16,0x80") // (nr & 0x800000) == 0 ?
  367. A("brcc 5f") // No, skip this
  368. A("add %15,%15")
  369. A("adc %16,%16") // %16:%15 <<= 1
  370. A("inc %3") // idx += 1
  371. // Now %16:%15 contains its MSBit set to 1, or %16:%15 is == 0. We are now absolutely sure
  372. // we have at least 9 MSBits available to enter the initial estimation table
  373. L("5")
  374. A("add %15,%15")
  375. A("adc %16,%16") // %16:%15 = tidx = (nr <<= 1), we lose the top MSBit (always set to 1, %16 is the index into the inverse table)
  376. A("add r30,%16") // Only use top 8 bits
  377. A("adc r31,%13") // r31:r30 = inv_tab + (tidx)
  378. A("lpm %14, Z") // %14 = inv_tab[tidx]
  379. A("ldi %15, 1") // %15 = 1 %15:%14 = inv_tab[tidx] + 256
  380. // We must scale the approximation to the proper place
  381. A("clr %16") // %16 will always be 0 here
  382. A("subi %3,8") // idx == 8 ?
  383. A("breq 6f") // yes, no need to scale
  384. A("brcs 7f") // If C=1, means idx < 8, result was negative!
  385. // idx > 8, now %3 = idx - 8. We must perform a left shift. idx range:[1-8]
  386. A("sbrs %3,0") // shift by 1bit position?
  387. A("rjmp 8f") // No
  388. A("add %14,%14")
  389. A("adc %15,%15") // %15:16 <<= 1
  390. L("8")
  391. A("sbrs %3,1") // shift by 2bit position?
  392. A("rjmp 9f") // No
  393. A("add %14,%14")
  394. A("adc %15,%15")
  395. A("add %14,%14")
  396. A("adc %15,%15") // %15:16 <<= 1
  397. L("9")
  398. A("sbrs %3,2") // shift by 4bits position?
  399. A("rjmp 16f") // No
  400. A("swap %15") // Swap nibbles. lo nibble of %15 will always be 0
  401. A("swap %14") // Swap nibbles
  402. A("mov %12,%14")
  403. A("andi %12,0x0F") // isolate low nibble
  404. A("andi %14,0xF0") // and clear it
  405. A("or %15,%12") // %15:%16 <<= 4
  406. L("16")
  407. A("sbrs %3,3") // shift by 8bits position?
  408. A("rjmp 6f") // No, we are done
  409. A("mov %16,%15")
  410. A("mov %15,%14")
  411. A("clr %14")
  412. A("jmp 6f")
  413. // idx < 8, now %3 = idx - 8. Get the count of bits
  414. L("7")
  415. A("neg %3") // %3 = -idx = count of bits to move right. idx range:[1...8]
  416. A("sbrs %3,0") // shift by 1 bit position ?
  417. A("rjmp 10f") // No, skip it
  418. A("asr %15") // (bit7 is always 0 here)
  419. A("ror %14")
  420. L("10")
  421. A("sbrs %3,1") // shift by 2 bit position ?
  422. A("rjmp 11f") // No, skip it
  423. A("asr %15") // (bit7 is always 0 here)
  424. A("ror %14")
  425. A("asr %15") // (bit7 is always 0 here)
  426. A("ror %14")
  427. L("11")
  428. A("sbrs %3,2") // shift by 4 bit position ?
  429. A("rjmp 12f") // No, skip it
  430. A("swap %15") // Swap nibbles
  431. A("andi %14, 0xF0") // Lose the lowest nibble
  432. A("swap %14") // Swap nibbles. Upper nibble is 0
  433. A("or %14,%15") // Pass nibble from upper byte
  434. A("andi %15, 0x0F") // And get rid of that nibble
  435. L("12")
  436. A("sbrs %3,3") // shift by 8 bit position ?
  437. A("rjmp 6f") // No, skip it
  438. A("mov %14,%15")
  439. A("clr %15")
  440. L("6") // %16:%15:%14 = initial estimation of 0x1000000 / d
  441. // Now, we must refine the estimation present on %16:%15:%14 using 1 iteration
  442. // of Newton-Raphson. As it has a quadratic convergence, 1 iteration is enough
  443. // to get more than 18bits of precision (the initial table lookup gives 9 bits of
  444. // precision to start from). 18bits of precision is all what is needed here for result
  445. // %8:%7:%6 = d = interval
  446. // %16:%15:%14 = x = initial estimation of 0x1000000 / d
  447. // %13 = 0
  448. // %3:%2:%1:%0 = working accumulator
  449. // Compute 1<<25 - x*d. Result should never exceed 25 bits and should always be positive
  450. A("clr %0")
  451. A("clr %1")
  452. A("clr %2")
  453. A("ldi %3,2") // %3:%2:%1:%0 = 0x2000000
  454. A("mul %6,%14") // r1:r0 = LO(d) * LO(x)
  455. A("sub %0,r0")
  456. A("sbc %1,r1")
  457. A("sbc %2,%13")
  458. A("sbc %3,%13") // %3:%2:%1:%0 -= LO(d) * LO(x)
  459. A("mul %7,%14") // r1:r0 = MI(d) * LO(x)
  460. A("sub %1,r0")
  461. A("sbc %2,r1" )
  462. A("sbc %3,%13") // %3:%2:%1:%0 -= MI(d) * LO(x) << 8
  463. A("mul %8,%14") // r1:r0 = HI(d) * LO(x)
  464. A("sub %2,r0")
  465. A("sbc %3,r1") // %3:%2:%1:%0 -= MIL(d) * LO(x) << 16
  466. A("mul %6,%15") // r1:r0 = LO(d) * MI(x)
  467. A("sub %1,r0")
  468. A("sbc %2,r1")
  469. A("sbc %3,%13") // %3:%2:%1:%0 -= LO(d) * MI(x) << 8
  470. A("mul %7,%15") // r1:r0 = MI(d) * MI(x)
  471. A("sub %2,r0")
  472. A("sbc %3,r1") // %3:%2:%1:%0 -= MI(d) * MI(x) << 16
  473. A("mul %8,%15") // r1:r0 = HI(d) * MI(x)
  474. A("sub %3,r0") // %3:%2:%1:%0 -= MIL(d) * MI(x) << 24
  475. A("mul %6,%16") // r1:r0 = LO(d) * HI(x)
  476. A("sub %2,r0")
  477. A("sbc %3,r1") // %3:%2:%1:%0 -= LO(d) * HI(x) << 16
  478. A("mul %7,%16") // r1:r0 = MI(d) * HI(x)
  479. A("sub %3,r0") // %3:%2:%1:%0 -= MI(d) * HI(x) << 24
  480. // %3:%2:%1:%0 = (1<<25) - x*d [169]
  481. // We need to multiply that result by x, and we are only interested in the top 24bits of that multiply
  482. // %16:%15:%14 = x = initial estimation of 0x1000000 / d
  483. // %3:%2:%1:%0 = (1<<25) - x*d = acc
  484. // %13 = 0
  485. // result = %11:%10:%9:%5:%4
  486. A("mul %14,%0") // r1:r0 = LO(x) * LO(acc)
  487. A("mov %4,r1")
  488. A("clr %5")
  489. A("clr %9")
  490. A("clr %10")
  491. A("clr %11") // %11:%10:%9:%5:%4 = LO(x) * LO(acc) >> 8
  492. A("mul %15,%0") // r1:r0 = MI(x) * LO(acc)
  493. A("add %4,r0")
  494. A("adc %5,r1")
  495. A("adc %9,%13")
  496. A("adc %10,%13")
  497. A("adc %11,%13") // %11:%10:%9:%5:%4 += MI(x) * LO(acc)
  498. A("mul %16,%0") // r1:r0 = HI(x) * LO(acc)
  499. A("add %5,r0")
  500. A("adc %9,r1")
  501. A("adc %10,%13")
  502. A("adc %11,%13") // %11:%10:%9:%5:%4 += MI(x) * LO(acc) << 8
  503. A("mul %14,%1") // r1:r0 = LO(x) * MIL(acc)
  504. A("add %4,r0")
  505. A("adc %5,r1")
  506. A("adc %9,%13")
  507. A("adc %10,%13")
  508. A("adc %11,%13") // %11:%10:%9:%5:%4 = LO(x) * MIL(acc)
  509. A("mul %15,%1") // r1:r0 = MI(x) * MIL(acc)
  510. A("add %5,r0")
  511. A("adc %9,r1")
  512. A("adc %10,%13")
  513. A("adc %11,%13") // %11:%10:%9:%5:%4 += MI(x) * MIL(acc) << 8
  514. A("mul %16,%1") // r1:r0 = HI(x) * MIL(acc)
  515. A("add %9,r0")
  516. A("adc %10,r1")
  517. A("adc %11,%13") // %11:%10:%9:%5:%4 += MI(x) * MIL(acc) << 16
  518. A("mul %14,%2") // r1:r0 = LO(x) * MIH(acc)
  519. A("add %5,r0")
  520. A("adc %9,r1")
  521. A("adc %10,%13")
  522. A("adc %11,%13") // %11:%10:%9:%5:%4 = LO(x) * MIH(acc) << 8
  523. A("mul %15,%2") // r1:r0 = MI(x) * MIH(acc)
  524. A("add %9,r0")
  525. A("adc %10,r1")
  526. A("adc %11,%13") // %11:%10:%9:%5:%4 += MI(x) * MIH(acc) << 16
  527. A("mul %16,%2") // r1:r0 = HI(x) * MIH(acc)
  528. A("add %10,r0")
  529. A("adc %11,r1") // %11:%10:%9:%5:%4 += MI(x) * MIH(acc) << 24
  530. A("mul %14,%3") // r1:r0 = LO(x) * HI(acc)
  531. A("add %9,r0")
  532. A("adc %10,r1")
  533. A("adc %11,%13") // %11:%10:%9:%5:%4 = LO(x) * HI(acc) << 16
  534. A("mul %15,%3") // r1:r0 = MI(x) * HI(acc)
  535. A("add %10,r0")
  536. A("adc %11,r1") // %11:%10:%9:%5:%4 += MI(x) * HI(acc) << 24
  537. A("mul %16,%3") // r1:r0 = HI(x) * HI(acc)
  538. A("add %11,r0") // %11:%10:%9:%5:%4 += MI(x) * HI(acc) << 32
  539. // At this point, %11:%10:%9 contains the new estimation of x.
  540. // Finally, we must correct the result. Estimate remainder as
  541. // (1<<24) - x*d
  542. // %11:%10:%9 = x
  543. // %8:%7:%6 = d = interval" "\n\t"
  544. A("ldi %3,1")
  545. A("clr %2")
  546. A("clr %1")
  547. A("clr %0") // %3:%2:%1:%0 = 0x1000000
  548. A("mul %6,%9") // r1:r0 = LO(d) * LO(x)
  549. A("sub %0,r0")
  550. A("sbc %1,r1")
  551. A("sbc %2,%13")
  552. A("sbc %3,%13") // %3:%2:%1:%0 -= LO(d) * LO(x)
  553. A("mul %7,%9") // r1:r0 = MI(d) * LO(x)
  554. A("sub %1,r0")
  555. A("sbc %2,r1")
  556. A("sbc %3,%13") // %3:%2:%1:%0 -= MI(d) * LO(x) << 8
  557. A("mul %8,%9") // r1:r0 = HI(d) * LO(x)
  558. A("sub %2,r0")
  559. A("sbc %3,r1") // %3:%2:%1:%0 -= MIL(d) * LO(x) << 16
  560. A("mul %6,%10") // r1:r0 = LO(d) * MI(x)
  561. A("sub %1,r0")
  562. A("sbc %2,r1")
  563. A("sbc %3,%13") // %3:%2:%1:%0 -= LO(d) * MI(x) << 8
  564. A("mul %7,%10") // r1:r0 = MI(d) * MI(x)
  565. A("sub %2,r0")
  566. A("sbc %3,r1") // %3:%2:%1:%0 -= MI(d) * MI(x) << 16
  567. A("mul %8,%10") // r1:r0 = HI(d) * MI(x)
  568. A("sub %3,r0") // %3:%2:%1:%0 -= MIL(d) * MI(x) << 24
  569. A("mul %6,%11") // r1:r0 = LO(d) * HI(x)
  570. A("sub %2,r0")
  571. A("sbc %3,r1") // %3:%2:%1:%0 -= LO(d) * HI(x) << 16
  572. A("mul %7,%11") // r1:r0 = MI(d) * HI(x)
  573. A("sub %3,r0") // %3:%2:%1:%0 -= MI(d) * HI(x) << 24
  574. // %3:%2:%1:%0 = r = (1<<24) - x*d
  575. // %8:%7:%6 = d = interval
  576. // Perform the final correction
  577. A("sub %0,%6")
  578. A("sbc %1,%7")
  579. A("sbc %2,%8") // r -= d
  580. A("brcs 14f") // if ( r >= d)
  581. // %11:%10:%9 = x
  582. A("ldi %3,1")
  583. A("add %9,%3")
  584. A("adc %10,%13")
  585. A("adc %11,%13") // x++
  586. L("14")
  587. // Estimation is done. %11:%10:%9 = x
  588. A("clr __zero_reg__") // Make C runtime happy
  589. // [211 cycles total]
  590. : "=r" (r2),
  591. "=r" (r3),
  592. "=r" (r4),
  593. "=d" (r5),
  594. "=r" (r6),
  595. "=r" (r7),
  596. "+r" (r8),
  597. "+r" (r9),
  598. "+r" (r10),
  599. "=d" (r11),
  600. "=r" (r12),
  601. "=r" (r13),
  602. "=d" (r14),
  603. "=d" (r15),
  604. "=d" (r16),
  605. "=d" (r17),
  606. "=d" (r18),
  607. "+z" (ptab)
  608. :
  609. : "r0", "r1", "cc"
  610. );
  611. // Return the result
  612. return r11 | (uint16_t(r12) << 8) | (uint32_t(r13) << 16);
  613. }
  614. #else
  615. // All other 32-bit MPUs can easily do inverse using hardware division,
  616. // so we don't need to reduce precision or to use assembly language at all.
  617. // This routine, for all other archs, returns 0x100000000 / d ~= 0xFFFFFFFF / d
  618. static FORCE_INLINE uint32_t get_period_inverse(const uint32_t d) {
  619. return d ? 0xFFFFFFFF / d : 0xFFFFFFFF;
  620. }
  621. #endif
  622. #endif
  623. #define MINIMAL_STEP_RATE 120
  624. /**
  625. * Calculate trapezoid parameters, multiplying the entry- and exit-speeds
  626. * by the provided factors.
  627. **
  628. * ############ VERY IMPORTANT ############
  629. * NOTE that the PRECONDITION to call this function is that the block is
  630. * NOT BUSY and it is marked as RECALCULATE. That WARRANTIES the Stepper ISR
  631. * is not and will not use the block while we modify it, so it is safe to
  632. * alter its values.
  633. */
  634. void Planner::calculate_trapezoid_for_block(block_t* const block, const float &entry_factor, const float &exit_factor) {
  635. uint32_t initial_rate = CEIL(block->nominal_rate * entry_factor),
  636. final_rate = CEIL(block->nominal_rate * exit_factor); // (steps per second)
  637. // Limit minimal step rate (Otherwise the timer will overflow.)
  638. NOLESS(initial_rate, uint32_t(MINIMAL_STEP_RATE));
  639. NOLESS(final_rate, uint32_t(MINIMAL_STEP_RATE));
  640. #if ENABLED(S_CURVE_ACCELERATION)
  641. uint32_t cruise_rate = initial_rate;
  642. #endif
  643. const int32_t accel = block->acceleration_steps_per_s2;
  644. // Steps required for acceleration, deceleration to/from nominal rate
  645. uint32_t accelerate_steps = CEIL(estimate_acceleration_distance(initial_rate, block->nominal_rate, accel)),
  646. decelerate_steps = FLOOR(estimate_acceleration_distance(block->nominal_rate, final_rate, -accel));
  647. // Steps between acceleration and deceleration, if any
  648. int32_t plateau_steps = block->step_event_count - accelerate_steps - decelerate_steps;
  649. // Does accelerate_steps + decelerate_steps exceed step_event_count?
  650. // Then we can't possibly reach the nominal rate, there will be no cruising.
  651. // Use intersection_distance() to calculate accel / braking time in order to
  652. // reach the final_rate exactly at the end of this block.
  653. if (plateau_steps < 0) {
  654. const float accelerate_steps_float = CEIL(intersection_distance(initial_rate, final_rate, accel, block->step_event_count));
  655. accelerate_steps = MIN(uint32_t(MAX(accelerate_steps_float, 0)), block->step_event_count);
  656. plateau_steps = 0;
  657. #if ENABLED(S_CURVE_ACCELERATION)
  658. // We won't reach the cruising rate. Let's calculate the speed we will reach
  659. cruise_rate = final_speed(initial_rate, accel, accelerate_steps);
  660. #endif
  661. }
  662. #if ENABLED(S_CURVE_ACCELERATION)
  663. else // We have some plateau time, so the cruise rate will be the nominal rate
  664. cruise_rate = block->nominal_rate;
  665. #endif
  666. #if ENABLED(S_CURVE_ACCELERATION)
  667. // Jerk controlled speed requires to express speed versus time, NOT steps
  668. uint32_t acceleration_time = ((float)(cruise_rate - initial_rate) / accel) * (STEPPER_TIMER_RATE),
  669. deceleration_time = ((float)(cruise_rate - final_rate) / accel) * (STEPPER_TIMER_RATE);
  670. // And to offload calculations from the ISR, we also calculate the inverse of those times here
  671. uint32_t acceleration_time_inverse = get_period_inverse(acceleration_time);
  672. uint32_t deceleration_time_inverse = get_period_inverse(deceleration_time);
  673. #endif
  674. // Store new block parameters
  675. block->accelerate_until = accelerate_steps;
  676. block->decelerate_after = accelerate_steps + plateau_steps;
  677. block->initial_rate = initial_rate;
  678. #if ENABLED(S_CURVE_ACCELERATION)
  679. block->acceleration_time = acceleration_time;
  680. block->deceleration_time = deceleration_time;
  681. block->acceleration_time_inverse = acceleration_time_inverse;
  682. block->deceleration_time_inverse = deceleration_time_inverse;
  683. block->cruise_rate = cruise_rate;
  684. #endif
  685. block->final_rate = final_rate;
  686. }
  687. /* PLANNER SPEED DEFINITION
  688. +--------+ <- current->nominal_speed
  689. / \
  690. current->entry_speed -> + \
  691. | + <- next->entry_speed (aka exit speed)
  692. +-------------+
  693. time -->
  694. Recalculates the motion plan according to the following basic guidelines:
  695. 1. Go over every feasible block sequentially in reverse order and calculate the junction speeds
  696. (i.e. current->entry_speed) such that:
  697. a. No junction speed exceeds the pre-computed maximum junction speed limit or nominal speeds of
  698. neighboring blocks.
  699. b. A block entry speed cannot exceed one reverse-computed from its exit speed (next->entry_speed)
  700. with a maximum allowable deceleration over the block travel distance.
  701. c. The last (or newest appended) block is planned from a complete stop (an exit speed of zero).
  702. 2. Go over every block in chronological (forward) order and dial down junction speed values if
  703. a. The exit speed exceeds the one forward-computed from its entry speed with the maximum allowable
  704. acceleration over the block travel distance.
  705. When these stages are complete, the planner will have maximized the velocity profiles throughout the all
  706. of the planner blocks, where every block is operating at its maximum allowable acceleration limits. In
  707. other words, for all of the blocks in the planner, the plan is optimal and no further speed improvements
  708. are possible. If a new block is added to the buffer, the plan is recomputed according to the said
  709. guidelines for a new optimal plan.
  710. To increase computational efficiency of these guidelines, a set of planner block pointers have been
  711. created to indicate stop-compute points for when the planner guidelines cannot logically make any further
  712. changes or improvements to the plan when in normal operation and new blocks are streamed and added to the
  713. planner buffer. For example, if a subset of sequential blocks in the planner have been planned and are
  714. bracketed by junction velocities at their maximums (or by the first planner block as well), no new block
  715. added to the planner buffer will alter the velocity profiles within them. So we no longer have to compute
  716. them. Or, if a set of sequential blocks from the first block in the planner (or a optimal stop-compute
  717. point) are all accelerating, they are all optimal and can not be altered by a new block added to the
  718. planner buffer, as this will only further increase the plan speed to chronological blocks until a maximum
  719. junction velocity is reached. However, if the operational conditions of the plan changes from infrequently
  720. used feed holds or feedrate overrides, the stop-compute pointers will be reset and the entire plan is
  721. recomputed as stated in the general guidelines.
  722. Planner buffer index mapping:
  723. - block_buffer_tail: Points to the beginning of the planner buffer. First to be executed or being executed.
  724. - block_buffer_head: Points to the buffer block after the last block in the buffer. Used to indicate whether
  725. the buffer is full or empty. As described for standard ring buffers, this block is always empty.
  726. - block_buffer_planned: Points to the first buffer block after the last optimally planned block for normal
  727. streaming operating conditions. Use for planning optimizations by avoiding recomputing parts of the
  728. planner buffer that don't change with the addition of a new block, as describe above. In addition,
  729. this block can never be less than block_buffer_tail and will always be pushed forward and maintain
  730. this requirement when encountered by the Planner::discard_current_block() routine during a cycle.
  731. NOTE: Since the planner only computes on what's in the planner buffer, some motions with lots of short
  732. line segments, like G2/3 arcs or complex curves, may seem to move slow. This is because there simply isn't
  733. enough combined distance traveled in the entire buffer to accelerate up to the nominal speed and then
  734. decelerate to a complete stop at the end of the buffer, as stated by the guidelines. If this happens and
  735. becomes an annoyance, there are a few simple solutions: (1) Maximize the machine acceleration. The planner
  736. will be able to compute higher velocity profiles within the same combined distance. (2) Maximize line
  737. motion(s) distance per block to a desired tolerance. The more combined distance the planner has to use,
  738. the faster it can go. (3) Maximize the planner buffer size. This also will increase the combined distance
  739. for the planner to compute over. It also increases the number of computations the planner has to perform
  740. to compute an optimal plan, so select carefully.
  741. */
  742. // The kernel called by recalculate() when scanning the plan from last to first entry.
  743. void Planner::reverse_pass_kernel(block_t* const current, const block_t * const next) {
  744. if (current) {
  745. // If entry speed is already at the maximum entry speed, and there was no change of speed
  746. // in the next block, there is no need to recheck. Block is cruising and there is no need to
  747. // compute anything for this block,
  748. // If not, block entry speed needs to be recalculated to ensure maximum possible planned speed.
  749. const float max_entry_speed_sqr = current->max_entry_speed_sqr;
  750. // Compute maximum entry speed decelerating over the current block from its exit speed.
  751. // If not at the maximum entry speed, or the previous block entry speed changed
  752. if (current->entry_speed_sqr != max_entry_speed_sqr || (next && TEST(next->flag, BLOCK_BIT_RECALCULATE))) {
  753. // If nominal length true, max junction speed is guaranteed to be reached.
  754. // If a block can de/ac-celerate from nominal speed to zero within the length of the block, then
  755. // the current block and next block junction speeds are guaranteed to always be at their maximum
  756. // junction speeds in deceleration and acceleration, respectively. This is due to how the current
  757. // block nominal speed limits both the current and next maximum junction speeds. Hence, in both
  758. // the reverse and forward planners, the corresponding block junction speed will always be at the
  759. // the maximum junction speed and may always be ignored for any speed reduction checks.
  760. const float new_entry_speed_sqr = TEST(current->flag, BLOCK_BIT_NOMINAL_LENGTH)
  761. ? max_entry_speed_sqr
  762. : MIN(max_entry_speed_sqr, max_allowable_speed_sqr(-current->acceleration, next ? next->entry_speed_sqr : sq(float(MINIMUM_PLANNER_SPEED)), current->millimeters));
  763. if (current->entry_speed_sqr != new_entry_speed_sqr) {
  764. // Need to recalculate the block speed - Mark it now, so the stepper
  765. // ISR does not consume the block before being recalculated
  766. SBI(current->flag, BLOCK_BIT_RECALCULATE);
  767. // But there is an inherent race condition here, as the block may have
  768. // become BUSY just before being marked RECALCULATE, so check for that!
  769. if (stepper.is_block_busy(current)) {
  770. // Block became busy. Clear the RECALCULATE flag (no point in
  771. // recalculating BUSY blocks). And don't set its speed, as it can't
  772. // be updated at this time.
  773. CBI(current->flag, BLOCK_BIT_RECALCULATE);
  774. }
  775. else {
  776. // Block is not BUSY so this is ahead of the Stepper ISR:
  777. // Just Set the new entry speed.
  778. current->entry_speed_sqr = new_entry_speed_sqr;
  779. }
  780. }
  781. }
  782. }
  783. }
  784. /**
  785. * recalculate() needs to go over the current plan twice.
  786. * Once in reverse and once forward. This implements the reverse pass.
  787. */
  788. void Planner::reverse_pass() {
  789. // Initialize block index to the last block in the planner buffer.
  790. uint8_t block_index = prev_block_index(block_buffer_head);
  791. // Read the index of the last buffer planned block.
  792. // The ISR may change it so get a stable local copy.
  793. uint8_t planned_block_index = block_buffer_planned;
  794. // If there was a race condition and block_buffer_planned was incremented
  795. // or was pointing at the head (queue empty) break loop now and avoid
  796. // planning already consumed blocks
  797. if (planned_block_index == block_buffer_head) return;
  798. // Reverse Pass: Coarsely maximize all possible deceleration curves back-planning from the last
  799. // block in buffer. Cease planning when the last optimal planned or tail pointer is reached.
  800. // NOTE: Forward pass will later refine and correct the reverse pass to create an optimal plan.
  801. const block_t *next = NULL;
  802. while (block_index != planned_block_index) {
  803. // Perform the reverse pass
  804. block_t *current = &block_buffer[block_index];
  805. // Only consider non sync blocks
  806. if (!TEST(current->flag, BLOCK_BIT_SYNC_POSITION)) {
  807. reverse_pass_kernel(current, next);
  808. next = current;
  809. }
  810. // Advance to the next
  811. block_index = prev_block_index(block_index);
  812. // The ISR could advance the block_buffer_planned while we were doing the reverse pass.
  813. // We must try to avoid using an already consumed block as the last one - So follow
  814. // changes to the pointer and make sure to limit the loop to the currently busy block
  815. while (planned_block_index != block_buffer_planned) {
  816. // If we reached the busy block or an already processed block, break the loop now
  817. if (block_index == planned_block_index) return;
  818. // Advance the pointer, following the busy block
  819. planned_block_index = next_block_index(planned_block_index);
  820. }
  821. }
  822. }
  823. // The kernel called by recalculate() when scanning the plan from first to last entry.
  824. void Planner::forward_pass_kernel(const block_t* const previous, block_t* const current, const uint8_t block_index) {
  825. if (previous) {
  826. // If the previous block is an acceleration block, too short to complete the full speed
  827. // change, adjust the entry speed accordingly. Entry speeds have already been reset,
  828. // maximized, and reverse-planned. If nominal length is set, max junction speed is
  829. // guaranteed to be reached. No need to recheck.
  830. if (!TEST(previous->flag, BLOCK_BIT_NOMINAL_LENGTH) &&
  831. previous->entry_speed_sqr < current->entry_speed_sqr) {
  832. // Compute the maximum allowable speed
  833. const float new_entry_speed_sqr = max_allowable_speed_sqr(-previous->acceleration, previous->entry_speed_sqr, previous->millimeters);
  834. // If true, current block is full-acceleration and we can move the planned pointer forward.
  835. if (new_entry_speed_sqr < current->entry_speed_sqr) {
  836. // Mark we need to recompute the trapezoidal shape, and do it now,
  837. // so the stepper ISR does not consume the block before being recalculated
  838. SBI(current->flag, BLOCK_BIT_RECALCULATE);
  839. // But there is an inherent race condition here, as the block maybe
  840. // became BUSY, just before it was marked as RECALCULATE, so check
  841. // if that is the case!
  842. if (stepper.is_block_busy(current)) {
  843. // Block became busy. Clear the RECALCULATE flag (no point in
  844. // recalculating BUSY blocks and don't set its speed, as it can't
  845. // be updated at this time.
  846. CBI(current->flag, BLOCK_BIT_RECALCULATE);
  847. }
  848. else {
  849. // Block is not BUSY, we won the race against the Stepper ISR:
  850. // Always <= max_entry_speed_sqr. Backward pass sets this.
  851. current->entry_speed_sqr = new_entry_speed_sqr; // Always <= max_entry_speed_sqr. Backward pass sets this.
  852. // Set optimal plan pointer.
  853. block_buffer_planned = block_index;
  854. }
  855. }
  856. }
  857. // Any block set at its maximum entry speed also creates an optimal plan up to this
  858. // point in the buffer. When the plan is bracketed by either the beginning of the
  859. // buffer and a maximum entry speed or two maximum entry speeds, every block in between
  860. // cannot logically be further improved. Hence, we don't have to recompute them anymore.
  861. if (current->entry_speed_sqr == current->max_entry_speed_sqr)
  862. block_buffer_planned = block_index;
  863. }
  864. }
  865. /**
  866. * recalculate() needs to go over the current plan twice.
  867. * Once in reverse and once forward. This implements the forward pass.
  868. */
  869. void Planner::forward_pass() {
  870. // Forward Pass: Forward plan the acceleration curve from the planned pointer onward.
  871. // Also scans for optimal plan breakpoints and appropriately updates the planned pointer.
  872. // Begin at buffer planned pointer. Note that block_buffer_planned can be modified
  873. // by the stepper ISR, so read it ONCE. It it guaranteed that block_buffer_planned
  874. // will never lead head, so the loop is safe to execute. Also note that the forward
  875. // pass will never modify the values at the tail.
  876. uint8_t block_index = block_buffer_planned;
  877. block_t *current;
  878. const block_t * previous = NULL;
  879. while (block_index != block_buffer_head) {
  880. // Perform the forward pass
  881. current = &block_buffer[block_index];
  882. // Skip SYNC blocks
  883. if (!TEST(current->flag, BLOCK_BIT_SYNC_POSITION)) {
  884. // If there's no previous block or the previous block is not
  885. // BUSY (thus, modifiable) run the forward_pass_kernel. Otherwise,
  886. // the previous block became BUSY, so assume the current block's
  887. // entry speed can't be altered (since that would also require
  888. // updating the exit speed of the previous block).
  889. if (!previous || !stepper.is_block_busy(previous))
  890. forward_pass_kernel(previous, current, block_index);
  891. previous = current;
  892. }
  893. // Advance to the previous
  894. block_index = next_block_index(block_index);
  895. }
  896. }
  897. /**
  898. * Recalculate the trapezoid speed profiles for all blocks in the plan
  899. * according to the entry_factor for each junction. Must be called by
  900. * recalculate() after updating the blocks.
  901. */
  902. void Planner::recalculate_trapezoids() {
  903. // The tail may be changed by the ISR so get a local copy.
  904. uint8_t block_index = block_buffer_tail,
  905. head_block_index = block_buffer_head;
  906. // Since there could be a sync block in the head of the queue, and the
  907. // next loop must not recalculate the head block (as it needs to be
  908. // specially handled), scan backwards to the first non-SYNC block.
  909. while (head_block_index != block_index) {
  910. // Go back (head always point to the first free block)
  911. const uint8_t prev_index = prev_block_index(head_block_index);
  912. // Get the pointer to the block
  913. block_t *prev = &block_buffer[prev_index];
  914. // If not dealing with a sync block, we are done. The last block is not a SYNC block
  915. if (!TEST(prev->flag, BLOCK_BIT_SYNC_POSITION)) break;
  916. // Examine the previous block. This and all following are SYNC blocks
  917. head_block_index = prev_index;
  918. }
  919. // Go from the tail (currently executed block) to the first block, without including it)
  920. block_t *current = NULL, *next = NULL;
  921. float current_entry_speed = 0.0, next_entry_speed = 0.0;
  922. while (block_index != head_block_index) {
  923. next = &block_buffer[block_index];
  924. // Skip sync blocks
  925. if (!TEST(next->flag, BLOCK_BIT_SYNC_POSITION)) {
  926. next_entry_speed = SQRT(next->entry_speed_sqr);
  927. if (current) {
  928. // Recalculate if current block entry or exit junction speed has changed.
  929. if (TEST(current->flag, BLOCK_BIT_RECALCULATE) || TEST(next->flag, BLOCK_BIT_RECALCULATE)) {
  930. // Mark the current block as RECALCULATE, to protect it from the Stepper ISR running it.
  931. // Note that due to the above condition, there's a chance the current block isn't marked as
  932. // RECALCULATE yet, but the next one is. That's the reason for the following line.
  933. SBI(current->flag, BLOCK_BIT_RECALCULATE);
  934. // But there is an inherent race condition here, as the block maybe
  935. // became BUSY, just before it was marked as RECALCULATE, so check
  936. // if that is the case!
  937. if (!stepper.is_block_busy(current)) {
  938. // Block is not BUSY, we won the race against the Stepper ISR:
  939. // NOTE: Entry and exit factors always > 0 by all previous logic operations.
  940. const float current_nominal_speed = SQRT(current->nominal_speed_sqr),
  941. nomr = 1.0f / current_nominal_speed;
  942. calculate_trapezoid_for_block(current, current_entry_speed * nomr, next_entry_speed * nomr);
  943. #if ENABLED(LIN_ADVANCE)
  944. if (current->use_advance_lead) {
  945. const float comp = current->e_D_ratio * extruder_advance_K[active_extruder] * settings.axis_steps_per_mm[E_AXIS];
  946. current->max_adv_steps = current_nominal_speed * comp;
  947. current->final_adv_steps = next_entry_speed * comp;
  948. }
  949. #endif
  950. }
  951. // Reset current only to ensure next trapezoid is computed - The
  952. // stepper is free to use the block from now on.
  953. CBI(current->flag, BLOCK_BIT_RECALCULATE);
  954. }
  955. }
  956. current = next;
  957. current_entry_speed = next_entry_speed;
  958. }
  959. block_index = next_block_index(block_index);
  960. }
  961. // Last/newest block in buffer. Exit speed is set with MINIMUM_PLANNER_SPEED. Always recalculated.
  962. if (next) {
  963. // Mark the next(last) block as RECALCULATE, to prevent the Stepper ISR running it.
  964. // As the last block is always recalculated here, there is a chance the block isn't
  965. // marked as RECALCULATE yet. That's the reason for the following line.
  966. SBI(next->flag, BLOCK_BIT_RECALCULATE);
  967. // But there is an inherent race condition here, as the block maybe
  968. // became BUSY, just before it was marked as RECALCULATE, so check
  969. // if that is the case!
  970. if (!stepper.is_block_busy(current)) {
  971. // Block is not BUSY, we won the race against the Stepper ISR:
  972. const float next_nominal_speed = SQRT(next->nominal_speed_sqr),
  973. nomr = 1.0f / next_nominal_speed;
  974. calculate_trapezoid_for_block(next, next_entry_speed * nomr, float(MINIMUM_PLANNER_SPEED) * nomr);
  975. #if ENABLED(LIN_ADVANCE)
  976. if (next->use_advance_lead) {
  977. const float comp = next->e_D_ratio * extruder_advance_K[active_extruder] * settings.axis_steps_per_mm[E_AXIS];
  978. next->max_adv_steps = next_nominal_speed * comp;
  979. next->final_adv_steps = (MINIMUM_PLANNER_SPEED) * comp;
  980. }
  981. #endif
  982. }
  983. // Reset next only to ensure its trapezoid is computed - The stepper is free to use
  984. // the block from now on.
  985. CBI(next->flag, BLOCK_BIT_RECALCULATE);
  986. }
  987. }
  988. void Planner::recalculate() {
  989. // Initialize block index to the last block in the planner buffer.
  990. const uint8_t block_index = prev_block_index(block_buffer_head);
  991. // If there is just one block, no planning can be done. Avoid it!
  992. if (block_index != block_buffer_planned) {
  993. reverse_pass();
  994. forward_pass();
  995. }
  996. recalculate_trapezoids();
  997. }
  998. #if ENABLED(AUTOTEMP)
  999. void Planner::getHighESpeed() {
  1000. static float oldt = 0;
  1001. if (!autotemp_enabled) return;
  1002. if (thermalManager.degTargetHotend(0) + 2 < autotemp_min) return; // probably temperature set to zero.
  1003. float high = 0.0;
  1004. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  1005. block_t* block = &block_buffer[b];
  1006. if (block->steps[X_AXIS] || block->steps[Y_AXIS] || block->steps[Z_AXIS]) {
  1007. const float se = (float)block->steps[E_AXIS] / block->step_event_count * SQRT(block->nominal_speed_sqr); // mm/sec;
  1008. NOLESS(high, se);
  1009. }
  1010. }
  1011. float t = autotemp_min + high * autotemp_factor;
  1012. t = constrain(t, autotemp_min, autotemp_max);
  1013. if (t < oldt) t = t * (1 - float(AUTOTEMP_OLDWEIGHT)) + oldt * float(AUTOTEMP_OLDWEIGHT);
  1014. oldt = t;
  1015. thermalManager.setTargetHotend(t, 0);
  1016. }
  1017. #endif // AUTOTEMP
  1018. /**
  1019. * Maintain fans, paste extruder pressure,
  1020. */
  1021. void Planner::check_axes_activity() {
  1022. uint8_t axis_active[NUM_AXIS] = { 0 },
  1023. tail_fan_speed[FAN_COUNT];
  1024. #if ENABLED(BARICUDA)
  1025. #if HAS_HEATER_1
  1026. uint8_t tail_valve_pressure;
  1027. #endif
  1028. #if HAS_HEATER_2
  1029. uint8_t tail_e_to_p_pressure;
  1030. #endif
  1031. #endif
  1032. if (has_blocks_queued()) {
  1033. #if FAN_COUNT > 0
  1034. FANS_LOOP(i)
  1035. tail_fan_speed[i] = (block_buffer[block_buffer_tail].fan_speed[i] * uint16_t(thermalManager.fan_speed_scaler[i])) >> 7;
  1036. #endif
  1037. block_t* block;
  1038. #if ENABLED(BARICUDA)
  1039. block = &block_buffer[block_buffer_tail];
  1040. #if HAS_HEATER_1
  1041. tail_valve_pressure = block->valve_pressure;
  1042. #endif
  1043. #if HAS_HEATER_2
  1044. tail_e_to_p_pressure = block->e_to_p_pressure;
  1045. #endif
  1046. #endif
  1047. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  1048. block = &block_buffer[b];
  1049. LOOP_XYZE(i) if (block->steps[i]) axis_active[i]++;
  1050. }
  1051. }
  1052. else {
  1053. #if FAN_COUNT > 0
  1054. FANS_LOOP(i)
  1055. tail_fan_speed[i] = (thermalManager.fan_speed[i] * uint16_t(thermalManager.fan_speed_scaler[i])) >> 7;
  1056. #endif
  1057. #if ENABLED(BARICUDA)
  1058. #if HAS_HEATER_1
  1059. tail_valve_pressure = baricuda_valve_pressure;
  1060. #endif
  1061. #if HAS_HEATER_2
  1062. tail_e_to_p_pressure = baricuda_e_to_p_pressure;
  1063. #endif
  1064. #endif
  1065. }
  1066. #if ENABLED(DISABLE_X)
  1067. if (!axis_active[X_AXIS]) disable_X();
  1068. #endif
  1069. #if ENABLED(DISABLE_Y)
  1070. if (!axis_active[Y_AXIS]) disable_Y();
  1071. #endif
  1072. #if ENABLED(DISABLE_Z)
  1073. if (!axis_active[Z_AXIS]) disable_Z();
  1074. #endif
  1075. #if ENABLED(DISABLE_E)
  1076. if (!axis_active[E_AXIS]) disable_e_steppers();
  1077. #endif
  1078. #if FAN_COUNT > 0
  1079. #if FAN_KICKSTART_TIME > 0
  1080. static millis_t fan_kick_end[FAN_COUNT] = { 0 };
  1081. #define KICKSTART_FAN(f) \
  1082. if (tail_fan_speed[f]) { \
  1083. millis_t ms = millis(); \
  1084. if (fan_kick_end[f] == 0) { \
  1085. fan_kick_end[f] = ms + FAN_KICKSTART_TIME; \
  1086. tail_fan_speed[f] = 255; \
  1087. } else if (PENDING(ms, fan_kick_end[f])) \
  1088. tail_fan_speed[f] = 255; \
  1089. } else fan_kick_end[f] = 0
  1090. #if HAS_FAN0
  1091. KICKSTART_FAN(0);
  1092. #endif
  1093. #if HAS_FAN1
  1094. KICKSTART_FAN(1);
  1095. #endif
  1096. #if HAS_FAN2
  1097. KICKSTART_FAN(2);
  1098. #endif
  1099. #endif // FAN_KICKSTART_TIME > 0
  1100. #if FAN_MIN_PWM != 0 || FAN_MAX_PWM != 255
  1101. #define CALC_FAN_SPEED(f) (tail_fan_speed[f] ? map(tail_fan_speed[f], 1, 255, FAN_MIN_PWM, FAN_MAX_PWM) : 0)
  1102. #else
  1103. #define CALC_FAN_SPEED(f) tail_fan_speed[f]
  1104. #endif
  1105. #if ENABLED(FAN_SOFT_PWM)
  1106. #if HAS_FAN0
  1107. thermalManager.soft_pwm_amount_fan[0] = CALC_FAN_SPEED(0);
  1108. #endif
  1109. #if HAS_FAN1
  1110. thermalManager.soft_pwm_amount_fan[1] = CALC_FAN_SPEED(1);
  1111. #endif
  1112. #if HAS_FAN2
  1113. thermalManager.soft_pwm_amount_fan[2] = CALC_FAN_SPEED(2);
  1114. #endif
  1115. #elif ENABLED(FAST_PWM_FAN)
  1116. #if HAS_FAN0
  1117. thermalManager.set_pwm_duty(FAN_PIN, CALC_FAN_SPEED(0));
  1118. #endif
  1119. #if HAS_FAN1
  1120. thermalManager.set_pwm_duty(FAN1_PIN, CALC_FAN_SPEED(1));
  1121. #endif
  1122. #if HAS_FAN2
  1123. thermalManager.set_pwm_duty(FAN2_PIN, CALC_FAN_SPEED(2));
  1124. #endif
  1125. #else
  1126. #if HAS_FAN0
  1127. analogWrite(FAN_PIN, CALC_FAN_SPEED(0));
  1128. #endif
  1129. #if HAS_FAN1
  1130. analogWrite(FAN1_PIN, CALC_FAN_SPEED(1));
  1131. #endif
  1132. #if HAS_FAN2
  1133. analogWrite(FAN2_PIN, CALC_FAN_SPEED(2));
  1134. #endif
  1135. #endif
  1136. #endif // FAN_COUNT > 0
  1137. #if ENABLED(AUTOTEMP)
  1138. getHighESpeed();
  1139. #endif
  1140. #if ENABLED(BARICUDA)
  1141. #if HAS_HEATER_1
  1142. analogWrite(HEATER_1_PIN, tail_valve_pressure);
  1143. #endif
  1144. #if HAS_HEATER_2
  1145. analogWrite(HEATER_2_PIN, tail_e_to_p_pressure);
  1146. #endif
  1147. #endif
  1148. }
  1149. #if DISABLED(NO_VOLUMETRICS)
  1150. /**
  1151. * Get a volumetric multiplier from a filament diameter.
  1152. * This is the reciprocal of the circular cross-section area.
  1153. * Return 1.0 with volumetric off or a diameter of 0.0.
  1154. */
  1155. inline float calculate_volumetric_multiplier(const float &diameter) {
  1156. return (parser.volumetric_enabled && diameter) ? 1.0f / CIRCLE_AREA(diameter * 0.5f) : 1;
  1157. }
  1158. /**
  1159. * Convert the filament sizes into volumetric multipliers.
  1160. * The multiplier converts a given E value into a length.
  1161. */
  1162. void Planner::calculate_volumetric_multipliers() {
  1163. for (uint8_t i = 0; i < COUNT(filament_size); i++) {
  1164. volumetric_multiplier[i] = calculate_volumetric_multiplier(filament_size[i]);
  1165. refresh_e_factor(i);
  1166. }
  1167. }
  1168. #endif // !NO_VOLUMETRICS
  1169. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  1170. /**
  1171. * Convert the ratio value given by the filament width sensor
  1172. * into a volumetric multiplier. Conversion differs when using
  1173. * linear extrusion vs volumetric extrusion.
  1174. */
  1175. void Planner::calculate_volumetric_for_width_sensor(const int8_t encoded_ratio) {
  1176. // Reconstitute the nominal/measured ratio
  1177. const float nom_meas_ratio = 1 + 0.01f * encoded_ratio,
  1178. ratio_2 = sq(nom_meas_ratio);
  1179. volumetric_multiplier[FILAMENT_SENSOR_EXTRUDER_NUM] = parser.volumetric_enabled
  1180. ? ratio_2 / CIRCLE_AREA(filament_width_nominal * 0.5f) // Volumetric uses a true volumetric multiplier
  1181. : ratio_2; // Linear squares the ratio, which scales the volume
  1182. refresh_e_factor(FILAMENT_SENSOR_EXTRUDER_NUM);
  1183. }
  1184. #endif
  1185. #if HAS_LEVELING
  1186. /**
  1187. * rx, ry, rz - Cartesian positions in mm
  1188. * Leveled XYZ on completion
  1189. */
  1190. void Planner::apply_leveling(float &rx, float &ry, float &rz) {
  1191. if (!leveling_active) return;
  1192. #if ABL_PLANAR
  1193. float dx = rx - (X_TILT_FULCRUM),
  1194. dy = ry - (Y_TILT_FULCRUM);
  1195. apply_rotation_xyz(bed_level_matrix, dx, dy, rz);
  1196. rx = dx + X_TILT_FULCRUM;
  1197. ry = dy + Y_TILT_FULCRUM;
  1198. #elif HAS_MESH
  1199. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1200. const float fade_scaling_factor = fade_scaling_factor_for_z(rz);
  1201. #else
  1202. constexpr float fade_scaling_factor = 1.0;
  1203. #endif
  1204. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  1205. const float raw[XYZ] = { rx, ry, 0 };
  1206. #endif
  1207. rz += (
  1208. #if ENABLED(MESH_BED_LEVELING)
  1209. mbl.get_z(rx, ry
  1210. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1211. , fade_scaling_factor
  1212. #endif
  1213. )
  1214. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  1215. fade_scaling_factor ? fade_scaling_factor * ubl.get_z_correction(rx, ry) : 0.0
  1216. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  1217. fade_scaling_factor ? fade_scaling_factor * bilinear_z_offset(raw) : 0.0
  1218. #endif
  1219. );
  1220. #endif
  1221. }
  1222. void Planner::unapply_leveling(float raw[XYZ]) {
  1223. if (leveling_active) {
  1224. #if ABL_PLANAR
  1225. matrix_3x3 inverse = matrix_3x3::transpose(bed_level_matrix);
  1226. float dx = raw[X_AXIS] - (X_TILT_FULCRUM),
  1227. dy = raw[Y_AXIS] - (Y_TILT_FULCRUM);
  1228. apply_rotation_xyz(inverse, dx, dy, raw[Z_AXIS]);
  1229. raw[X_AXIS] = dx + X_TILT_FULCRUM;
  1230. raw[Y_AXIS] = dy + Y_TILT_FULCRUM;
  1231. #elif HAS_MESH
  1232. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1233. const float fade_scaling_factor = fade_scaling_factor_for_z(raw[Z_AXIS]);
  1234. #else
  1235. constexpr float fade_scaling_factor = 1.0;
  1236. #endif
  1237. raw[Z_AXIS] -= (
  1238. #if ENABLED(MESH_BED_LEVELING)
  1239. mbl.get_z(raw[X_AXIS], raw[Y_AXIS]
  1240. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1241. , fade_scaling_factor
  1242. #endif
  1243. )
  1244. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  1245. fade_scaling_factor ? fade_scaling_factor * ubl.get_z_correction(raw[X_AXIS], raw[Y_AXIS]) : 0.0
  1246. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  1247. fade_scaling_factor ? fade_scaling_factor * bilinear_z_offset(raw) : 0.0
  1248. #endif
  1249. );
  1250. #endif
  1251. }
  1252. #if ENABLED(SKEW_CORRECTION)
  1253. unskew(raw[X_AXIS], raw[Y_AXIS], raw[Z_AXIS]);
  1254. #endif
  1255. }
  1256. #endif // HAS_LEVELING
  1257. #if ENABLED(FWRETRACT)
  1258. /**
  1259. * rz, e - Cartesian positions in mm
  1260. */
  1261. void Planner::apply_retract(float &rz, float &e) {
  1262. rz += fwretract.current_hop;
  1263. e -= fwretract.current_retract[active_extruder];
  1264. }
  1265. void Planner::unapply_retract(float &rz, float &e) {
  1266. rz -= fwretract.current_hop;
  1267. e += fwretract.current_retract[active_extruder];
  1268. }
  1269. #endif
  1270. void Planner::quick_stop() {
  1271. // Remove all the queued blocks. Note that this function is NOT
  1272. // called from the Stepper ISR, so we must consider tail as readonly!
  1273. // that is why we set head to tail - But there is a race condition that
  1274. // must be handled: The tail could change between the read and the assignment
  1275. // so this must be enclosed in a critical section
  1276. const bool was_enabled = STEPPER_ISR_ENABLED();
  1277. if (was_enabled) DISABLE_STEPPER_DRIVER_INTERRUPT();
  1278. // Drop all queue entries
  1279. block_buffer_nonbusy = block_buffer_planned = block_buffer_head = block_buffer_tail;
  1280. // Restart the block delay for the first movement - As the queue was
  1281. // forced to empty, there's no risk the ISR will touch this.
  1282. delay_before_delivering = BLOCK_DELAY_FOR_1ST_MOVE;
  1283. #if ENABLED(ULTRA_LCD)
  1284. // Clear the accumulated runtime
  1285. clear_block_buffer_runtime();
  1286. #endif
  1287. // Make sure to drop any attempt of queuing moves for at least 1 second
  1288. cleaning_buffer_counter = 1000;
  1289. // Reenable Stepper ISR
  1290. if (was_enabled) ENABLE_STEPPER_DRIVER_INTERRUPT();
  1291. // And stop the stepper ISR
  1292. stepper.quick_stop();
  1293. }
  1294. void Planner::endstop_triggered(const AxisEnum axis) {
  1295. // Record stepper position and discard the current block
  1296. stepper.endstop_triggered(axis);
  1297. }
  1298. float Planner::triggered_position_mm(const AxisEnum axis) {
  1299. return stepper.triggered_position(axis) * steps_to_mm[axis];
  1300. }
  1301. void Planner::finish_and_disable() {
  1302. while (has_blocks_queued() || cleaning_buffer_counter) idle();
  1303. disable_all_steppers();
  1304. }
  1305. /**
  1306. * Get an axis position according to stepper position(s)
  1307. * For CORE machines apply translation from ABC to XYZ.
  1308. */
  1309. float Planner::get_axis_position_mm(const AxisEnum axis) {
  1310. float axis_steps;
  1311. #if IS_CORE
  1312. // Requesting one of the "core" axes?
  1313. if (axis == CORE_AXIS_1 || axis == CORE_AXIS_2) {
  1314. // Protect the access to the position.
  1315. const bool was_enabled = STEPPER_ISR_ENABLED();
  1316. if (was_enabled) DISABLE_STEPPER_DRIVER_INTERRUPT();
  1317. // ((a1+a2)+(a1-a2))/2 -> (a1+a2+a1-a2)/2 -> (a1+a1)/2 -> a1
  1318. // ((a1+a2)-(a1-a2))/2 -> (a1+a2-a1+a2)/2 -> (a2+a2)/2 -> a2
  1319. axis_steps = 0.5f * (
  1320. axis == CORE_AXIS_2 ? CORESIGN(stepper.position(CORE_AXIS_1) - stepper.position(CORE_AXIS_2))
  1321. : stepper.position(CORE_AXIS_1) + stepper.position(CORE_AXIS_2)
  1322. );
  1323. if (was_enabled) ENABLE_STEPPER_DRIVER_INTERRUPT();
  1324. }
  1325. else
  1326. axis_steps = stepper.position(axis);
  1327. #else
  1328. axis_steps = stepper.position(axis);
  1329. #endif
  1330. return axis_steps * steps_to_mm[axis];
  1331. }
  1332. /**
  1333. * Block until all buffered steps are executed / cleaned
  1334. */
  1335. void Planner::synchronize() {
  1336. while (
  1337. has_blocks_queued() || cleaning_buffer_counter
  1338. #if ENABLED(EXTERNAL_CLOSED_LOOP_CONTROLLER)
  1339. || (READ(CLOSED_LOOP_ENABLE_PIN) && !READ(CLOSED_LOOP_MOVE_COMPLETE_PIN))
  1340. #endif
  1341. ) idle();
  1342. }
  1343. /**
  1344. * The following implements axis backlash correction. To minimize seams
  1345. * on the printed part, the backlash correction only adds steps to the
  1346. * current segment (instead of creating a new segment, which causes
  1347. * discontinuities and print artifacts).
  1348. *
  1349. * When BACKLASH_SMOOTHING_MM is enabled and non-zero, the backlash
  1350. * correction is spread over multiple segments, smoothing out print
  1351. * artifacts even more.
  1352. */
  1353. #if ENABLED(BACKLASH_COMPENSATION)
  1354. #if ENABLED(BACKLASH_GCODE)
  1355. extern float backlash_distance_mm[], backlash_correction;
  1356. #ifdef BACKLASH_SMOOTHING_MM
  1357. extern float backlash_smoothing_mm;
  1358. #endif
  1359. #else
  1360. constexpr float backlash_distance_mm[XYZ] = BACKLASH_DISTANCE_MM,
  1361. backlash_correction = BACKLASH_CORRECTION;
  1362. #ifdef BACKLASH_SMOOTHING_MM
  1363. constexpr float backlash_smoothing_mm = BACKLASH_SMOOTHING_MM;
  1364. #endif
  1365. #endif
  1366. void Planner::add_backlash_correction_steps(const int32_t da, const int32_t db, const int32_t dc, const uint8_t dm, block_t * const block) {
  1367. static uint8_t last_direction_bits;
  1368. uint8_t changed_dir = last_direction_bits ^ dm;
  1369. // Ignore direction change if no steps are taken in that direction
  1370. if (da == 0) CBI(changed_dir, X_AXIS);
  1371. if (db == 0) CBI(changed_dir, Y_AXIS);
  1372. if (dc == 0) CBI(changed_dir, Z_AXIS);
  1373. last_direction_bits ^= changed_dir;
  1374. if (backlash_correction == 0) return;
  1375. #ifdef BACKLASH_SMOOTHING_MM
  1376. // The segment proportion is a value greater than 0.0 indicating how much residual_error
  1377. // is corrected for in this segment. The contribution is based on segment length and the
  1378. // smoothing distance. Since the computation of this proportion involves a floating point
  1379. // division, defer computation until needed.
  1380. float segment_proportion = 0;
  1381. // Residual error carried forward across multiple segments, so correction can be applied
  1382. // to segments where there is no direction change.
  1383. static int32_t residual_error[XYZ] = { 0 };
  1384. #else
  1385. // No leftover residual error from segment to segment
  1386. int32_t residual_error[XYZ] = { 0 };
  1387. // No direction change, no correction.
  1388. if (!changed_dir) return;
  1389. #endif
  1390. LOOP_XYZ(axis) {
  1391. if (backlash_distance_mm[axis]) {
  1392. const bool reversing = TEST(dm,axis);
  1393. // When an axis changes direction, add axis backlash to the residual error
  1394. if (TEST(changed_dir, axis))
  1395. residual_error[axis] += backlash_correction * (reversing ? -1.0f : 1.0f) * backlash_distance_mm[axis] * planner.settings.axis_steps_per_mm[axis];
  1396. // Decide how much of the residual error to correct in this segment
  1397. int32_t error_correction = residual_error[axis];
  1398. #ifdef BACKLASH_SMOOTHING_MM
  1399. if (error_correction && backlash_smoothing_mm != 0) {
  1400. // Take up a portion of the residual_error in this segment, but only when
  1401. // the current segment travels in the same direction as the correction
  1402. if (reversing == (error_correction < 0)) {
  1403. if (segment_proportion == 0)
  1404. segment_proportion = MIN(1.0f, block->millimeters / backlash_smoothing_mm);
  1405. error_correction = ceil(segment_proportion * error_correction);
  1406. }
  1407. else
  1408. error_correction = 0; // Don't take up any backlash in this segment, as it would subtract steps
  1409. }
  1410. #endif
  1411. // Making a correction reduces the residual error and modifies delta_mm
  1412. if (error_correction) {
  1413. block->steps[axis] += ABS(error_correction);
  1414. residual_error[axis] -= error_correction;
  1415. }
  1416. }
  1417. }
  1418. }
  1419. #endif // BACKLASH_COMPENSATION
  1420. /**
  1421. * Planner::_buffer_steps
  1422. *
  1423. * Add a new linear movement to the planner queue (in terms of steps).
  1424. *
  1425. * target - target position in steps units
  1426. * target_float - target position in direct (mm, degrees) units. optional
  1427. * fr_mm_s - (target) speed of the move
  1428. * extruder - target extruder
  1429. * millimeters - the length of the movement, if known
  1430. *
  1431. * Returns true if movement was properly queued, false otherwise
  1432. */
  1433. bool Planner::_buffer_steps(const int32_t (&target)[XYZE]
  1434. #if HAS_POSITION_FLOAT
  1435. , const float (&target_float)[ABCE]
  1436. #endif
  1437. #if IS_KINEMATIC && ENABLED(JUNCTION_DEVIATION)
  1438. , const float (&delta_mm_cart)[XYZE]
  1439. #endif
  1440. , float fr_mm_s, const uint8_t extruder, const float &millimeters
  1441. ) {
  1442. // If we are cleaning, do not accept queuing of movements
  1443. if (cleaning_buffer_counter) return false;
  1444. // Wait for the next available block
  1445. uint8_t next_buffer_head;
  1446. block_t * const block = get_next_free_block(next_buffer_head);
  1447. // Fill the block with the specified movement
  1448. if (!_populate_block(block, false, target
  1449. #if HAS_POSITION_FLOAT
  1450. , target_float
  1451. #endif
  1452. #if IS_KINEMATIC && ENABLED(JUNCTION_DEVIATION)
  1453. , delta_mm_cart
  1454. #endif
  1455. , fr_mm_s, extruder, millimeters
  1456. )) {
  1457. // Movement was not queued, probably because it was too short.
  1458. // Simply accept that as movement queued and done
  1459. return true;
  1460. }
  1461. // If this is the first added movement, reload the delay, otherwise, cancel it.
  1462. if (block_buffer_head == block_buffer_tail) {
  1463. // If it was the first queued block, restart the 1st block delivery delay, to
  1464. // give the planner an opportunity to queue more movements and plan them
  1465. // As there are no queued movements, the Stepper ISR will not touch this
  1466. // variable, so there is no risk setting this here (but it MUST be done
  1467. // before the following line!!)
  1468. delay_before_delivering = BLOCK_DELAY_FOR_1ST_MOVE;
  1469. }
  1470. // Move buffer head
  1471. block_buffer_head = next_buffer_head;
  1472. // Recalculate and optimize trapezoidal speed profiles
  1473. recalculate();
  1474. // Movement successfully queued!
  1475. return true;
  1476. }
  1477. /**
  1478. * Planner::_populate_block
  1479. *
  1480. * Fills a new linear movement in the block (in terms of steps).
  1481. *
  1482. * target - target position in steps units
  1483. * fr_mm_s - (target) speed of the move
  1484. * extruder - target extruder
  1485. *
  1486. * Returns true is movement is acceptable, false otherwise
  1487. */
  1488. bool Planner::_populate_block(block_t * const block, bool split_move,
  1489. const int32_t (&target)[ABCE]
  1490. #if HAS_POSITION_FLOAT
  1491. , const float (&target_float)[ABCE]
  1492. #endif
  1493. #if IS_KINEMATIC && ENABLED(JUNCTION_DEVIATION)
  1494. , const float (&delta_mm_cart)[XYZE]
  1495. #endif
  1496. , float fr_mm_s, const uint8_t extruder, const float &millimeters/*=0.0*/
  1497. ) {
  1498. const int32_t da = target[A_AXIS] - position[A_AXIS],
  1499. db = target[B_AXIS] - position[B_AXIS],
  1500. dc = target[C_AXIS] - position[C_AXIS];
  1501. int32_t de = target[E_AXIS] - position[E_AXIS];
  1502. /* <-- add a slash to enable
  1503. SERIAL_ECHOPAIR(" _populate_block FR:", fr_mm_s);
  1504. SERIAL_ECHOPAIR(" A:", target[A_AXIS]);
  1505. SERIAL_ECHOPAIR(" (", da);
  1506. SERIAL_ECHOPAIR(" steps) B:", target[B_AXIS]);
  1507. SERIAL_ECHOPAIR(" (", db);
  1508. SERIAL_ECHOPAIR(" steps) C:", target[C_AXIS]);
  1509. SERIAL_ECHOPAIR(" (", dc);
  1510. SERIAL_ECHOPAIR(" steps) E:", target[E_AXIS]);
  1511. SERIAL_ECHOPAIR(" (", de);
  1512. SERIAL_ECHOLNPGM(" steps)");
  1513. //*/
  1514. #if ENABLED(PREVENT_COLD_EXTRUSION) || ENABLED(PREVENT_LENGTHY_EXTRUDE)
  1515. if (de) {
  1516. #if ENABLED(PREVENT_COLD_EXTRUSION)
  1517. if (thermalManager.tooColdToExtrude(extruder)) {
  1518. position[E_AXIS] = target[E_AXIS]; // Behave as if the move really took place, but ignore E part
  1519. #if HAS_POSITION_FLOAT
  1520. position_float[E_AXIS] = target_float[E_AXIS];
  1521. #endif
  1522. de = 0; // no difference
  1523. SERIAL_ECHO_MSG(MSG_ERR_COLD_EXTRUDE_STOP);
  1524. }
  1525. #endif // PREVENT_COLD_EXTRUSION
  1526. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  1527. if (ABS(de * e_factor[extruder]) > (int32_t)settings.axis_steps_per_mm[E_AXIS_N(extruder)] * (EXTRUDE_MAXLENGTH)) { // It's not important to get max. extrusion length in a precision < 1mm, so save some cycles and cast to int
  1528. position[E_AXIS] = target[E_AXIS]; // Behave as if the move really took place, but ignore E part
  1529. #if HAS_POSITION_FLOAT
  1530. position_float[E_AXIS] = target_float[E_AXIS];
  1531. #endif
  1532. de = 0; // no difference
  1533. SERIAL_ECHO_MSG(MSG_ERR_LONG_EXTRUDE_STOP);
  1534. }
  1535. #endif // PREVENT_LENGTHY_EXTRUDE
  1536. }
  1537. #endif // PREVENT_COLD_EXTRUSION || PREVENT_LENGTHY_EXTRUDE
  1538. // Compute direction bit-mask for this block
  1539. uint8_t dm = 0;
  1540. #if CORE_IS_XY
  1541. if (da < 0) SBI(dm, X_HEAD); // Save the real Extruder (head) direction in X Axis
  1542. if (db < 0) SBI(dm, Y_HEAD); // ...and Y
  1543. if (dc < 0) SBI(dm, Z_AXIS);
  1544. if (da + db < 0) SBI(dm, A_AXIS); // Motor A direction
  1545. if (CORESIGN(da - db) < 0) SBI(dm, B_AXIS); // Motor B direction
  1546. #elif CORE_IS_XZ
  1547. if (da < 0) SBI(dm, X_HEAD); // Save the real Extruder (head) direction in X Axis
  1548. if (db < 0) SBI(dm, Y_AXIS);
  1549. if (dc < 0) SBI(dm, Z_HEAD); // ...and Z
  1550. if (da + dc < 0) SBI(dm, A_AXIS); // Motor A direction
  1551. if (CORESIGN(da - dc) < 0) SBI(dm, C_AXIS); // Motor C direction
  1552. #elif CORE_IS_YZ
  1553. if (da < 0) SBI(dm, X_AXIS);
  1554. if (db < 0) SBI(dm, Y_HEAD); // Save the real Extruder (head) direction in Y Axis
  1555. if (dc < 0) SBI(dm, Z_HEAD); // ...and Z
  1556. if (db + dc < 0) SBI(dm, B_AXIS); // Motor B direction
  1557. if (CORESIGN(db - dc) < 0) SBI(dm, C_AXIS); // Motor C direction
  1558. #else
  1559. if (da < 0) SBI(dm, X_AXIS);
  1560. if (db < 0) SBI(dm, Y_AXIS);
  1561. if (dc < 0) SBI(dm, Z_AXIS);
  1562. #endif
  1563. if (de < 0) SBI(dm, E_AXIS);
  1564. const float esteps_float = de * e_factor[extruder];
  1565. const uint32_t esteps = ABS(esteps_float) + 0.5f;
  1566. // Clear all flags, including the "busy" bit
  1567. block->flag = 0x00;
  1568. // Set direction bits
  1569. block->direction_bits = dm;
  1570. // Number of steps for each axis
  1571. // See http://www.corexy.com/theory.html
  1572. #if CORE_IS_XY
  1573. block->steps[A_AXIS] = ABS(da + db);
  1574. block->steps[B_AXIS] = ABS(da - db);
  1575. block->steps[Z_AXIS] = ABS(dc);
  1576. #elif CORE_IS_XZ
  1577. block->steps[A_AXIS] = ABS(da + dc);
  1578. block->steps[Y_AXIS] = ABS(db);
  1579. block->steps[C_AXIS] = ABS(da - dc);
  1580. #elif CORE_IS_YZ
  1581. block->steps[X_AXIS] = ABS(da);
  1582. block->steps[B_AXIS] = ABS(db + dc);
  1583. block->steps[C_AXIS] = ABS(db - dc);
  1584. #elif IS_SCARA
  1585. block->steps[A_AXIS] = ABS(da);
  1586. block->steps[B_AXIS] = ABS(db);
  1587. block->steps[Z_AXIS] = ABS(dc);
  1588. #else
  1589. // default non-h-bot planning
  1590. block->steps[A_AXIS] = ABS(da);
  1591. block->steps[B_AXIS] = ABS(db);
  1592. block->steps[C_AXIS] = ABS(dc);
  1593. #endif
  1594. /**
  1595. * This part of the code calculates the total length of the movement.
  1596. * For cartesian bots, the X_AXIS is the real X movement and same for Y_AXIS.
  1597. * But for corexy bots, that is not true. The "X_AXIS" and "Y_AXIS" motors (that should be named to A_AXIS
  1598. * and B_AXIS) cannot be used for X and Y length, because A=X+Y and B=X-Y.
  1599. * So we need to create other 2 "AXIS", named X_HEAD and Y_HEAD, meaning the real displacement of the Head.
  1600. * Having the real displacement of the head, we can calculate the total movement length and apply the desired speed.
  1601. */
  1602. #if IS_CORE
  1603. float delta_mm[Z_HEAD + 1];
  1604. #if CORE_IS_XY
  1605. delta_mm[X_HEAD] = da * steps_to_mm[A_AXIS];
  1606. delta_mm[Y_HEAD] = db * steps_to_mm[B_AXIS];
  1607. delta_mm[Z_AXIS] = dc * steps_to_mm[Z_AXIS];
  1608. delta_mm[A_AXIS] = (da + db) * steps_to_mm[A_AXIS];
  1609. delta_mm[B_AXIS] = CORESIGN(da - db) * steps_to_mm[B_AXIS];
  1610. #elif CORE_IS_XZ
  1611. delta_mm[X_HEAD] = da * steps_to_mm[A_AXIS];
  1612. delta_mm[Y_AXIS] = db * steps_to_mm[Y_AXIS];
  1613. delta_mm[Z_HEAD] = dc * steps_to_mm[C_AXIS];
  1614. delta_mm[A_AXIS] = (da + dc) * steps_to_mm[A_AXIS];
  1615. delta_mm[C_AXIS] = CORESIGN(da - dc) * steps_to_mm[C_AXIS];
  1616. #elif CORE_IS_YZ
  1617. delta_mm[X_AXIS] = da * steps_to_mm[X_AXIS];
  1618. delta_mm[Y_HEAD] = db * steps_to_mm[B_AXIS];
  1619. delta_mm[Z_HEAD] = dc * steps_to_mm[C_AXIS];
  1620. delta_mm[B_AXIS] = (db + dc) * steps_to_mm[B_AXIS];
  1621. delta_mm[C_AXIS] = CORESIGN(db - dc) * steps_to_mm[C_AXIS];
  1622. #endif
  1623. #else
  1624. float delta_mm[ABCE];
  1625. delta_mm[A_AXIS] = da * steps_to_mm[A_AXIS];
  1626. delta_mm[B_AXIS] = db * steps_to_mm[B_AXIS];
  1627. delta_mm[C_AXIS] = dc * steps_to_mm[C_AXIS];
  1628. #endif
  1629. delta_mm[E_AXIS] = esteps_float * steps_to_mm[E_AXIS_N(extruder)];
  1630. if (block->steps[A_AXIS] < MIN_STEPS_PER_SEGMENT && block->steps[B_AXIS] < MIN_STEPS_PER_SEGMENT && block->steps[C_AXIS] < MIN_STEPS_PER_SEGMENT) {
  1631. block->millimeters = ABS(delta_mm[E_AXIS]);
  1632. }
  1633. else {
  1634. if (millimeters)
  1635. block->millimeters = millimeters;
  1636. else
  1637. block->millimeters = SQRT(
  1638. #if CORE_IS_XY
  1639. sq(delta_mm[X_HEAD]) + sq(delta_mm[Y_HEAD]) + sq(delta_mm[Z_AXIS])
  1640. #elif CORE_IS_XZ
  1641. sq(delta_mm[X_HEAD]) + sq(delta_mm[Y_AXIS]) + sq(delta_mm[Z_HEAD])
  1642. #elif CORE_IS_YZ
  1643. sq(delta_mm[X_AXIS]) + sq(delta_mm[Y_HEAD]) + sq(delta_mm[Z_HEAD])
  1644. #else
  1645. sq(delta_mm[X_AXIS]) + sq(delta_mm[Y_AXIS]) + sq(delta_mm[Z_AXIS])
  1646. #endif
  1647. );
  1648. /**
  1649. * At this point at least one of the axes has more steps than
  1650. * MIN_STEPS_PER_SEGMENT, ensuring the segment won't get dropped as
  1651. * zero-length. It's important to not apply corrections
  1652. * to blocks that would get dropped!
  1653. *
  1654. * A correction function is permitted to add steps to an axis, it
  1655. * should *never* remove steps!
  1656. */
  1657. #if ENABLED(BACKLASH_COMPENSATION)
  1658. add_backlash_correction_steps(da, db, dc, dm, block);
  1659. #endif
  1660. }
  1661. block->steps[E_AXIS] = esteps;
  1662. block->step_event_count = MAX(block->steps[A_AXIS], block->steps[B_AXIS], block->steps[C_AXIS], esteps);
  1663. // Bail if this is a zero-length block
  1664. if (block->step_event_count < MIN_STEPS_PER_SEGMENT) return false;
  1665. #if ENABLED(MIXING_EXTRUDER)
  1666. MIXER_POPULATE_BLOCK();
  1667. #endif
  1668. #if FAN_COUNT > 0
  1669. FANS_LOOP(i) block->fan_speed[i] = thermalManager.fan_speed[i];
  1670. #endif
  1671. #if ENABLED(BARICUDA)
  1672. block->valve_pressure = baricuda_valve_pressure;
  1673. block->e_to_p_pressure = baricuda_e_to_p_pressure;
  1674. #endif
  1675. #if EXTRUDERS > 1
  1676. block->extruder = extruder;
  1677. #endif
  1678. #if ENABLED(AUTO_POWER_CONTROL)
  1679. if (block->steps[X_AXIS] || block->steps[Y_AXIS] || block->steps[Z_AXIS])
  1680. powerManager.power_on();
  1681. #endif
  1682. // Enable active axes
  1683. #if CORE_IS_XY
  1684. if (block->steps[A_AXIS] || block->steps[B_AXIS]) {
  1685. enable_X();
  1686. enable_Y();
  1687. }
  1688. #if DISABLED(Z_LATE_ENABLE)
  1689. if (block->steps[Z_AXIS]) enable_Z();
  1690. #endif
  1691. #elif CORE_IS_XZ
  1692. if (block->steps[A_AXIS] || block->steps[C_AXIS]) {
  1693. enable_X();
  1694. enable_Z();
  1695. }
  1696. if (block->steps[Y_AXIS]) enable_Y();
  1697. #elif CORE_IS_YZ
  1698. if (block->steps[B_AXIS] || block->steps[C_AXIS]) {
  1699. enable_Y();
  1700. enable_Z();
  1701. }
  1702. if (block->steps[X_AXIS]) enable_X();
  1703. #else
  1704. if (block->steps[X_AXIS]) enable_X();
  1705. if (block->steps[Y_AXIS]) enable_Y();
  1706. #if DISABLED(Z_LATE_ENABLE)
  1707. if (block->steps[Z_AXIS]) enable_Z();
  1708. #endif
  1709. #endif
  1710. // Enable extruder(s)
  1711. if (esteps) {
  1712. #if ENABLED(AUTO_POWER_CONTROL)
  1713. powerManager.power_on();
  1714. #endif
  1715. #if ENABLED(DISABLE_INACTIVE_EXTRUDER) // Enable only the selected extruder
  1716. #define DISABLE_IDLE_E(N) if (!g_uc_extruder_last_move[N]) disable_E##N();
  1717. for (uint8_t i = 0; i < EXTRUDERS; i++)
  1718. if (g_uc_extruder_last_move[i] > 0) g_uc_extruder_last_move[i]--;
  1719. switch (extruder) {
  1720. case 0:
  1721. #if EXTRUDERS > 1
  1722. DISABLE_IDLE_E(1);
  1723. #if EXTRUDERS > 2
  1724. DISABLE_IDLE_E(2);
  1725. #if EXTRUDERS > 3
  1726. DISABLE_IDLE_E(3);
  1727. #if EXTRUDERS > 4
  1728. DISABLE_IDLE_E(4);
  1729. #if EXTRUDERS > 5
  1730. DISABLE_IDLE_E(5);
  1731. #endif // EXTRUDERS > 5
  1732. #endif // EXTRUDERS > 4
  1733. #endif // EXTRUDERS > 3
  1734. #endif // EXTRUDERS > 2
  1735. #endif // EXTRUDERS > 1
  1736. enable_E0();
  1737. g_uc_extruder_last_move[0] = (BLOCK_BUFFER_SIZE) * 2;
  1738. #if HAS_DUPLICATION_MODE
  1739. if (extruder_duplication_enabled) {
  1740. enable_E1();
  1741. g_uc_extruder_last_move[1] = (BLOCK_BUFFER_SIZE) * 2;
  1742. }
  1743. #endif
  1744. break;
  1745. #if EXTRUDERS > 1
  1746. case 1:
  1747. DISABLE_IDLE_E(0);
  1748. #if EXTRUDERS > 2
  1749. DISABLE_IDLE_E(2);
  1750. #if EXTRUDERS > 3
  1751. DISABLE_IDLE_E(3);
  1752. #if EXTRUDERS > 4
  1753. DISABLE_IDLE_E(4);
  1754. #if EXTRUDERS > 5
  1755. DISABLE_IDLE_E(5);
  1756. #endif // EXTRUDERS > 5
  1757. #endif // EXTRUDERS > 4
  1758. #endif // EXTRUDERS > 3
  1759. #endif // EXTRUDERS > 2
  1760. enable_E1();
  1761. g_uc_extruder_last_move[1] = (BLOCK_BUFFER_SIZE) * 2;
  1762. break;
  1763. #if EXTRUDERS > 2
  1764. case 2:
  1765. DISABLE_IDLE_E(0);
  1766. DISABLE_IDLE_E(1);
  1767. #if EXTRUDERS > 3
  1768. DISABLE_IDLE_E(3);
  1769. #if EXTRUDERS > 4
  1770. DISABLE_IDLE_E(4);
  1771. #if EXTRUDERS > 5
  1772. DISABLE_IDLE_E(5);
  1773. #endif
  1774. #endif
  1775. #endif
  1776. enable_E2();
  1777. g_uc_extruder_last_move[2] = (BLOCK_BUFFER_SIZE) * 2;
  1778. break;
  1779. #if EXTRUDERS > 3
  1780. case 3:
  1781. DISABLE_IDLE_E(0);
  1782. DISABLE_IDLE_E(1);
  1783. DISABLE_IDLE_E(2);
  1784. #if EXTRUDERS > 4
  1785. DISABLE_IDLE_E(4);
  1786. #if EXTRUDERS > 5
  1787. DISABLE_IDLE_E(5);
  1788. #endif
  1789. #endif
  1790. enable_E3();
  1791. g_uc_extruder_last_move[3] = (BLOCK_BUFFER_SIZE) * 2;
  1792. break;
  1793. #if EXTRUDERS > 4
  1794. case 4:
  1795. DISABLE_IDLE_E(0);
  1796. DISABLE_IDLE_E(1);
  1797. DISABLE_IDLE_E(2);
  1798. DISABLE_IDLE_E(3);
  1799. #if EXTRUDERS > 5
  1800. DISABLE_IDLE_E(5);
  1801. #endif
  1802. enable_E4();
  1803. g_uc_extruder_last_move[4] = (BLOCK_BUFFER_SIZE) * 2;
  1804. break;
  1805. #if EXTRUDERS > 5
  1806. case 5:
  1807. DISABLE_IDLE_E(0);
  1808. DISABLE_IDLE_E(1);
  1809. DISABLE_IDLE_E(2);
  1810. DISABLE_IDLE_E(3);
  1811. DISABLE_IDLE_E(4);
  1812. enable_E5();
  1813. g_uc_extruder_last_move[5] = (BLOCK_BUFFER_SIZE) * 2;
  1814. break;
  1815. #endif // EXTRUDERS > 5
  1816. #endif // EXTRUDERS > 4
  1817. #endif // EXTRUDERS > 3
  1818. #endif // EXTRUDERS > 2
  1819. #endif // EXTRUDERS > 1
  1820. }
  1821. #else
  1822. enable_E0();
  1823. enable_E1();
  1824. enable_E2();
  1825. enable_E3();
  1826. enable_E4();
  1827. enable_E5();
  1828. #endif
  1829. }
  1830. if (esteps)
  1831. NOLESS(fr_mm_s, settings.min_feedrate_mm_s);
  1832. else
  1833. NOLESS(fr_mm_s, settings.min_travel_feedrate_mm_s);
  1834. const float inverse_millimeters = 1.0f / block->millimeters; // Inverse millimeters to remove multiple divides
  1835. // Calculate inverse time for this move. No divide by zero due to previous checks.
  1836. // Example: At 120mm/s a 60mm move takes 0.5s. So this will give 2.0.
  1837. float inverse_secs = fr_mm_s * inverse_millimeters;
  1838. // Get the number of non busy movements in queue (non busy means that they can be altered)
  1839. const uint8_t moves_queued = nonbusy_movesplanned();
  1840. // Slow down when the buffer starts to empty, rather than wait at the corner for a buffer refill
  1841. #if ENABLED(SLOWDOWN) || ENABLED(ULTRA_LCD) || defined(XY_FREQUENCY_LIMIT)
  1842. // Segment time im micro seconds
  1843. uint32_t segment_time_us = LROUND(1000000.0f / inverse_secs);
  1844. #endif
  1845. #if ENABLED(SLOWDOWN)
  1846. if (WITHIN(moves_queued, 2, (BLOCK_BUFFER_SIZE) / 2 - 1)) {
  1847. if (segment_time_us < settings.min_segment_time_us) {
  1848. // buffer is draining, add extra time. The amount of time added increases if the buffer is still emptied more.
  1849. const uint32_t nst = segment_time_us + LROUND(2 * (settings.min_segment_time_us - segment_time_us) / moves_queued);
  1850. inverse_secs = 1000000.0f / nst;
  1851. #if defined(XY_FREQUENCY_LIMIT) || ENABLED(ULTRA_LCD)
  1852. segment_time_us = nst;
  1853. #endif
  1854. }
  1855. }
  1856. #endif
  1857. #if ENABLED(ULTRA_LCD)
  1858. // Protect the access to the position.
  1859. const bool was_enabled = STEPPER_ISR_ENABLED();
  1860. if (was_enabled) DISABLE_STEPPER_DRIVER_INTERRUPT();
  1861. block_buffer_runtime_us += segment_time_us;
  1862. if (was_enabled) ENABLE_STEPPER_DRIVER_INTERRUPT();
  1863. #endif
  1864. block->nominal_speed_sqr = sq(block->millimeters * inverse_secs); // (mm/sec)^2 Always > 0
  1865. block->nominal_rate = CEIL(block->step_event_count * inverse_secs); // (step/sec) Always > 0
  1866. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  1867. static float filwidth_e_count = 0, filwidth_delay_dist = 0;
  1868. //FMM update ring buffer used for delay with filament measurements
  1869. if (extruder == FILAMENT_SENSOR_EXTRUDER_NUM && filwidth_delay_index[1] >= 0) { //only for extruder with filament sensor and if ring buffer is initialized
  1870. constexpr int MMD_CM = MAX_MEASUREMENT_DELAY + 1, MMD_MM = MMD_CM * 10;
  1871. // increment counters with next move in e axis
  1872. filwidth_e_count += delta_mm[E_AXIS];
  1873. filwidth_delay_dist += delta_mm[E_AXIS];
  1874. // Only get new measurements on forward E movement
  1875. if (!UNEAR_ZERO(filwidth_e_count)) {
  1876. // Loop the delay distance counter (modulus by the mm length)
  1877. while (filwidth_delay_dist >= MMD_MM) filwidth_delay_dist -= MMD_MM;
  1878. // Convert into an index into the measurement array
  1879. filwidth_delay_index[0] = int8_t(filwidth_delay_dist * 0.1f);
  1880. // If the index has changed (must have gone forward)...
  1881. if (filwidth_delay_index[0] != filwidth_delay_index[1]) {
  1882. filwidth_e_count = 0; // Reset the E movement counter
  1883. const int8_t meas_sample = thermalManager.widthFil_to_size_ratio();
  1884. do {
  1885. filwidth_delay_index[1] = (filwidth_delay_index[1] + 1) % MMD_CM; // The next unused slot
  1886. measurement_delay[filwidth_delay_index[1]] = meas_sample; // Store the measurement
  1887. } while (filwidth_delay_index[0] != filwidth_delay_index[1]); // More slots to fill?
  1888. }
  1889. }
  1890. }
  1891. #endif
  1892. // Calculate and limit speed in mm/sec for each axis
  1893. float current_speed[NUM_AXIS], speed_factor = 1.0f; // factor <1 decreases speed
  1894. LOOP_XYZE(i) {
  1895. #if ENABLED(MIXING_EXTRUDER) && ENABLED(RETRACT_SYNC_MIXING)
  1896. // In worst case, only one extruder running, no change is needed.
  1897. // In best case, all extruders run the same amount, we can divide by MIXING_STEPPERS
  1898. float delta_mm_i = 0;
  1899. if (i == E_AXIS && mixer.get_current_vtool() == MIXER_AUTORETRACT_TOOL)
  1900. delta_mm_i = delta_mm[i] / MIXING_STEPPERS;
  1901. else
  1902. delta_mm_i = delta_mm[i];
  1903. #else
  1904. const float delta_mm_i = delta_mm[i];
  1905. #endif
  1906. const float cs = ABS(current_speed[i] = delta_mm_i * inverse_secs);
  1907. #if ENABLED(DISTINCT_E_FACTORS)
  1908. if (i == E_AXIS) i += extruder;
  1909. #endif
  1910. if (cs > settings.max_feedrate_mm_s[i]) NOMORE(speed_factor, settings.max_feedrate_mm_s[i] / cs);
  1911. }
  1912. // Max segment time in µs.
  1913. #ifdef XY_FREQUENCY_LIMIT
  1914. // Check and limit the xy direction change frequency
  1915. const unsigned char direction_change = block->direction_bits ^ old_direction_bits;
  1916. old_direction_bits = block->direction_bits;
  1917. segment_time_us = LROUND((float)segment_time_us / speed_factor);
  1918. uint32_t xs0 = axis_segment_time_us[X_AXIS][0],
  1919. xs1 = axis_segment_time_us[X_AXIS][1],
  1920. xs2 = axis_segment_time_us[X_AXIS][2],
  1921. ys0 = axis_segment_time_us[Y_AXIS][0],
  1922. ys1 = axis_segment_time_us[Y_AXIS][1],
  1923. ys2 = axis_segment_time_us[Y_AXIS][2];
  1924. if (TEST(direction_change, X_AXIS)) {
  1925. xs2 = axis_segment_time_us[X_AXIS][2] = xs1;
  1926. xs1 = axis_segment_time_us[X_AXIS][1] = xs0;
  1927. xs0 = 0;
  1928. }
  1929. xs0 = axis_segment_time_us[X_AXIS][0] = xs0 + segment_time_us;
  1930. if (TEST(direction_change, Y_AXIS)) {
  1931. ys2 = axis_segment_time_us[Y_AXIS][2] = axis_segment_time_us[Y_AXIS][1];
  1932. ys1 = axis_segment_time_us[Y_AXIS][1] = axis_segment_time_us[Y_AXIS][0];
  1933. ys0 = 0;
  1934. }
  1935. ys0 = axis_segment_time_us[Y_AXIS][0] = ys0 + segment_time_us;
  1936. const uint32_t max_x_segment_time = MAX(xs0, xs1, xs2),
  1937. max_y_segment_time = MAX(ys0, ys1, ys2),
  1938. min_xy_segment_time = MIN(max_x_segment_time, max_y_segment_time);
  1939. if (min_xy_segment_time < MAX_FREQ_TIME_US) {
  1940. const float low_sf = speed_factor * min_xy_segment_time / (MAX_FREQ_TIME_US);
  1941. NOMORE(speed_factor, low_sf);
  1942. }
  1943. #endif // XY_FREQUENCY_LIMIT
  1944. // Correct the speed
  1945. if (speed_factor < 1.0f) {
  1946. LOOP_XYZE(i) current_speed[i] *= speed_factor;
  1947. block->nominal_rate *= speed_factor;
  1948. block->nominal_speed_sqr = block->nominal_speed_sqr * sq(speed_factor);
  1949. }
  1950. // Compute and limit the acceleration rate for the trapezoid generator.
  1951. const float steps_per_mm = block->step_event_count * inverse_millimeters;
  1952. uint32_t accel;
  1953. if (!block->steps[A_AXIS] && !block->steps[B_AXIS] && !block->steps[C_AXIS]) {
  1954. // convert to: acceleration steps/sec^2
  1955. accel = CEIL(settings.retract_acceleration * steps_per_mm);
  1956. #if ENABLED(LIN_ADVANCE)
  1957. block->use_advance_lead = false;
  1958. #endif
  1959. }
  1960. else {
  1961. #define LIMIT_ACCEL_LONG(AXIS,INDX) do{ \
  1962. if (block->steps[AXIS] && max_acceleration_steps_per_s2[AXIS+INDX] < accel) { \
  1963. const uint32_t comp = max_acceleration_steps_per_s2[AXIS+INDX] * block->step_event_count; \
  1964. if (accel * block->steps[AXIS] > comp) accel = comp / block->steps[AXIS]; \
  1965. } \
  1966. }while(0)
  1967. #define LIMIT_ACCEL_FLOAT(AXIS,INDX) do{ \
  1968. if (block->steps[AXIS] && max_acceleration_steps_per_s2[AXIS+INDX] < accel) { \
  1969. const float comp = (float)max_acceleration_steps_per_s2[AXIS+INDX] * (float)block->step_event_count; \
  1970. if ((float)accel * (float)block->steps[AXIS] > comp) accel = comp / (float)block->steps[AXIS]; \
  1971. } \
  1972. }while(0)
  1973. // Start with print or travel acceleration
  1974. accel = CEIL((esteps ? settings.acceleration : settings.travel_acceleration) * steps_per_mm);
  1975. #if ENABLED(LIN_ADVANCE)
  1976. #if ENABLED(JUNCTION_DEVIATION)
  1977. #if ENABLED(DISTINCT_E_FACTORS)
  1978. #define MAX_E_JERK max_e_jerk[extruder]
  1979. #else
  1980. #define MAX_E_JERK max_e_jerk
  1981. #endif
  1982. #else
  1983. #define MAX_E_JERK max_jerk[E_AXIS]
  1984. #endif
  1985. /**
  1986. *
  1987. * Use LIN_ADVANCE for blocks if all these are true:
  1988. *
  1989. * esteps : This is a print move, because we checked for A, B, C steps before.
  1990. *
  1991. * extruder_advance_K[active_extruder] : There is an advance factor set for this extruder.
  1992. *
  1993. * de > 0 : Extruder is running forward (e.g., for "Wipe while retracting" (Slic3r) or "Combing" (Cura) moves)
  1994. */
  1995. block->use_advance_lead = esteps
  1996. && extruder_advance_K[active_extruder]
  1997. && de > 0;
  1998. if (block->use_advance_lead) {
  1999. block->e_D_ratio = (target_float[E_AXIS] - position_float[E_AXIS]) /
  2000. #if IS_KINEMATIC
  2001. block->millimeters
  2002. #else
  2003. SQRT(sq(target_float[X_AXIS] - position_float[X_AXIS])
  2004. + sq(target_float[Y_AXIS] - position_float[Y_AXIS])
  2005. + sq(target_float[Z_AXIS] - position_float[Z_AXIS]))
  2006. #endif
  2007. ;
  2008. // Check for unusual high e_D ratio to detect if a retract move was combined with the last print move due to min. steps per segment. Never execute this with advance!
  2009. // This assumes no one will use a retract length of 0mm < retr_length < ~0.2mm and no one will print 100mm wide lines using 3mm filament or 35mm wide lines using 1.75mm filament.
  2010. if (block->e_D_ratio > 3.0f)
  2011. block->use_advance_lead = false;
  2012. else {
  2013. const uint32_t max_accel_steps_per_s2 = MAX_E_JERK / (extruder_advance_K[active_extruder] * block->e_D_ratio) * steps_per_mm;
  2014. #if ENABLED(LA_DEBUG)
  2015. if (accel > max_accel_steps_per_s2) SERIAL_ECHOLNPGM("Acceleration limited.");
  2016. #endif
  2017. NOMORE(accel, max_accel_steps_per_s2);
  2018. }
  2019. }
  2020. #endif
  2021. #if ENABLED(DISTINCT_E_FACTORS)
  2022. #define ACCEL_IDX extruder
  2023. #else
  2024. #define ACCEL_IDX 0
  2025. #endif
  2026. // Limit acceleration per axis
  2027. if (block->step_event_count <= cutoff_long) {
  2028. LIMIT_ACCEL_LONG(A_AXIS, 0);
  2029. LIMIT_ACCEL_LONG(B_AXIS, 0);
  2030. LIMIT_ACCEL_LONG(C_AXIS, 0);
  2031. LIMIT_ACCEL_LONG(E_AXIS, ACCEL_IDX);
  2032. }
  2033. else {
  2034. LIMIT_ACCEL_FLOAT(A_AXIS, 0);
  2035. LIMIT_ACCEL_FLOAT(B_AXIS, 0);
  2036. LIMIT_ACCEL_FLOAT(C_AXIS, 0);
  2037. LIMIT_ACCEL_FLOAT(E_AXIS, ACCEL_IDX);
  2038. }
  2039. }
  2040. block->acceleration_steps_per_s2 = accel;
  2041. block->acceleration = accel / steps_per_mm;
  2042. #if DISABLED(S_CURVE_ACCELERATION)
  2043. block->acceleration_rate = (uint32_t)(accel * (4096.0f * 4096.0f / (STEPPER_TIMER_RATE)));
  2044. #endif
  2045. #if ENABLED(LIN_ADVANCE)
  2046. if (block->use_advance_lead) {
  2047. block->advance_speed = (STEPPER_TIMER_RATE) / (extruder_advance_K[active_extruder] * block->e_D_ratio * block->acceleration * settings.axis_steps_per_mm[E_AXIS_N(extruder)]);
  2048. #if ENABLED(LA_DEBUG)
  2049. if (extruder_advance_K[active_extruder] * block->e_D_ratio * block->acceleration * 2 < SQRT(block->nominal_speed_sqr) * block->e_D_ratio)
  2050. SERIAL_ECHOLNPGM("More than 2 steps per eISR loop executed.");
  2051. if (block->advance_speed < 200)
  2052. SERIAL_ECHOLNPGM("eISR running at > 10kHz.");
  2053. #endif
  2054. }
  2055. #endif
  2056. float vmax_junction_sqr; // Initial limit on the segment entry velocity (mm/s)^2
  2057. #if ENABLED(JUNCTION_DEVIATION)
  2058. /**
  2059. * Compute maximum allowable entry speed at junction by centripetal acceleration approximation.
  2060. * Let a circle be tangent to both previous and current path line segments, where the junction
  2061. * deviation is defined as the distance from the junction to the closest edge of the circle,
  2062. * colinear with the circle center. The circular segment joining the two paths represents the
  2063. * path of centripetal acceleration. Solve for max velocity based on max acceleration about the
  2064. * radius of the circle, defined indirectly by junction deviation. This may be also viewed as
  2065. * path width or max_jerk in the previous Grbl version. This approach does not actually deviate
  2066. * from path, but used as a robust way to compute cornering speeds, as it takes into account the
  2067. * nonlinearities of both the junction angle and junction velocity.
  2068. *
  2069. * NOTE: If the junction deviation value is finite, Grbl executes the motions in an exact path
  2070. * mode (G61). If the junction deviation value is zero, Grbl will execute the motion in an exact
  2071. * stop mode (G61.1) manner. In the future, if continuous mode (G64) is desired, the math here
  2072. * is exactly the same. Instead of motioning all the way to junction point, the machine will
  2073. * just follow the arc circle defined here. The Arduino doesn't have the CPU cycles to perform
  2074. * a continuous mode path, but ARM-based microcontrollers most certainly do.
  2075. *
  2076. * NOTE: The max junction speed is a fixed value, since machine acceleration limits cannot be
  2077. * changed dynamically during operation nor can the line move geometry. This must be kept in
  2078. * memory in the event of a feedrate override changing the nominal speeds of blocks, which can
  2079. * change the overall maximum entry speed conditions of all blocks.
  2080. *
  2081. * #######
  2082. * https://github.com/MarlinFirmware/Marlin/issues/10341#issuecomment-388191754
  2083. *
  2084. * hoffbaked: on May 10 2018 tuned and improved the GRBL algorithm for Marlin:
  2085. Okay! It seems to be working good. I somewhat arbitrarily cut it off at 1mm
  2086. on then on anything with less sides than an octagon. With this, and the
  2087. reverse pass actually recalculating things, a corner acceleration value
  2088. of 1000 junction deviation of .05 are pretty reasonable. If the cycles
  2089. can be spared, a better acos could be used. For all I know, it may be
  2090. already calculated in a different place. */
  2091. // Unit vector of previous path line segment
  2092. static float previous_unit_vec[XYZE];
  2093. #if IS_KINEMATIC && ENABLED(JUNCTION_DEVIATION)
  2094. float unit_vec[] = {
  2095. delta_mm_cart[X_AXIS] * inverse_millimeters,
  2096. delta_mm_cart[Y_AXIS] * inverse_millimeters,
  2097. delta_mm_cart[Z_AXIS] * inverse_millimeters,
  2098. delta_mm_cart[E_AXIS] * inverse_millimeters
  2099. };
  2100. #else
  2101. float unit_vec[] = {
  2102. delta_mm[X_AXIS] * inverse_millimeters,
  2103. delta_mm[Y_AXIS] * inverse_millimeters,
  2104. delta_mm[Z_AXIS] * inverse_millimeters,
  2105. delta_mm[E_AXIS] * inverse_millimeters
  2106. };
  2107. #endif
  2108. #if IS_CORE && ENABLED(JUNCTION_DEVIATION)
  2109. /**
  2110. * On CoreXY the length of the vector [A,B] is SQRT(2) times the length of the head movement vector [X,Y].
  2111. * So taking Z and E into account, we cannot scale to a unit vector with "inverse_millimeters".
  2112. * => normalize the complete junction vector
  2113. */
  2114. normalize_junction_vector(unit_vec);
  2115. #endif
  2116. // Skip first block or when previous_nominal_speed is used as a flag for homing and offset cycles.
  2117. if (moves_queued && !UNEAR_ZERO(previous_nominal_speed_sqr)) {
  2118. // Compute cosine of angle between previous and current path. (prev_unit_vec is negative)
  2119. // NOTE: Max junction velocity is computed without sin() or acos() by trig half angle identity.
  2120. float junction_cos_theta = -previous_unit_vec[X_AXIS] * unit_vec[X_AXIS]
  2121. -previous_unit_vec[Y_AXIS] * unit_vec[Y_AXIS]
  2122. -previous_unit_vec[Z_AXIS] * unit_vec[Z_AXIS]
  2123. -previous_unit_vec[E_AXIS] * unit_vec[E_AXIS]
  2124. ;
  2125. // NOTE: Computed without any expensive trig, sin() or acos(), by trig half angle identity of cos(theta).
  2126. if (junction_cos_theta > 0.999999f) {
  2127. // For a 0 degree acute junction, just set minimum junction speed.
  2128. vmax_junction_sqr = sq(float(MINIMUM_PLANNER_SPEED));
  2129. }
  2130. else {
  2131. NOLESS(junction_cos_theta, -0.999999f); // Check for numerical round-off to avoid divide by zero.
  2132. // Convert delta vector to unit vector
  2133. float junction_unit_vec[XYZE] = {
  2134. unit_vec[X_AXIS] - previous_unit_vec[X_AXIS],
  2135. unit_vec[Y_AXIS] - previous_unit_vec[Y_AXIS],
  2136. unit_vec[Z_AXIS] - previous_unit_vec[Z_AXIS],
  2137. unit_vec[E_AXIS] - previous_unit_vec[E_AXIS]
  2138. };
  2139. normalize_junction_vector(junction_unit_vec);
  2140. const float junction_acceleration = limit_value_by_axis_maximum(block->acceleration, junction_unit_vec),
  2141. sin_theta_d2 = SQRT(0.5f * (1.0f - junction_cos_theta)); // Trig half angle identity. Always positive.
  2142. vmax_junction_sqr = (junction_acceleration * junction_deviation_mm * sin_theta_d2) / (1.0f - sin_theta_d2);
  2143. if (block->millimeters < 1) {
  2144. // Fast acos approximation, minus the error bar to be safe
  2145. const float junction_theta = (RADIANS(-40) * sq(junction_cos_theta) - RADIANS(50)) * junction_cos_theta + RADIANS(90) - 0.18f;
  2146. // If angle is greater than 135 degrees (octagon), find speed for approximate arc
  2147. if (junction_theta > RADIANS(135)) {
  2148. const float limit_sqr = block->millimeters / (RADIANS(180) - junction_theta) * junction_acceleration;
  2149. NOMORE(vmax_junction_sqr, limit_sqr);
  2150. }
  2151. }
  2152. }
  2153. // Get the lowest speed
  2154. vmax_junction_sqr = MIN(vmax_junction_sqr, block->nominal_speed_sqr, previous_nominal_speed_sqr);
  2155. }
  2156. else // Init entry speed to zero. Assume it starts from rest. Planner will correct this later.
  2157. vmax_junction_sqr = 0;
  2158. COPY(previous_unit_vec, unit_vec);
  2159. #endif
  2160. #if HAS_CLASSIC_JERK
  2161. /**
  2162. * Adapted from Průša MKS firmware
  2163. * https://github.com/prusa3d/Prusa-Firmware
  2164. */
  2165. const float nominal_speed = SQRT(block->nominal_speed_sqr);
  2166. // Exit speed limited by a jerk to full halt of a previous last segment
  2167. static float previous_safe_speed;
  2168. // Start with a safe speed (from which the machine may halt to stop immediately).
  2169. float safe_speed = nominal_speed;
  2170. uint8_t limited = 0;
  2171. #if ENABLED(JUNCTION_DEVIATION) && ENABLED(LIN_ADVANCE)
  2172. LOOP_XYZ(i)
  2173. #else
  2174. LOOP_XYZE(i)
  2175. #endif
  2176. {
  2177. const float jerk = ABS(current_speed[i]), // cs : Starting from zero, change in speed for this axis
  2178. maxj = max_jerk[i]; // mj : The max jerk setting for this axis
  2179. if (jerk > maxj) { // cs > mj : New current speed too fast?
  2180. if (limited) { // limited already?
  2181. const float mjerk = nominal_speed * maxj; // ns*mj
  2182. if (jerk * safe_speed > mjerk) safe_speed = mjerk / jerk; // ns*mj/cs
  2183. }
  2184. else {
  2185. safe_speed *= maxj / jerk; // Initial limit: ns*mj/cs
  2186. ++limited; // Initially limited
  2187. }
  2188. }
  2189. }
  2190. float vmax_junction;
  2191. if (moves_queued && !UNEAR_ZERO(previous_nominal_speed_sqr)) {
  2192. // Estimate a maximum velocity allowed at a joint of two successive segments.
  2193. // If this maximum velocity allowed is lower than the minimum of the entry / exit safe velocities,
  2194. // then the machine is not coasting anymore and the safe entry / exit velocities shall be used.
  2195. // Factor to multiply the previous / current nominal velocities to get componentwise limited velocities.
  2196. float v_factor = 1;
  2197. limited = 0;
  2198. // The junction velocity will be shared between successive segments. Limit the junction velocity to their minimum.
  2199. // Pick the smaller of the nominal speeds. Higher speed shall not be achieved at the junction during coasting.
  2200. const float previous_nominal_speed = SQRT(previous_nominal_speed_sqr);
  2201. vmax_junction = MIN(nominal_speed, previous_nominal_speed);
  2202. // Now limit the jerk in all axes.
  2203. const float smaller_speed_factor = vmax_junction / previous_nominal_speed;
  2204. #if ENABLED(JUNCTION_DEVIATION) && ENABLED(LIN_ADVANCE)
  2205. LOOP_XYZ(axis)
  2206. #else
  2207. LOOP_XYZE(axis)
  2208. #endif
  2209. {
  2210. // Limit an axis. We have to differentiate: coasting, reversal of an axis, full stop.
  2211. float v_exit = previous_speed[axis] * smaller_speed_factor,
  2212. v_entry = current_speed[axis];
  2213. if (limited) {
  2214. v_exit *= v_factor;
  2215. v_entry *= v_factor;
  2216. }
  2217. // Calculate jerk depending on whether the axis is coasting in the same direction or reversing.
  2218. const float jerk = (v_exit > v_entry)
  2219. ? // coasting axis reversal
  2220. ( (v_entry > 0 || v_exit < 0) ? (v_exit - v_entry) : MAX(v_exit, -v_entry) )
  2221. : // v_exit <= v_entry coasting axis reversal
  2222. ( (v_entry < 0 || v_exit > 0) ? (v_entry - v_exit) : MAX(-v_exit, v_entry) );
  2223. if (jerk > max_jerk[axis]) {
  2224. v_factor *= max_jerk[axis] / jerk;
  2225. ++limited;
  2226. }
  2227. }
  2228. if (limited) vmax_junction *= v_factor;
  2229. // Now the transition velocity is known, which maximizes the shared exit / entry velocity while
  2230. // respecting the jerk factors, it may be possible, that applying separate safe exit / entry velocities will achieve faster prints.
  2231. const float vmax_junction_threshold = vmax_junction * 0.99f;
  2232. if (previous_safe_speed > vmax_junction_threshold && safe_speed > vmax_junction_threshold)
  2233. vmax_junction = safe_speed;
  2234. }
  2235. else
  2236. vmax_junction = safe_speed;
  2237. previous_safe_speed = safe_speed;
  2238. #if ENABLED(JUNCTION_DEVIATION)
  2239. vmax_junction_sqr = MIN(vmax_junction_sqr, sq(vmax_junction));
  2240. #else
  2241. vmax_junction_sqr = sq(vmax_junction);
  2242. #endif
  2243. #endif // Classic Jerk Limiting
  2244. // Max entry speed of this block equals the max exit speed of the previous block.
  2245. block->max_entry_speed_sqr = vmax_junction_sqr;
  2246. // Initialize block entry speed. Compute based on deceleration to user-defined MINIMUM_PLANNER_SPEED.
  2247. const float v_allowable_sqr = max_allowable_speed_sqr(-block->acceleration, sq(float(MINIMUM_PLANNER_SPEED)), block->millimeters);
  2248. // If we are trying to add a split block, start with the
  2249. // max. allowed speed to avoid an interrupted first move.
  2250. block->entry_speed_sqr = !split_move ? sq(float(MINIMUM_PLANNER_SPEED)) : MIN(vmax_junction_sqr, v_allowable_sqr);
  2251. // Initialize planner efficiency flags
  2252. // Set flag if block will always reach maximum junction speed regardless of entry/exit speeds.
  2253. // If a block can de/ac-celerate from nominal speed to zero within the length of the block, then
  2254. // the current block and next block junction speeds are guaranteed to always be at their maximum
  2255. // junction speeds in deceleration and acceleration, respectively. This is due to how the current
  2256. // block nominal speed limits both the current and next maximum junction speeds. Hence, in both
  2257. // the reverse and forward planners, the corresponding block junction speed will always be at the
  2258. // the maximum junction speed and may always be ignored for any speed reduction checks.
  2259. block->flag |= block->nominal_speed_sqr <= v_allowable_sqr ? BLOCK_FLAG_RECALCULATE | BLOCK_FLAG_NOMINAL_LENGTH : BLOCK_FLAG_RECALCULATE;
  2260. // Update previous path unit_vector and nominal speed
  2261. COPY(previous_speed, current_speed);
  2262. previous_nominal_speed_sqr = block->nominal_speed_sqr;
  2263. // Update the position
  2264. static_assert(COUNT(target) > 1, "Parameter to _buffer_steps must be (&target)[XYZE]!");
  2265. COPY(position, target);
  2266. #if HAS_POSITION_FLOAT
  2267. COPY(position_float, target_float);
  2268. #endif
  2269. #if ENABLED(GRADIENT_MIX)
  2270. mixer.gradient_control(target_float[Z_AXIS]);
  2271. #endif
  2272. // Movement was accepted
  2273. return true;
  2274. } // _populate_block()
  2275. /**
  2276. * Planner::buffer_sync_block
  2277. * Add a block to the buffer that just updates the position
  2278. */
  2279. void Planner::buffer_sync_block() {
  2280. // Wait for the next available block
  2281. uint8_t next_buffer_head;
  2282. block_t * const block = get_next_free_block(next_buffer_head);
  2283. // Clear block
  2284. memset(block, 0, sizeof(block_t));
  2285. block->flag = BLOCK_FLAG_SYNC_POSITION;
  2286. block->position[A_AXIS] = position[A_AXIS];
  2287. block->position[B_AXIS] = position[B_AXIS];
  2288. block->position[C_AXIS] = position[C_AXIS];
  2289. block->position[E_AXIS] = position[E_AXIS];
  2290. // If this is the first added movement, reload the delay, otherwise, cancel it.
  2291. if (block_buffer_head == block_buffer_tail) {
  2292. // If it was the first queued block, restart the 1st block delivery delay, to
  2293. // give the planner an opportunity to queue more movements and plan them
  2294. // As there are no queued movements, the Stepper ISR will not touch this
  2295. // variable, so there is no risk setting this here (but it MUST be done
  2296. // before the following line!!)
  2297. delay_before_delivering = BLOCK_DELAY_FOR_1ST_MOVE;
  2298. }
  2299. block_buffer_head = next_buffer_head;
  2300. stepper.wake_up();
  2301. } // buffer_sync_block()
  2302. /**
  2303. * Planner::buffer_segment
  2304. *
  2305. * Add a new linear movement to the buffer in axis units.
  2306. *
  2307. * Leveling and kinematics should be applied ahead of calling this.
  2308. *
  2309. * a,b,c,e - target positions in mm and/or degrees
  2310. * fr_mm_s - (target) speed of the move
  2311. * extruder - target extruder
  2312. * millimeters - the length of the movement, if known
  2313. */
  2314. bool Planner::buffer_segment(const float &a, const float &b, const float &c, const float &e
  2315. #if IS_KINEMATIC && ENABLED(JUNCTION_DEVIATION)
  2316. , const float (&delta_mm_cart)[XYZE]
  2317. #endif
  2318. , const float &fr_mm_s, const uint8_t extruder, const float &millimeters/*=0.0*/
  2319. ) {
  2320. // If we are cleaning, do not accept queuing of movements
  2321. if (cleaning_buffer_counter) return false;
  2322. // When changing extruders recalculate steps corresponding to the E position
  2323. #if ENABLED(DISTINCT_E_FACTORS)
  2324. if (last_extruder != extruder && settings.axis_steps_per_mm[E_AXIS_N(extruder)] != settings.axis_steps_per_mm[E_AXIS_N(last_extruder)]) {
  2325. position[E_AXIS] = LROUND(position[E_AXIS] * settings.axis_steps_per_mm[E_AXIS_N(extruder)] * steps_to_mm[E_AXIS_N(last_extruder)]);
  2326. last_extruder = extruder;
  2327. }
  2328. #endif
  2329. // The target position of the tool in absolute steps
  2330. // Calculate target position in absolute steps
  2331. const int32_t target[ABCE] = {
  2332. LROUND(a * settings.axis_steps_per_mm[A_AXIS]),
  2333. LROUND(b * settings.axis_steps_per_mm[B_AXIS]),
  2334. LROUND(c * settings.axis_steps_per_mm[C_AXIS]),
  2335. LROUND(e * settings.axis_steps_per_mm[E_AXIS_N(extruder)])
  2336. };
  2337. #if HAS_POSITION_FLOAT
  2338. const float target_float[XYZE] = { a, b, c, e };
  2339. #endif
  2340. // DRYRUN prevents E moves from taking place
  2341. if (DEBUGGING(DRYRUN)) {
  2342. position[E_AXIS] = target[E_AXIS];
  2343. #if HAS_POSITION_FLOAT
  2344. position_float[E_AXIS] = e;
  2345. #endif
  2346. }
  2347. /* <-- add a slash to enable
  2348. SERIAL_ECHOPAIR(" buffer_segment FR:", fr_mm_s);
  2349. #if IS_KINEMATIC
  2350. SERIAL_ECHOPAIR(" A:", a);
  2351. SERIAL_ECHOPAIR(" (", position[A_AXIS]);
  2352. SERIAL_ECHOPAIR("->", target[A_AXIS]);
  2353. SERIAL_ECHOPAIR(") B:", b);
  2354. #else
  2355. SERIAL_ECHOPAIR(" X:", a);
  2356. SERIAL_ECHOPAIR(" (", position[X_AXIS]);
  2357. SERIAL_ECHOPAIR("->", target[X_AXIS]);
  2358. SERIAL_ECHOPAIR(") Y:", b);
  2359. #endif
  2360. SERIAL_ECHOPAIR(" (", position[Y_AXIS]);
  2361. SERIAL_ECHOPAIR("->", target[Y_AXIS]);
  2362. #if ENABLED(DELTA)
  2363. SERIAL_ECHOPAIR(") C:", c);
  2364. #else
  2365. SERIAL_ECHOPAIR(") Z:", c);
  2366. #endif
  2367. SERIAL_ECHOPAIR(" (", position[Z_AXIS]);
  2368. SERIAL_ECHOPAIR("->", target[Z_AXIS]);
  2369. SERIAL_ECHOPAIR(") E:", e);
  2370. SERIAL_ECHOPAIR(" (", position[E_AXIS]);
  2371. SERIAL_ECHOPAIR("->", target[E_AXIS]);
  2372. SERIAL_ECHOLNPGM(")");
  2373. //*/
  2374. // Queue the movement
  2375. if (
  2376. !_buffer_steps(target
  2377. #if HAS_POSITION_FLOAT
  2378. , target_float
  2379. #endif
  2380. #if IS_KINEMATIC && ENABLED(JUNCTION_DEVIATION)
  2381. , delta_mm_cart
  2382. #endif
  2383. , fr_mm_s, extruder, millimeters
  2384. )
  2385. ) return false;
  2386. stepper.wake_up();
  2387. return true;
  2388. } // buffer_segment()
  2389. /**
  2390. * Add a new linear movement to the buffer.
  2391. * The target is cartesian, it's translated to delta/scara if
  2392. * needed.
  2393. *
  2394. *
  2395. * rx,ry,rz,e - target position in mm or degrees
  2396. * fr_mm_s - (target) speed of the move (mm/s)
  2397. * extruder - target extruder
  2398. * millimeters - the length of the movement, if known
  2399. * inv_duration - the reciprocal if the duration of the movement, if known (kinematic only if feeedrate scaling is enabled)
  2400. */
  2401. bool Planner::buffer_line(const float &rx, const float &ry, const float &rz, const float &e, const float &fr_mm_s, const uint8_t extruder, const float millimeters
  2402. #if ENABLED(SCARA_FEEDRATE_SCALING)
  2403. , const float &inv_duration
  2404. #endif
  2405. ) {
  2406. float raw[XYZE] = { rx, ry, rz, e };
  2407. #if HAS_POSITION_MODIFIERS
  2408. apply_modifiers(raw);
  2409. #endif
  2410. #if IS_KINEMATIC
  2411. const float delta_mm_cart[] = {
  2412. rx - position_cart[X_AXIS],
  2413. ry - position_cart[Y_AXIS],
  2414. rz - position_cart[Z_AXIS]
  2415. #if ENABLED(JUNCTION_DEVIATION)
  2416. , e - position_cart[E_AXIS]
  2417. #endif
  2418. };
  2419. float mm = millimeters;
  2420. if (mm == 0.0)
  2421. mm = (delta_mm_cart[X_AXIS] != 0.0 || delta_mm_cart[Y_AXIS] != 0.0) ? SQRT(sq(delta_mm_cart[X_AXIS]) + sq(delta_mm_cart[Y_AXIS]) + sq(delta_mm_cart[Z_AXIS])) : ABS(delta_mm_cart[Z_AXIS]);
  2422. inverse_kinematics(raw);
  2423. #if ENABLED(SCARA_FEEDRATE_SCALING)
  2424. // For SCARA scale the feed rate from mm/s to degrees/s
  2425. // i.e., Complete the angular vector in the given time.
  2426. const float duration_recip = inv_duration ? inv_duration : fr_mm_s / mm,
  2427. feedrate = HYPOT(delta[A_AXIS] - position_float[A_AXIS], delta[B_AXIS] - position_float[B_AXIS]) * duration_recip;
  2428. #else
  2429. const float feedrate = fr_mm_s;
  2430. #endif
  2431. if (buffer_segment(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], raw[E_AXIS]
  2432. #if ENABLED(JUNCTION_DEVIATION)
  2433. , delta_mm_cart
  2434. #endif
  2435. , feedrate, extruder, mm
  2436. )) {
  2437. position_cart[X_AXIS] = rx;
  2438. position_cart[Y_AXIS] = ry;
  2439. position_cart[Z_AXIS] = rz;
  2440. position_cart[E_AXIS] = e;
  2441. return true;
  2442. }
  2443. else
  2444. return false;
  2445. #else
  2446. return buffer_segment(raw, fr_mm_s, extruder, millimeters);
  2447. #endif
  2448. } // buffer_line()
  2449. /**
  2450. * Directly set the planner ABC position (and stepper positions)
  2451. * converting mm (or angles for SCARA) into steps.
  2452. *
  2453. * The provided ABC position is in machine units.
  2454. */
  2455. void Planner::set_machine_position_mm(const float &a, const float &b, const float &c, const float &e) {
  2456. #if ENABLED(DISTINCT_E_FACTORS)
  2457. last_extruder = active_extruder;
  2458. #endif
  2459. position[A_AXIS] = LROUND(a * settings.axis_steps_per_mm[A_AXIS]);
  2460. position[B_AXIS] = LROUND(b * settings.axis_steps_per_mm[B_AXIS]);
  2461. position[C_AXIS] = LROUND(c * settings.axis_steps_per_mm[C_AXIS]);
  2462. position[E_AXIS] = LROUND(e * settings.axis_steps_per_mm[E_AXIS_N(active_extruder)]);
  2463. #if HAS_POSITION_FLOAT
  2464. position_float[A_AXIS] = a;
  2465. position_float[B_AXIS] = b;
  2466. position_float[C_AXIS] = c;
  2467. position_float[E_AXIS] = e;
  2468. #endif
  2469. if (has_blocks_queued()) {
  2470. //previous_nominal_speed_sqr = 0.0; // Reset planner junction speeds. Assume start from rest.
  2471. //ZERO(previous_speed);
  2472. buffer_sync_block();
  2473. }
  2474. else
  2475. stepper.set_position(position[A_AXIS], position[B_AXIS], position[C_AXIS], position[E_AXIS]);
  2476. }
  2477. void Planner::set_position_mm(const float &rx, const float &ry, const float &rz, const float &e) {
  2478. float raw[XYZE] = { rx, ry, rz, e };
  2479. #if HAS_POSITION_MODIFIERS
  2480. apply_modifiers(raw
  2481. #if HAS_LEVELING
  2482. , true
  2483. #endif
  2484. );
  2485. #endif
  2486. #if IS_KINEMATIC
  2487. position_cart[X_AXIS] = rx;
  2488. position_cart[Y_AXIS] = ry;
  2489. position_cart[Z_AXIS] = rz;
  2490. position_cart[E_AXIS] = e;
  2491. inverse_kinematics(raw);
  2492. set_machine_position_mm(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], raw[E_AXIS]);
  2493. #else
  2494. set_machine_position_mm(raw[X_AXIS], raw[Y_AXIS], raw[Z_AXIS], raw[E_AXIS]);
  2495. #endif
  2496. }
  2497. /**
  2498. * Setters for planner position (also setting stepper position).
  2499. */
  2500. void Planner::set_e_position_mm(const float &e) {
  2501. const uint8_t axis_index = E_AXIS_N(active_extruder);
  2502. #if ENABLED(DISTINCT_E_FACTORS)
  2503. last_extruder = active_extruder;
  2504. #endif
  2505. #if ENABLED(FWRETRACT)
  2506. float e_new = e - fwretract.current_retract[active_extruder];
  2507. #else
  2508. const float e_new = e;
  2509. #endif
  2510. position[E_AXIS] = LROUND(settings.axis_steps_per_mm[axis_index] * e_new);
  2511. #if HAS_POSITION_FLOAT
  2512. position_float[E_AXIS] = e_new;
  2513. #endif
  2514. #if IS_KINEMATIC
  2515. position_cart[E_AXIS] = e;
  2516. #endif
  2517. if (has_blocks_queued())
  2518. buffer_sync_block();
  2519. else
  2520. stepper.set_position(E_AXIS, position[E_AXIS]);
  2521. }
  2522. // Recalculate the steps/s^2 acceleration rates, based on the mm/s^2
  2523. void Planner::reset_acceleration_rates() {
  2524. #if ENABLED(DISTINCT_E_FACTORS)
  2525. #define AXIS_CONDITION (i < E_AXIS || i == E_AXIS_N(active_extruder))
  2526. #else
  2527. #define AXIS_CONDITION true
  2528. #endif
  2529. uint32_t highest_rate = 1;
  2530. LOOP_XYZE_N(i) {
  2531. max_acceleration_steps_per_s2[i] = settings.max_acceleration_mm_per_s2[i] * settings.axis_steps_per_mm[i];
  2532. if (AXIS_CONDITION) NOLESS(highest_rate, max_acceleration_steps_per_s2[i]);
  2533. }
  2534. cutoff_long = 4294967295UL / highest_rate; // 0xFFFFFFFFUL
  2535. #if ENABLED(JUNCTION_DEVIATION) && ENABLED(LIN_ADVANCE)
  2536. recalculate_max_e_jerk();
  2537. #endif
  2538. }
  2539. // Recalculate position, steps_to_mm if settings.axis_steps_per_mm changes!
  2540. void Planner::refresh_positioning() {
  2541. LOOP_XYZE_N(i) steps_to_mm[i] = 1.0f / settings.axis_steps_per_mm[i];
  2542. set_position_mm(current_position);
  2543. reset_acceleration_rates();
  2544. }
  2545. #if ENABLED(AUTOTEMP)
  2546. void Planner::autotemp_M104_M109() {
  2547. if ((autotemp_enabled = parser.seen('F'))) autotemp_factor = parser.value_float();
  2548. if (parser.seen('S')) autotemp_min = parser.value_celsius();
  2549. if (parser.seen('B')) autotemp_max = parser.value_celsius();
  2550. }
  2551. #endif