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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
  4. *
  5. * Based on Sprinter and grbl.
  6. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <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 "../gcode/parser.h"
  69. #include "../MarlinCore.h"
  70. #if HAS_LEVELING
  71. #include "../feature/bedlevel/bedlevel.h"
  72. #endif
  73. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  74. #include "../feature/filwidth.h"
  75. #endif
  76. #if ENABLED(BARICUDA)
  77. #include "../feature/baricuda.h"
  78. #endif
  79. #if ENABLED(MIXING_EXTRUDER)
  80. #include "../feature/mixing.h"
  81. #endif
  82. #if ENABLED(AUTO_POWER_CONTROL)
  83. #include "../feature/power.h"
  84. #endif
  85. #if ENABLED(BACKLASH_COMPENSATION)
  86. #include "../feature/backlash.h"
  87. #endif
  88. #if ENABLED(CANCEL_OBJECTS)
  89. #include "../feature/cancel_object.h"
  90. #endif
  91. #if ENABLED(POWER_LOSS_RECOVERY)
  92. #include "../feature/powerloss.h"
  93. #endif
  94. #if HAS_CUTTER
  95. #include "../feature/spindle_laser.h"
  96. #endif
  97. // Delay for delivery of first block to the stepper ISR, if the queue contains 2 or
  98. // fewer movements. The delay is measured in milliseconds, and must be less than 250ms
  99. #define BLOCK_DELAY_FOR_1ST_MOVE 100
  100. Planner planner;
  101. // public:
  102. /**
  103. * A ring buffer of moves described in steps
  104. */
  105. block_t Planner::block_buffer[BLOCK_BUFFER_SIZE];
  106. volatile uint8_t Planner::block_buffer_head, // Index of the next block to be pushed
  107. Planner::block_buffer_nonbusy, // Index of the first non-busy block
  108. Planner::block_buffer_planned, // Index of the optimally planned block
  109. Planner::block_buffer_tail; // Index of the busy block, if any
  110. uint16_t Planner::cleaning_buffer_counter; // A counter to disable queuing of blocks
  111. uint8_t Planner::delay_before_delivering; // This counter delays delivery of blocks when queue becomes empty to allow the opportunity of merging blocks
  112. planner_settings_t Planner::settings; // Initialized by settings.load()
  113. uint32_t Planner::max_acceleration_steps_per_s2[XYZE_N]; // (steps/s^2) Derived from mm_per_s2
  114. float Planner::steps_to_mm[XYZE_N]; // (mm) Millimeters per step
  115. #if HAS_JUNCTION_DEVIATION
  116. float Planner::junction_deviation_mm; // (mm) M205 J
  117. #if ENABLED(LIN_ADVANCE)
  118. float Planner::max_e_jerk // Calculated from junction_deviation_mm
  119. TERN_(DISTINCT_E_FACTORS, [EXTRUDERS]);
  120. #endif
  121. #endif
  122. #if HAS_CLASSIC_JERK
  123. TERN(HAS_LINEAR_E_JERK, xyz_pos_t, xyze_pos_t) Planner::max_jerk;
  124. #endif
  125. #if ENABLED(SD_ABORT_ON_ENDSTOP_HIT)
  126. bool Planner::abort_on_endstop_hit = false;
  127. #endif
  128. #if ENABLED(DISTINCT_E_FACTORS)
  129. uint8_t Planner::last_extruder = 0; // Respond to extruder change
  130. #endif
  131. #if EXTRUDERS
  132. int16_t Planner::flow_percentage[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(100); // Extrusion factor for each extruder
  133. float Planner::e_factor[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(1.0f); // The flow percentage and volumetric multiplier combine to scale E movement
  134. #endif
  135. #if DISABLED(NO_VOLUMETRICS)
  136. 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
  137. Planner::volumetric_area_nominal = CIRCLE_AREA(float(DEFAULT_NOMINAL_FILAMENT_DIA) * 0.5f), // Nominal cross-sectional area
  138. Planner::volumetric_multiplier[EXTRUDERS]; // Reciprocal of cross-sectional area of filament (in mm^2). Pre-calculated to reduce computation in the planner
  139. #endif
  140. #if HAS_LEVELING
  141. bool Planner::leveling_active = false; // Flag that auto bed leveling is enabled
  142. #if ABL_PLANAR
  143. matrix_3x3 Planner::bed_level_matrix; // Transform to compensate for bed level
  144. #endif
  145. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  146. float Planner::z_fade_height, // Initialized by settings.load()
  147. Planner::inverse_z_fade_height,
  148. Planner::last_fade_z;
  149. #endif
  150. #else
  151. constexpr bool Planner::leveling_active;
  152. #endif
  153. skew_factor_t Planner::skew_factor; // Initialized by settings.load()
  154. #if ENABLED(AUTOTEMP)
  155. float Planner::autotemp_max = 250,
  156. Planner::autotemp_min = 210,
  157. Planner::autotemp_factor = 0.1f;
  158. bool Planner::autotemp_enabled = false;
  159. #endif
  160. // private:
  161. xyze_long_t Planner::position{0};
  162. uint32_t Planner::cutoff_long;
  163. xyze_float_t Planner::previous_speed;
  164. float Planner::previous_nominal_speed_sqr;
  165. #if ENABLED(DISABLE_INACTIVE_EXTRUDER)
  166. uint8_t Planner::g_uc_extruder_last_move[EXTRUDERS] = { 0 };
  167. #endif
  168. #ifdef XY_FREQUENCY_LIMIT
  169. // Old direction bits. Used for speed calculations
  170. unsigned char Planner::old_direction_bits = 0;
  171. // Segment times (in µs). Used for speed calculations
  172. xy_ulong_t Planner::axis_segment_time_us[3] = { { MAX_FREQ_TIME_US + 1, MAX_FREQ_TIME_US + 1 } };
  173. #endif
  174. #if ENABLED(LIN_ADVANCE)
  175. float Planner::extruder_advance_K[EXTRUDERS]; // Initialized by settings.load()
  176. #endif
  177. #if HAS_POSITION_FLOAT
  178. xyze_pos_t Planner::position_float; // Needed for accurate maths. Steps cannot be used!
  179. #endif
  180. #if IS_KINEMATIC
  181. xyze_pos_t Planner::position_cart;
  182. #endif
  183. #if HAS_SPI_LCD
  184. volatile uint32_t Planner::block_buffer_runtime_us = 0;
  185. #endif
  186. /**
  187. * Class and Instance Methods
  188. */
  189. Planner::Planner() { init(); }
  190. void Planner::init() {
  191. position.reset();
  192. TERN_(HAS_POSITION_FLOAT, position_float.reset());
  193. TERN_(IS_KINEMATIC, position_cart.reset());
  194. previous_speed.reset();
  195. previous_nominal_speed_sqr = 0;
  196. TERN_(ABL_PLANAR, bed_level_matrix.set_to_identity());
  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. * Get the current block for processing
  626. * and mark the block as busy.
  627. * Return nullptr if the buffer is empty
  628. * or if there is a first-block delay.
  629. *
  630. * WARNING: Called from Stepper ISR context!
  631. */
  632. block_t* Planner::get_current_block() {
  633. // Get the number of moves in the planner queue so far
  634. const uint8_t nr_moves = movesplanned();
  635. // If there are any moves queued ...
  636. if (nr_moves) {
  637. // If there is still delay of delivery of blocks running, decrement it
  638. if (delay_before_delivering) {
  639. --delay_before_delivering;
  640. // If the number of movements queued is less than 3, and there is still time
  641. // to wait, do not deliver anything
  642. if (nr_moves < 3 && delay_before_delivering) return nullptr;
  643. delay_before_delivering = 0;
  644. }
  645. // If we are here, there is no excuse to deliver the block
  646. block_t * const block = &block_buffer[block_buffer_tail];
  647. // No trapezoid calculated? Don't execute yet.
  648. if (TEST(block->flag, BLOCK_BIT_RECALCULATE)) return nullptr;
  649. // We can't be sure how long an active block will take, so don't count it.
  650. TERN_(HAS_SPI_LCD, block_buffer_runtime_us -= block->segment_time_us);
  651. // As this block is busy, advance the nonbusy block pointer
  652. block_buffer_nonbusy = next_block_index(block_buffer_tail);
  653. // Push block_buffer_planned pointer, if encountered.
  654. if (block_buffer_tail == block_buffer_planned)
  655. block_buffer_planned = block_buffer_nonbusy;
  656. // Return the block
  657. return block;
  658. }
  659. // The queue became empty
  660. TERN_(HAS_SPI_LCD, clear_block_buffer_runtime()); // paranoia. Buffer is empty now - so reset accumulated time to zero.
  661. return nullptr;
  662. }
  663. /**
  664. * Calculate trapezoid parameters, multiplying the entry- and exit-speeds
  665. * by the provided factors.
  666. **
  667. * ############ VERY IMPORTANT ############
  668. * NOTE that the PRECONDITION to call this function is that the block is
  669. * NOT BUSY and it is marked as RECALCULATE. That WARRANTIES the Stepper ISR
  670. * is not and will not use the block while we modify it, so it is safe to
  671. * alter its values.
  672. */
  673. void Planner::calculate_trapezoid_for_block(block_t* const block, const float &entry_factor, const float &exit_factor) {
  674. uint32_t initial_rate = CEIL(block->nominal_rate * entry_factor),
  675. final_rate = CEIL(block->nominal_rate * exit_factor); // (steps per second)
  676. // Limit minimal step rate (Otherwise the timer will overflow.)
  677. NOLESS(initial_rate, uint32_t(MINIMAL_STEP_RATE));
  678. NOLESS(final_rate, uint32_t(MINIMAL_STEP_RATE));
  679. #if ENABLED(S_CURVE_ACCELERATION)
  680. uint32_t cruise_rate = initial_rate;
  681. #endif
  682. const int32_t accel = block->acceleration_steps_per_s2;
  683. // Steps required for acceleration, deceleration to/from nominal rate
  684. uint32_t accelerate_steps = CEIL(estimate_acceleration_distance(initial_rate, block->nominal_rate, accel)),
  685. decelerate_steps = FLOOR(estimate_acceleration_distance(block->nominal_rate, final_rate, -accel));
  686. // Steps between acceleration and deceleration, if any
  687. int32_t plateau_steps = block->step_event_count - accelerate_steps - decelerate_steps;
  688. // Does accelerate_steps + decelerate_steps exceed step_event_count?
  689. // Then we can't possibly reach the nominal rate, there will be no cruising.
  690. // Use intersection_distance() to calculate accel / braking time in order to
  691. // reach the final_rate exactly at the end of this block.
  692. if (plateau_steps < 0) {
  693. const float accelerate_steps_float = CEIL(intersection_distance(initial_rate, final_rate, accel, block->step_event_count));
  694. accelerate_steps = _MIN(uint32_t(_MAX(accelerate_steps_float, 0)), block->step_event_count);
  695. plateau_steps = 0;
  696. #if ENABLED(S_CURVE_ACCELERATION)
  697. // We won't reach the cruising rate. Let's calculate the speed we will reach
  698. cruise_rate = final_speed(initial_rate, accel, accelerate_steps);
  699. #endif
  700. }
  701. #if ENABLED(S_CURVE_ACCELERATION)
  702. else // We have some plateau time, so the cruise rate will be the nominal rate
  703. cruise_rate = block->nominal_rate;
  704. #endif
  705. #if ENABLED(S_CURVE_ACCELERATION)
  706. // Jerk controlled speed requires to express speed versus time, NOT steps
  707. uint32_t acceleration_time = ((float)(cruise_rate - initial_rate) / accel) * (STEPPER_TIMER_RATE),
  708. deceleration_time = ((float)(cruise_rate - final_rate) / accel) * (STEPPER_TIMER_RATE),
  709. // And to offload calculations from the ISR, we also calculate the inverse of those times here
  710. acceleration_time_inverse = get_period_inverse(acceleration_time),
  711. deceleration_time_inverse = get_period_inverse(deceleration_time);
  712. #endif
  713. // Store new block parameters
  714. block->accelerate_until = accelerate_steps;
  715. block->decelerate_after = accelerate_steps + plateau_steps;
  716. block->initial_rate = initial_rate;
  717. #if ENABLED(S_CURVE_ACCELERATION)
  718. block->acceleration_time = acceleration_time;
  719. block->deceleration_time = deceleration_time;
  720. block->acceleration_time_inverse = acceleration_time_inverse;
  721. block->deceleration_time_inverse = deceleration_time_inverse;
  722. block->cruise_rate = cruise_rate;
  723. #endif
  724. block->final_rate = final_rate;
  725. /**
  726. * Laser trapezoid calculations
  727. *
  728. * Approximate the trapezoid with the laser, incrementing the power every `entry_per` while accelerating
  729. * and decrementing it every `exit_power_per` while decelerating, thus ensuring power is related to feedrate.
  730. *
  731. * LASER_POWER_INLINE_TRAPEZOID_CONT doesn't need this as it continuously approximates
  732. *
  733. * Note this may behave unreliably when running with S_CURVE_ACCELERATION
  734. */
  735. #if ENABLED(LASER_POWER_INLINE_TRAPEZOID)
  736. if (block->laser.power > 0) { // No need to care if power == 0
  737. const uint8_t entry_power = block->laser.power * entry_factor; // Power on block entry
  738. #if DISABLED(LASER_POWER_INLINE_TRAPEZOID_CONT)
  739. // Speedup power
  740. const uint8_t entry_power_diff = block->laser.power - entry_power;
  741. if (entry_power_diff) {
  742. block->laser.entry_per = accelerate_steps / entry_power_diff;
  743. block->laser.power_entry = entry_power;
  744. }
  745. else {
  746. block->laser.entry_per = 0;
  747. block->laser.power_entry = block->laser.power;
  748. }
  749. // Slowdown power
  750. const uint8_t exit_power = block->laser.power * exit_factor, // Power on block entry
  751. exit_power_diff = block->laser.power - exit_power;
  752. if (exit_power_diff) {
  753. block->laser.exit_per = (block->step_event_count - block->decelerate_after) / exit_power_diff;
  754. block->laser.power_exit = exit_power;
  755. }
  756. else {
  757. block->laser.exit_per = 0;
  758. block->laser.power_exit = block->laser.power;
  759. }
  760. #else
  761. block->laser.power_entry = entry_power;
  762. #endif
  763. }
  764. #endif
  765. }
  766. /* PLANNER SPEED DEFINITION
  767. +--------+ <- current->nominal_speed
  768. / \
  769. current->entry_speed -> + \
  770. | + <- next->entry_speed (aka exit speed)
  771. +-------------+
  772. time -->
  773. Recalculates the motion plan according to the following basic guidelines:
  774. 1. Go over every feasible block sequentially in reverse order and calculate the junction speeds
  775. (i.e. current->entry_speed) such that:
  776. a. No junction speed exceeds the pre-computed maximum junction speed limit or nominal speeds of
  777. neighboring blocks.
  778. b. A block entry speed cannot exceed one reverse-computed from its exit speed (next->entry_speed)
  779. with a maximum allowable deceleration over the block travel distance.
  780. c. The last (or newest appended) block is planned from a complete stop (an exit speed of zero).
  781. 2. Go over every block in chronological (forward) order and dial down junction speed values if
  782. a. The exit speed exceeds the one forward-computed from its entry speed with the maximum allowable
  783. acceleration over the block travel distance.
  784. When these stages are complete, the planner will have maximized the velocity profiles throughout the all
  785. of the planner blocks, where every block is operating at its maximum allowable acceleration limits. In
  786. other words, for all of the blocks in the planner, the plan is optimal and no further speed improvements
  787. are possible. If a new block is added to the buffer, the plan is recomputed according to the said
  788. guidelines for a new optimal plan.
  789. To increase computational efficiency of these guidelines, a set of planner block pointers have been
  790. created to indicate stop-compute points for when the planner guidelines cannot logically make any further
  791. changes or improvements to the plan when in normal operation and new blocks are streamed and added to the
  792. planner buffer. For example, if a subset of sequential blocks in the planner have been planned and are
  793. bracketed by junction velocities at their maximums (or by the first planner block as well), no new block
  794. added to the planner buffer will alter the velocity profiles within them. So we no longer have to compute
  795. them. Or, if a set of sequential blocks from the first block in the planner (or a optimal stop-compute
  796. point) are all accelerating, they are all optimal and can not be altered by a new block added to the
  797. planner buffer, as this will only further increase the plan speed to chronological blocks until a maximum
  798. junction velocity is reached. However, if the operational conditions of the plan changes from infrequently
  799. used feed holds or feedrate overrides, the stop-compute pointers will be reset and the entire plan is
  800. recomputed as stated in the general guidelines.
  801. Planner buffer index mapping:
  802. - block_buffer_tail: Points to the beginning of the planner buffer. First to be executed or being executed.
  803. - block_buffer_head: Points to the buffer block after the last block in the buffer. Used to indicate whether
  804. the buffer is full or empty. As described for standard ring buffers, this block is always empty.
  805. - block_buffer_planned: Points to the first buffer block after the last optimally planned block for normal
  806. streaming operating conditions. Use for planning optimizations by avoiding recomputing parts of the
  807. planner buffer that don't change with the addition of a new block, as describe above. In addition,
  808. this block can never be less than block_buffer_tail and will always be pushed forward and maintain
  809. this requirement when encountered by the Planner::discard_current_block() routine during a cycle.
  810. NOTE: Since the planner only computes on what's in the planner buffer, some motions with lots of short
  811. line segments, like G2/3 arcs or complex curves, may seem to move slow. This is because there simply isn't
  812. enough combined distance traveled in the entire buffer to accelerate up to the nominal speed and then
  813. decelerate to a complete stop at the end of the buffer, as stated by the guidelines. If this happens and
  814. becomes an annoyance, there are a few simple solutions: (1) Maximize the machine acceleration. The planner
  815. will be able to compute higher velocity profiles within the same combined distance. (2) Maximize line
  816. motion(s) distance per block to a desired tolerance. The more combined distance the planner has to use,
  817. the faster it can go. (3) Maximize the planner buffer size. This also will increase the combined distance
  818. for the planner to compute over. It also increases the number of computations the planner has to perform
  819. to compute an optimal plan, so select carefully.
  820. */
  821. // The kernel called by recalculate() when scanning the plan from last to first entry.
  822. void Planner::reverse_pass_kernel(block_t* const current, const block_t * const next) {
  823. if (current) {
  824. // If entry speed is already at the maximum entry speed, and there was no change of speed
  825. // in the next block, there is no need to recheck. Block is cruising and there is no need to
  826. // compute anything for this block,
  827. // If not, block entry speed needs to be recalculated to ensure maximum possible planned speed.
  828. const float max_entry_speed_sqr = current->max_entry_speed_sqr;
  829. // Compute maximum entry speed decelerating over the current block from its exit speed.
  830. // If not at the maximum entry speed, or the previous block entry speed changed
  831. if (current->entry_speed_sqr != max_entry_speed_sqr || (next && TEST(next->flag, BLOCK_BIT_RECALCULATE))) {
  832. // If nominal length true, max junction speed is guaranteed to be reached.
  833. // If a block can de/ac-celerate from nominal speed to zero within the length of the block, then
  834. // the current block and next block junction speeds are guaranteed to always be at their maximum
  835. // junction speeds in deceleration and acceleration, respectively. This is due to how the current
  836. // block nominal speed limits both the current and next maximum junction speeds. Hence, in both
  837. // the reverse and forward planners, the corresponding block junction speed will always be at the
  838. // the maximum junction speed and may always be ignored for any speed reduction checks.
  839. const float new_entry_speed_sqr = TEST(current->flag, BLOCK_BIT_NOMINAL_LENGTH)
  840. ? max_entry_speed_sqr
  841. : _MIN(max_entry_speed_sqr, max_allowable_speed_sqr(-current->acceleration, next ? next->entry_speed_sqr : sq(float(MINIMUM_PLANNER_SPEED)), current->millimeters));
  842. if (current->entry_speed_sqr != new_entry_speed_sqr) {
  843. // Need to recalculate the block speed - Mark it now, so the stepper
  844. // ISR does not consume the block before being recalculated
  845. SBI(current->flag, BLOCK_BIT_RECALCULATE);
  846. // But there is an inherent race condition here, as the block may have
  847. // become BUSY just before being marked RECALCULATE, so check for that!
  848. if (stepper.is_block_busy(current)) {
  849. // Block became busy. Clear the RECALCULATE flag (no point in
  850. // recalculating BUSY blocks). And don't set its speed, as it can't
  851. // be updated at this time.
  852. CBI(current->flag, BLOCK_BIT_RECALCULATE);
  853. }
  854. else {
  855. // Block is not BUSY so this is ahead of the Stepper ISR:
  856. // Just Set the new entry speed.
  857. current->entry_speed_sqr = new_entry_speed_sqr;
  858. }
  859. }
  860. }
  861. }
  862. }
  863. /**
  864. * recalculate() needs to go over the current plan twice.
  865. * Once in reverse and once forward. This implements the reverse pass.
  866. */
  867. void Planner::reverse_pass() {
  868. // Initialize block index to the last block in the planner buffer.
  869. uint8_t block_index = prev_block_index(block_buffer_head);
  870. // Read the index of the last buffer planned block.
  871. // The ISR may change it so get a stable local copy.
  872. uint8_t planned_block_index = block_buffer_planned;
  873. // If there was a race condition and block_buffer_planned was incremented
  874. // or was pointing at the head (queue empty) break loop now and avoid
  875. // planning already consumed blocks
  876. if (planned_block_index == block_buffer_head) return;
  877. // Reverse Pass: Coarsely maximize all possible deceleration curves back-planning from the last
  878. // block in buffer. Cease planning when the last optimal planned or tail pointer is reached.
  879. // NOTE: Forward pass will later refine and correct the reverse pass to create an optimal plan.
  880. const block_t *next = nullptr;
  881. while (block_index != planned_block_index) {
  882. // Perform the reverse pass
  883. block_t *current = &block_buffer[block_index];
  884. // Only consider non sync blocks
  885. if (!TEST(current->flag, BLOCK_BIT_SYNC_POSITION)) {
  886. reverse_pass_kernel(current, next);
  887. next = current;
  888. }
  889. // Advance to the next
  890. block_index = prev_block_index(block_index);
  891. // The ISR could advance the block_buffer_planned while we were doing the reverse pass.
  892. // We must try to avoid using an already consumed block as the last one - So follow
  893. // changes to the pointer and make sure to limit the loop to the currently busy block
  894. while (planned_block_index != block_buffer_planned) {
  895. // If we reached the busy block or an already processed block, break the loop now
  896. if (block_index == planned_block_index) return;
  897. // Advance the pointer, following the busy block
  898. planned_block_index = next_block_index(planned_block_index);
  899. }
  900. }
  901. }
  902. // The kernel called by recalculate() when scanning the plan from first to last entry.
  903. void Planner::forward_pass_kernel(const block_t* const previous, block_t* const current, const uint8_t block_index) {
  904. if (previous) {
  905. // If the previous block is an acceleration block, too short to complete the full speed
  906. // change, adjust the entry speed accordingly. Entry speeds have already been reset,
  907. // maximized, and reverse-planned. If nominal length is set, max junction speed is
  908. // guaranteed to be reached. No need to recheck.
  909. if (!TEST(previous->flag, BLOCK_BIT_NOMINAL_LENGTH) &&
  910. previous->entry_speed_sqr < current->entry_speed_sqr) {
  911. // Compute the maximum allowable speed
  912. const float new_entry_speed_sqr = max_allowable_speed_sqr(-previous->acceleration, previous->entry_speed_sqr, previous->millimeters);
  913. // If true, current block is full-acceleration and we can move the planned pointer forward.
  914. if (new_entry_speed_sqr < current->entry_speed_sqr) {
  915. // Mark we need to recompute the trapezoidal shape, and do it now,
  916. // so the stepper ISR does not consume the block before being recalculated
  917. SBI(current->flag, BLOCK_BIT_RECALCULATE);
  918. // But there is an inherent race condition here, as the block maybe
  919. // became BUSY, just before it was marked as RECALCULATE, so check
  920. // if that is the case!
  921. if (stepper.is_block_busy(current)) {
  922. // Block became busy. Clear the RECALCULATE flag (no point in
  923. // recalculating BUSY blocks and don't set its speed, as it can't
  924. // be updated at this time.
  925. CBI(current->flag, BLOCK_BIT_RECALCULATE);
  926. }
  927. else {
  928. // Block is not BUSY, we won the race against the Stepper ISR:
  929. // Always <= max_entry_speed_sqr. Backward pass sets this.
  930. current->entry_speed_sqr = new_entry_speed_sqr; // Always <= max_entry_speed_sqr. Backward pass sets this.
  931. // Set optimal plan pointer.
  932. block_buffer_planned = block_index;
  933. }
  934. }
  935. }
  936. // Any block set at its maximum entry speed also creates an optimal plan up to this
  937. // point in the buffer. When the plan is bracketed by either the beginning of the
  938. // buffer and a maximum entry speed or two maximum entry speeds, every block in between
  939. // cannot logically be further improved. Hence, we don't have to recompute them anymore.
  940. if (current->entry_speed_sqr == current->max_entry_speed_sqr)
  941. block_buffer_planned = block_index;
  942. }
  943. }
  944. /**
  945. * recalculate() needs to go over the current plan twice.
  946. * Once in reverse and once forward. This implements the forward pass.
  947. */
  948. void Planner::forward_pass() {
  949. // Forward Pass: Forward plan the acceleration curve from the planned pointer onward.
  950. // Also scans for optimal plan breakpoints and appropriately updates the planned pointer.
  951. // Begin at buffer planned pointer. Note that block_buffer_planned can be modified
  952. // by the stepper ISR, so read it ONCE. It it guaranteed that block_buffer_planned
  953. // will never lead head, so the loop is safe to execute. Also note that the forward
  954. // pass will never modify the values at the tail.
  955. uint8_t block_index = block_buffer_planned;
  956. block_t *block;
  957. const block_t * previous = nullptr;
  958. while (block_index != block_buffer_head) {
  959. // Perform the forward pass
  960. block = &block_buffer[block_index];
  961. // Skip SYNC blocks
  962. if (!TEST(block->flag, BLOCK_BIT_SYNC_POSITION)) {
  963. // If there's no previous block or the previous block is not
  964. // BUSY (thus, modifiable) run the forward_pass_kernel. Otherwise,
  965. // the previous block became BUSY, so assume the current block's
  966. // entry speed can't be altered (since that would also require
  967. // updating the exit speed of the previous block).
  968. if (!previous || !stepper.is_block_busy(previous))
  969. forward_pass_kernel(previous, block, block_index);
  970. previous = block;
  971. }
  972. // Advance to the previous
  973. block_index = next_block_index(block_index);
  974. }
  975. }
  976. /**
  977. * Recalculate the trapezoid speed profiles for all blocks in the plan
  978. * according to the entry_factor for each junction. Must be called by
  979. * recalculate() after updating the blocks.
  980. */
  981. void Planner::recalculate_trapezoids() {
  982. // The tail may be changed by the ISR so get a local copy.
  983. uint8_t block_index = block_buffer_tail,
  984. head_block_index = block_buffer_head;
  985. // Since there could be a sync block in the head of the queue, and the
  986. // next loop must not recalculate the head block (as it needs to be
  987. // specially handled), scan backwards to the first non-SYNC block.
  988. while (head_block_index != block_index) {
  989. // Go back (head always point to the first free block)
  990. const uint8_t prev_index = prev_block_index(head_block_index);
  991. // Get the pointer to the block
  992. block_t *prev = &block_buffer[prev_index];
  993. // If not dealing with a sync block, we are done. The last block is not a SYNC block
  994. if (!TEST(prev->flag, BLOCK_BIT_SYNC_POSITION)) break;
  995. // Examine the previous block. This and all following are SYNC blocks
  996. head_block_index = prev_index;
  997. }
  998. // Go from the tail (currently executed block) to the first block, without including it)
  999. block_t *block = nullptr, *next = nullptr;
  1000. float current_entry_speed = 0.0, next_entry_speed = 0.0;
  1001. while (block_index != head_block_index) {
  1002. next = &block_buffer[block_index];
  1003. // Skip sync blocks
  1004. if (!TEST(next->flag, BLOCK_BIT_SYNC_POSITION)) {
  1005. next_entry_speed = SQRT(next->entry_speed_sqr);
  1006. if (block) {
  1007. // Recalculate if current block entry or exit junction speed has changed.
  1008. if (TEST(block->flag, BLOCK_BIT_RECALCULATE) || TEST(next->flag, BLOCK_BIT_RECALCULATE)) {
  1009. // Mark the current block as RECALCULATE, to protect it from the Stepper ISR running it.
  1010. // Note that due to the above condition, there's a chance the current block isn't marked as
  1011. // RECALCULATE yet, but the next one is. That's the reason for the following line.
  1012. SBI(block->flag, BLOCK_BIT_RECALCULATE);
  1013. // But there is an inherent race condition here, as the block maybe
  1014. // became BUSY, just before it was marked as RECALCULATE, so check
  1015. // if that is the case!
  1016. if (!stepper.is_block_busy(block)) {
  1017. // Block is not BUSY, we won the race against the Stepper ISR:
  1018. // NOTE: Entry and exit factors always > 0 by all previous logic operations.
  1019. const float current_nominal_speed = SQRT(block->nominal_speed_sqr),
  1020. nomr = 1.0f / current_nominal_speed;
  1021. calculate_trapezoid_for_block(block, current_entry_speed * nomr, next_entry_speed * nomr);
  1022. #if ENABLED(LIN_ADVANCE)
  1023. if (block->use_advance_lead) {
  1024. const float comp = block->e_D_ratio * extruder_advance_K[active_extruder] * settings.axis_steps_per_mm[E_AXIS];
  1025. block->max_adv_steps = current_nominal_speed * comp;
  1026. block->final_adv_steps = next_entry_speed * comp;
  1027. }
  1028. #endif
  1029. }
  1030. // Reset current only to ensure next trapezoid is computed - The
  1031. // stepper is free to use the block from now on.
  1032. CBI(block->flag, BLOCK_BIT_RECALCULATE);
  1033. }
  1034. }
  1035. block = next;
  1036. current_entry_speed = next_entry_speed;
  1037. }
  1038. block_index = next_block_index(block_index);
  1039. }
  1040. // Last/newest block in buffer. Exit speed is set with MINIMUM_PLANNER_SPEED. Always recalculated.
  1041. if (next) {
  1042. // Mark the next(last) block as RECALCULATE, to prevent the Stepper ISR running it.
  1043. // As the last block is always recalculated here, there is a chance the block isn't
  1044. // marked as RECALCULATE yet. That's the reason for the following line.
  1045. SBI(next->flag, BLOCK_BIT_RECALCULATE);
  1046. // But there is an inherent race condition here, as the block maybe
  1047. // became BUSY, just before it was marked as RECALCULATE, so check
  1048. // if that is the case!
  1049. if (!stepper.is_block_busy(block)) {
  1050. // Block is not BUSY, we won the race against the Stepper ISR:
  1051. const float next_nominal_speed = SQRT(next->nominal_speed_sqr),
  1052. nomr = 1.0f / next_nominal_speed;
  1053. calculate_trapezoid_for_block(next, next_entry_speed * nomr, float(MINIMUM_PLANNER_SPEED) * nomr);
  1054. #if ENABLED(LIN_ADVANCE)
  1055. if (next->use_advance_lead) {
  1056. const float comp = next->e_D_ratio * extruder_advance_K[active_extruder] * settings.axis_steps_per_mm[E_AXIS];
  1057. next->max_adv_steps = next_nominal_speed * comp;
  1058. next->final_adv_steps = (MINIMUM_PLANNER_SPEED) * comp;
  1059. }
  1060. #endif
  1061. }
  1062. // Reset next only to ensure its trapezoid is computed - The stepper is free to use
  1063. // the block from now on.
  1064. CBI(next->flag, BLOCK_BIT_RECALCULATE);
  1065. }
  1066. }
  1067. void Planner::recalculate() {
  1068. // Initialize block index to the last block in the planner buffer.
  1069. const uint8_t block_index = prev_block_index(block_buffer_head);
  1070. // If there is just one block, no planning can be done. Avoid it!
  1071. if (block_index != block_buffer_planned) {
  1072. reverse_pass();
  1073. forward_pass();
  1074. }
  1075. recalculate_trapezoids();
  1076. }
  1077. #if ENABLED(AUTOTEMP)
  1078. void Planner::getHighESpeed() {
  1079. static float oldt = 0;
  1080. if (!autotemp_enabled) return;
  1081. if (thermalManager.degTargetHotend(0) + 2 < autotemp_min) return; // probably temperature set to zero.
  1082. float high = 0.0;
  1083. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  1084. block_t* block = &block_buffer[b];
  1085. if (block->steps.x || block->steps.y || block->steps.z) {
  1086. const float se = (float)block->steps.e / block->step_event_count * SQRT(block->nominal_speed_sqr); // mm/sec;
  1087. NOLESS(high, se);
  1088. }
  1089. }
  1090. float t = autotemp_min + high * autotemp_factor;
  1091. LIMIT(t, autotemp_min, autotemp_max);
  1092. if (t < oldt) t = t * (1 - float(AUTOTEMP_OLDWEIGHT)) + oldt * float(AUTOTEMP_OLDWEIGHT);
  1093. oldt = t;
  1094. thermalManager.setTargetHotend(t, 0);
  1095. }
  1096. #endif // AUTOTEMP
  1097. /**
  1098. * Maintain fans, paste extruder pressure,
  1099. */
  1100. void Planner::check_axes_activity() {
  1101. #if ANY(DISABLE_X, DISABLE_Y, DISABLE_Z, DISABLE_E)
  1102. xyze_bool_t axis_active = { false };
  1103. #endif
  1104. #if HAS_FAN
  1105. uint8_t tail_fan_speed[FAN_COUNT];
  1106. #endif
  1107. #if ENABLED(BARICUDA)
  1108. #if HAS_HEATER_1
  1109. uint8_t tail_valve_pressure;
  1110. #endif
  1111. #if HAS_HEATER_2
  1112. uint8_t tail_e_to_p_pressure;
  1113. #endif
  1114. #endif
  1115. if (has_blocks_queued()) {
  1116. #if HAS_FAN || ENABLED(BARICUDA)
  1117. block_t *block = &block_buffer[block_buffer_tail];
  1118. #endif
  1119. #if HAS_FAN
  1120. FANS_LOOP(i)
  1121. tail_fan_speed[i] = thermalManager.scaledFanSpeed(i, block->fan_speed[i]);
  1122. #endif
  1123. #if ENABLED(BARICUDA)
  1124. TERN_(HAS_HEATER_1, tail_valve_pressure = block->valve_pressure);
  1125. TERN_(HAS_HEATER_2, tail_e_to_p_pressure = block->e_to_p_pressure);
  1126. #endif
  1127. #if ANY(DISABLE_X, DISABLE_Y, DISABLE_Z, DISABLE_E)
  1128. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  1129. block_t *block = &block_buffer[b];
  1130. LOOP_XYZE(i) if (block->steps[i]) axis_active[i] = true;
  1131. }
  1132. #endif
  1133. }
  1134. else {
  1135. TERN_(HAS_CUTTER, cutter.refresh());
  1136. #if HAS_FAN
  1137. FANS_LOOP(i)
  1138. tail_fan_speed[i] = thermalManager.scaledFanSpeed(i);
  1139. #endif
  1140. #if ENABLED(BARICUDA)
  1141. TERN_(HAS_HEATER_1, tail_valve_pressure = baricuda_valve_pressure);
  1142. TERN_(HAS_HEATER_2, tail_e_to_p_pressure = baricuda_e_to_p_pressure);
  1143. #endif
  1144. }
  1145. //
  1146. // Disable inactive axes
  1147. //
  1148. if (TERN0(DISABLE_X, !axis_active.x)) DISABLE_AXIS_X();
  1149. if (TERN0(DISABLE_Y, !axis_active.y)) DISABLE_AXIS_Y();
  1150. if (TERN0(DISABLE_Z, !axis_active.z)) DISABLE_AXIS_Z();
  1151. if (TERN0(DISABLE_E, !axis_active.e)) disable_e_steppers();
  1152. //
  1153. // Update Fan speeds
  1154. //
  1155. #if HAS_FAN
  1156. #if FAN_KICKSTART_TIME > 0
  1157. static millis_t fan_kick_end[FAN_COUNT] = { 0 };
  1158. #define KICKSTART_FAN(f) \
  1159. if (tail_fan_speed[f]) { \
  1160. millis_t ms = millis(); \
  1161. if (fan_kick_end[f] == 0) { \
  1162. fan_kick_end[f] = ms + FAN_KICKSTART_TIME; \
  1163. tail_fan_speed[f] = 255; \
  1164. } else if (PENDING(ms, fan_kick_end[f])) \
  1165. tail_fan_speed[f] = 255; \
  1166. } else fan_kick_end[f] = 0
  1167. #else
  1168. #define KICKSTART_FAN(f) NOOP
  1169. #endif
  1170. #if FAN_MIN_PWM != 0 || FAN_MAX_PWM != 255
  1171. #define CALC_FAN_SPEED(f) (tail_fan_speed[f] ? map(tail_fan_speed[f], 1, 255, FAN_MIN_PWM, FAN_MAX_PWM) : FAN_OFF_PWM)
  1172. #else
  1173. #define CALC_FAN_SPEED(f) (tail_fan_speed[f] ?: FAN_OFF_PWM)
  1174. #endif
  1175. #if ENABLED(FAN_SOFT_PWM)
  1176. #define _FAN_SET(F) thermalManager.soft_pwm_amount_fan[F] = CALC_FAN_SPEED(F);
  1177. #elif ENABLED(FAST_PWM_FAN)
  1178. #define _FAN_SET(F) set_pwm_duty(FAN##F##_PIN, CALC_FAN_SPEED(F));
  1179. #else
  1180. #define _FAN_SET(F) analogWrite(pin_t(FAN##F##_PIN), CALC_FAN_SPEED(F));
  1181. #endif
  1182. #define FAN_SET(F) do{ KICKSTART_FAN(F); _FAN_SET(F); }while(0)
  1183. TERN_(HAS_FAN0, FAN_SET(0));
  1184. TERN_(HAS_FAN1, FAN_SET(1));
  1185. TERN_(HAS_FAN2, FAN_SET(2));
  1186. TERN_(HAS_FAN3, FAN_SET(3));
  1187. TERN_(HAS_FAN4, FAN_SET(4));
  1188. TERN_(HAS_FAN5, FAN_SET(5));
  1189. TERN_(HAS_FAN6, FAN_SET(6));
  1190. TERN_(HAS_FAN7, FAN_SET(7));
  1191. #endif // HAS_FAN
  1192. TERN_(AUTOTEMP, getHighESpeed());
  1193. #if ENABLED(BARICUDA)
  1194. TERN_(HAS_HEATER_1, analogWrite(pin_t(HEATER_1_PIN), tail_valve_pressure));
  1195. TERN_(HAS_HEATER_2, analogWrite(pin_t(HEATER_2_PIN), tail_e_to_p_pressure));
  1196. #endif
  1197. }
  1198. #if DISABLED(NO_VOLUMETRICS)
  1199. /**
  1200. * Get a volumetric multiplier from a filament diameter.
  1201. * This is the reciprocal of the circular cross-section area.
  1202. * Return 1.0 with volumetric off or a diameter of 0.0.
  1203. */
  1204. inline float calculate_volumetric_multiplier(const float &diameter) {
  1205. return (parser.volumetric_enabled && diameter) ? 1.0f / CIRCLE_AREA(diameter * 0.5f) : 1;
  1206. }
  1207. /**
  1208. * Convert the filament sizes into volumetric multipliers.
  1209. * The multiplier converts a given E value into a length.
  1210. */
  1211. void Planner::calculate_volumetric_multipliers() {
  1212. LOOP_L_N(i, COUNT(filament_size)) {
  1213. volumetric_multiplier[i] = calculate_volumetric_multiplier(filament_size[i]);
  1214. refresh_e_factor(i);
  1215. }
  1216. }
  1217. #endif // !NO_VOLUMETRICS
  1218. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  1219. /**
  1220. * Convert the ratio value given by the filament width sensor
  1221. * into a volumetric multiplier. Conversion differs when using
  1222. * linear extrusion vs volumetric extrusion.
  1223. */
  1224. void Planner::apply_filament_width_sensor(const int8_t encoded_ratio) {
  1225. // Reconstitute the nominal/measured ratio
  1226. const float nom_meas_ratio = 1 + 0.01f * encoded_ratio,
  1227. ratio_2 = sq(nom_meas_ratio);
  1228. volumetric_multiplier[FILAMENT_SENSOR_EXTRUDER_NUM] = parser.volumetric_enabled
  1229. ? ratio_2 / CIRCLE_AREA(filwidth.nominal_mm * 0.5f) // Volumetric uses a true volumetric multiplier
  1230. : ratio_2; // Linear squares the ratio, which scales the volume
  1231. refresh_e_factor(FILAMENT_SENSOR_EXTRUDER_NUM);
  1232. }
  1233. #endif
  1234. #if HAS_LEVELING
  1235. constexpr xy_pos_t level_fulcrum = {
  1236. TERN(Z_SAFE_HOMING, Z_SAFE_HOMING_X_POINT, X_HOME_POS),
  1237. TERN(Z_SAFE_HOMING, Z_SAFE_HOMING_Y_POINT, Y_HOME_POS)
  1238. };
  1239. /**
  1240. * rx, ry, rz - Cartesian positions in mm
  1241. * Leveled XYZ on completion
  1242. */
  1243. void Planner::apply_leveling(xyz_pos_t &raw) {
  1244. if (!leveling_active) return;
  1245. #if ABL_PLANAR
  1246. xy_pos_t d = raw - level_fulcrum;
  1247. apply_rotation_xyz(bed_level_matrix, d.x, d.y, raw.z);
  1248. raw = d + level_fulcrum;
  1249. #elif HAS_MESH
  1250. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1251. const float fade_scaling_factor = fade_scaling_factor_for_z(raw.z);
  1252. #elif DISABLED(MESH_BED_LEVELING)
  1253. constexpr float fade_scaling_factor = 1.0;
  1254. #endif
  1255. raw.z += (
  1256. #if ENABLED(MESH_BED_LEVELING)
  1257. mbl.get_z(raw
  1258. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1259. , fade_scaling_factor
  1260. #endif
  1261. )
  1262. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  1263. fade_scaling_factor ? fade_scaling_factor * ubl.get_z_correction(raw) : 0.0
  1264. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  1265. fade_scaling_factor ? fade_scaling_factor * bilinear_z_offset(raw) : 0.0
  1266. #endif
  1267. );
  1268. #endif
  1269. }
  1270. void Planner::unapply_leveling(xyz_pos_t &raw) {
  1271. if (leveling_active) {
  1272. #if ABL_PLANAR
  1273. matrix_3x3 inverse = matrix_3x3::transpose(bed_level_matrix);
  1274. xy_pos_t d = raw - level_fulcrum;
  1275. apply_rotation_xyz(inverse, d.x, d.y, raw.z);
  1276. raw = d + level_fulcrum;
  1277. #elif HAS_MESH
  1278. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1279. const float fade_scaling_factor = fade_scaling_factor_for_z(raw.z);
  1280. #elif DISABLED(MESH_BED_LEVELING)
  1281. constexpr float fade_scaling_factor = 1.0;
  1282. #endif
  1283. raw.z -= (
  1284. #if ENABLED(MESH_BED_LEVELING)
  1285. mbl.get_z(raw
  1286. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1287. , fade_scaling_factor
  1288. #endif
  1289. )
  1290. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  1291. fade_scaling_factor ? fade_scaling_factor * ubl.get_z_correction(raw) : 0.0
  1292. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  1293. fade_scaling_factor ? fade_scaling_factor * bilinear_z_offset(raw) : 0.0
  1294. #endif
  1295. );
  1296. #endif
  1297. }
  1298. }
  1299. #endif // HAS_LEVELING
  1300. #if ENABLED(FWRETRACT)
  1301. /**
  1302. * rz, e - Cartesian positions in mm
  1303. */
  1304. void Planner::apply_retract(float &rz, float &e) {
  1305. rz += fwretract.current_hop;
  1306. e -= fwretract.current_retract[active_extruder];
  1307. }
  1308. void Planner::unapply_retract(float &rz, float &e) {
  1309. rz -= fwretract.current_hop;
  1310. e += fwretract.current_retract[active_extruder];
  1311. }
  1312. #endif
  1313. void Planner::quick_stop() {
  1314. // Remove all the queued blocks. Note that this function is NOT
  1315. // called from the Stepper ISR, so we must consider tail as readonly!
  1316. // that is why we set head to tail - But there is a race condition that
  1317. // must be handled: The tail could change between the read and the assignment
  1318. // so this must be enclosed in a critical section
  1319. const bool was_enabled = stepper.suspend();
  1320. // Drop all queue entries
  1321. block_buffer_nonbusy = block_buffer_planned = block_buffer_head = block_buffer_tail;
  1322. // Restart the block delay for the first movement - As the queue was
  1323. // forced to empty, there's no risk the ISR will touch this.
  1324. delay_before_delivering = BLOCK_DELAY_FOR_1ST_MOVE;
  1325. #if HAS_SPI_LCD
  1326. // Clear the accumulated runtime
  1327. clear_block_buffer_runtime();
  1328. #endif
  1329. // Make sure to drop any attempt of queuing moves for 1 second
  1330. cleaning_buffer_counter = TEMP_TIMER_FREQUENCY;
  1331. // Reenable Stepper ISR
  1332. if (was_enabled) stepper.wake_up();
  1333. // And stop the stepper ISR
  1334. stepper.quick_stop();
  1335. }
  1336. void Planner::endstop_triggered(const AxisEnum axis) {
  1337. // Record stepper position and discard the current block
  1338. stepper.endstop_triggered(axis);
  1339. }
  1340. float Planner::triggered_position_mm(const AxisEnum axis) {
  1341. return stepper.triggered_position(axis) * steps_to_mm[axis];
  1342. }
  1343. void Planner::finish_and_disable() {
  1344. while (has_blocks_queued() || cleaning_buffer_counter) idle();
  1345. disable_all_steppers();
  1346. }
  1347. /**
  1348. * Get an axis position according to stepper position(s)
  1349. * For CORE machines apply translation from ABC to XYZ.
  1350. */
  1351. float Planner::get_axis_position_mm(const AxisEnum axis) {
  1352. float axis_steps;
  1353. #if IS_CORE
  1354. // Requesting one of the "core" axes?
  1355. if (axis == CORE_AXIS_1 || axis == CORE_AXIS_2) {
  1356. // Protect the access to the position.
  1357. const bool was_enabled = stepper.suspend();
  1358. const int32_t p1 = stepper.position(CORE_AXIS_1),
  1359. p2 = stepper.position(CORE_AXIS_2);
  1360. if (was_enabled) stepper.wake_up();
  1361. // ((a1+a2)+(a1-a2))/2 -> (a1+a2+a1-a2)/2 -> (a1+a1)/2 -> a1
  1362. // ((a1+a2)-(a1-a2))/2 -> (a1+a2-a1+a2)/2 -> (a2+a2)/2 -> a2
  1363. axis_steps = (axis == CORE_AXIS_2 ? CORESIGN(p1 - p2) : p1 + p2) * 0.5f;
  1364. }
  1365. else
  1366. axis_steps = stepper.position(axis);
  1367. #else
  1368. axis_steps = stepper.position(axis);
  1369. #endif
  1370. return axis_steps * steps_to_mm[axis];
  1371. }
  1372. /**
  1373. * Block until all buffered steps are executed / cleaned
  1374. */
  1375. void Planner::synchronize() {
  1376. while (
  1377. has_blocks_queued() || cleaning_buffer_counter
  1378. #if ENABLED(EXTERNAL_CLOSED_LOOP_CONTROLLER)
  1379. || (READ(CLOSED_LOOP_ENABLE_PIN) && !READ(CLOSED_LOOP_MOVE_COMPLETE_PIN))
  1380. #endif
  1381. ) idle();
  1382. }
  1383. /**
  1384. * Planner::_buffer_steps
  1385. *
  1386. * Add a new linear movement to the planner queue (in terms of steps).
  1387. *
  1388. * target - target position in steps units
  1389. * target_float - target position in direct (mm, degrees) units. optional
  1390. * fr_mm_s - (target) speed of the move
  1391. * extruder - target extruder
  1392. * millimeters - the length of the movement, if known
  1393. *
  1394. * Returns true if movement was properly queued, false otherwise
  1395. */
  1396. bool Planner::_buffer_steps(const xyze_long_t &target
  1397. #if HAS_POSITION_FLOAT
  1398. , const xyze_pos_t &target_float
  1399. #endif
  1400. #if HAS_DIST_MM_ARG
  1401. , const xyze_float_t &cart_dist_mm
  1402. #endif
  1403. , feedRate_t fr_mm_s, const uint8_t extruder, const float &millimeters
  1404. ) {
  1405. // If we are cleaning, do not accept queuing of movements
  1406. if (cleaning_buffer_counter) return false;
  1407. // Wait for the next available block
  1408. uint8_t next_buffer_head;
  1409. block_t * const block = get_next_free_block(next_buffer_head);
  1410. // Fill the block with the specified movement
  1411. if (!_populate_block(block, false, target
  1412. #if HAS_POSITION_FLOAT
  1413. , target_float
  1414. #endif
  1415. #if HAS_DIST_MM_ARG
  1416. , cart_dist_mm
  1417. #endif
  1418. , fr_mm_s, extruder, millimeters
  1419. )) {
  1420. // Movement was not queued, probably because it was too short.
  1421. // Simply accept that as movement queued and done
  1422. return true;
  1423. }
  1424. // If this is the first added movement, reload the delay, otherwise, cancel it.
  1425. if (block_buffer_head == block_buffer_tail) {
  1426. // If it was the first queued block, restart the 1st block delivery delay, to
  1427. // give the planner an opportunity to queue more movements and plan them
  1428. // As there are no queued movements, the Stepper ISR will not touch this
  1429. // variable, so there is no risk setting this here (but it MUST be done
  1430. // before the following line!!)
  1431. delay_before_delivering = BLOCK_DELAY_FOR_1ST_MOVE;
  1432. }
  1433. // Move buffer head
  1434. block_buffer_head = next_buffer_head;
  1435. // Recalculate and optimize trapezoidal speed profiles
  1436. recalculate();
  1437. // Movement successfully queued!
  1438. return true;
  1439. }
  1440. /**
  1441. * Planner::_populate_block
  1442. *
  1443. * Fills a new linear movement in the block (in terms of steps).
  1444. *
  1445. * target - target position in steps units
  1446. * fr_mm_s - (target) speed of the move
  1447. * extruder - target extruder
  1448. *
  1449. * Returns true is movement is acceptable, false otherwise
  1450. */
  1451. bool Planner::_populate_block(block_t * const block, bool split_move,
  1452. const abce_long_t &target
  1453. #if HAS_POSITION_FLOAT
  1454. , const xyze_pos_t &target_float
  1455. #endif
  1456. #if HAS_DIST_MM_ARG
  1457. , const xyze_float_t &cart_dist_mm
  1458. #endif
  1459. , feedRate_t fr_mm_s, const uint8_t extruder, const float &millimeters/*=0.0*/
  1460. ) {
  1461. const int32_t da = target.a - position.a,
  1462. db = target.b - position.b,
  1463. dc = target.c - position.c;
  1464. #if EXTRUDERS
  1465. int32_t de = target.e - position.e;
  1466. #else
  1467. constexpr int32_t de = 0;
  1468. #endif
  1469. /* <-- add a slash to enable
  1470. SERIAL_ECHOLNPAIR(" _populate_block FR:", fr_mm_s,
  1471. " A:", target.a, " (", da, " steps)"
  1472. " B:", target.b, " (", db, " steps)"
  1473. " C:", target.c, " (", dc, " steps)"
  1474. #if EXTRUDERS
  1475. " E:", target.e, " (", de, " steps)"
  1476. #endif
  1477. );
  1478. //*/
  1479. #if EITHER(PREVENT_COLD_EXTRUSION, PREVENT_LENGTHY_EXTRUDE)
  1480. if (de) {
  1481. #if ENABLED(PREVENT_COLD_EXTRUSION)
  1482. if (thermalManager.tooColdToExtrude(extruder)) {
  1483. position.e = target.e; // Behave as if the move really took place, but ignore E part
  1484. TERN_(HAS_POSITION_FLOAT, position_float.e = target_float.e);
  1485. de = 0; // no difference
  1486. SERIAL_ECHO_MSG(STR_ERR_COLD_EXTRUDE_STOP);
  1487. }
  1488. #endif // PREVENT_COLD_EXTRUSION
  1489. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  1490. const float e_steps = ABS(de * e_factor[extruder]);
  1491. const float max_e_steps = settings.axis_steps_per_mm[E_AXIS_N(extruder)] * (EXTRUDE_MAXLENGTH);
  1492. if (e_steps > max_e_steps) {
  1493. #if ENABLED(MIXING_EXTRUDER)
  1494. bool ignore_e = false;
  1495. float collector[MIXING_STEPPERS];
  1496. mixer.refresh_collector(1.0, mixer.get_current_vtool(), collector);
  1497. MIXER_STEPPER_LOOP(e)
  1498. if (e_steps * collector[e] > max_e_steps) { ignore_e = true; break; }
  1499. #else
  1500. constexpr bool ignore_e = true;
  1501. #endif
  1502. if (ignore_e) {
  1503. position.e = target.e; // Behave as if the move really took place, but ignore E part
  1504. TERN_(HAS_POSITION_FLOAT, position_float.e = target_float.e);
  1505. de = 0; // no difference
  1506. SERIAL_ECHO_MSG(STR_ERR_LONG_EXTRUDE_STOP);
  1507. }
  1508. }
  1509. #endif // PREVENT_LENGTHY_EXTRUDE
  1510. }
  1511. #endif // PREVENT_COLD_EXTRUSION || PREVENT_LENGTHY_EXTRUDE
  1512. // Compute direction bit-mask for this block
  1513. uint8_t dm = 0;
  1514. #if CORE_IS_XY
  1515. if (da < 0) SBI(dm, X_HEAD); // Save the real Extruder (head) direction in X Axis
  1516. if (db < 0) SBI(dm, Y_HEAD); // ...and Y
  1517. if (dc < 0) SBI(dm, Z_AXIS);
  1518. if (da + db < 0) SBI(dm, A_AXIS); // Motor A direction
  1519. if (CORESIGN(da - db) < 0) SBI(dm, B_AXIS); // Motor B direction
  1520. #elif CORE_IS_XZ
  1521. if (da < 0) SBI(dm, X_HEAD); // Save the real Extruder (head) direction in X Axis
  1522. if (db < 0) SBI(dm, Y_AXIS);
  1523. if (dc < 0) SBI(dm, Z_HEAD); // ...and Z
  1524. if (da + dc < 0) SBI(dm, A_AXIS); // Motor A direction
  1525. if (CORESIGN(da - dc) < 0) SBI(dm, C_AXIS); // Motor C direction
  1526. #elif CORE_IS_YZ
  1527. if (da < 0) SBI(dm, X_AXIS);
  1528. if (db < 0) SBI(dm, Y_HEAD); // Save the real Extruder (head) direction in Y Axis
  1529. if (dc < 0) SBI(dm, Z_HEAD); // ...and Z
  1530. if (db + dc < 0) SBI(dm, B_AXIS); // Motor B direction
  1531. if (CORESIGN(db - dc) < 0) SBI(dm, C_AXIS); // Motor C direction
  1532. #else
  1533. if (da < 0) SBI(dm, X_AXIS);
  1534. if (db < 0) SBI(dm, Y_AXIS);
  1535. if (dc < 0) SBI(dm, Z_AXIS);
  1536. #endif
  1537. if (de < 0) SBI(dm, E_AXIS);
  1538. #if EXTRUDERS
  1539. const float esteps_float = de * e_factor[extruder];
  1540. const uint32_t esteps = ABS(esteps_float) + 0.5f;
  1541. #else
  1542. constexpr uint32_t esteps = 0;
  1543. #endif
  1544. // Clear all flags, including the "busy" bit
  1545. block->flag = 0x00;
  1546. // Set direction bits
  1547. block->direction_bits = dm;
  1548. // Update block laser power
  1549. #if ENABLED(LASER_POWER_INLINE)
  1550. block->laser.status = settings.laser.status;
  1551. block->laser.power = settings.laser.power;
  1552. #endif
  1553. // Number of steps for each axis
  1554. // See http://www.corexy.com/theory.html
  1555. #if CORE_IS_XY
  1556. block->steps.set(ABS(da + db), ABS(da - db), ABS(dc));
  1557. #elif CORE_IS_XZ
  1558. block->steps.set(ABS(da + dc), ABS(db), ABS(da - dc));
  1559. #elif CORE_IS_YZ
  1560. block->steps.set(ABS(da), ABS(db + dc), ABS(db - dc));
  1561. #elif IS_SCARA
  1562. block->steps.set(ABS(da), ABS(db), ABS(dc));
  1563. #else
  1564. // default non-h-bot planning
  1565. block->steps.set(ABS(da), ABS(db), ABS(dc));
  1566. #endif
  1567. /**
  1568. * This part of the code calculates the total length of the movement.
  1569. * For cartesian bots, the X_AXIS is the real X movement and same for Y_AXIS.
  1570. * But for corexy bots, that is not true. The "X_AXIS" and "Y_AXIS" motors (that should be named to A_AXIS
  1571. * and B_AXIS) cannot be used for X and Y length, because A=X+Y and B=X-Y.
  1572. * So we need to create other 2 "AXIS", named X_HEAD and Y_HEAD, meaning the real displacement of the Head.
  1573. * Having the real displacement of the head, we can calculate the total movement length and apply the desired speed.
  1574. */
  1575. struct DistanceMM : abce_float_t {
  1576. TERN_(IS_CORE, xyz_pos_t head);
  1577. } steps_dist_mm;
  1578. #if IS_CORE
  1579. #if CORE_IS_XY
  1580. steps_dist_mm.head.x = da * steps_to_mm[A_AXIS];
  1581. steps_dist_mm.head.y = db * steps_to_mm[B_AXIS];
  1582. steps_dist_mm.z = dc * steps_to_mm[Z_AXIS];
  1583. steps_dist_mm.a = (da + db) * steps_to_mm[A_AXIS];
  1584. steps_dist_mm.b = CORESIGN(da - db) * steps_to_mm[B_AXIS];
  1585. #elif CORE_IS_XZ
  1586. steps_dist_mm.head.x = da * steps_to_mm[A_AXIS];
  1587. steps_dist_mm.y = db * steps_to_mm[Y_AXIS];
  1588. steps_dist_mm.head.z = dc * steps_to_mm[C_AXIS];
  1589. steps_dist_mm.a = (da + dc) * steps_to_mm[A_AXIS];
  1590. steps_dist_mm.c = CORESIGN(da - dc) * steps_to_mm[C_AXIS];
  1591. #elif CORE_IS_YZ
  1592. steps_dist_mm.x = da * steps_to_mm[X_AXIS];
  1593. steps_dist_mm.head.y = db * steps_to_mm[B_AXIS];
  1594. steps_dist_mm.head.z = dc * steps_to_mm[C_AXIS];
  1595. steps_dist_mm.b = (db + dc) * steps_to_mm[B_AXIS];
  1596. steps_dist_mm.c = CORESIGN(db - dc) * steps_to_mm[C_AXIS];
  1597. #endif
  1598. #else
  1599. steps_dist_mm.a = da * steps_to_mm[A_AXIS];
  1600. steps_dist_mm.b = db * steps_to_mm[B_AXIS];
  1601. steps_dist_mm.c = dc * steps_to_mm[C_AXIS];
  1602. #endif
  1603. #if EXTRUDERS
  1604. steps_dist_mm.e = esteps_float * steps_to_mm[E_AXIS_N(extruder)];
  1605. #else
  1606. steps_dist_mm.e = 0.0f;
  1607. #endif
  1608. TERN_(LCD_SHOW_E_TOTAL, e_move_accumulator += steps_dist_mm.e);
  1609. if (block->steps.a < MIN_STEPS_PER_SEGMENT && block->steps.b < MIN_STEPS_PER_SEGMENT && block->steps.c < MIN_STEPS_PER_SEGMENT) {
  1610. block->millimeters = (0
  1611. #if EXTRUDERS
  1612. + ABS(steps_dist_mm.e)
  1613. #endif
  1614. );
  1615. }
  1616. else {
  1617. if (millimeters)
  1618. block->millimeters = millimeters;
  1619. else
  1620. block->millimeters = SQRT(
  1621. #if CORE_IS_XY
  1622. sq(steps_dist_mm.head.x) + sq(steps_dist_mm.head.y) + sq(steps_dist_mm.z)
  1623. #elif CORE_IS_XZ
  1624. sq(steps_dist_mm.head.x) + sq(steps_dist_mm.y) + sq(steps_dist_mm.head.z)
  1625. #elif CORE_IS_YZ
  1626. sq(steps_dist_mm.x) + sq(steps_dist_mm.head.y) + sq(steps_dist_mm.head.z)
  1627. #else
  1628. sq(steps_dist_mm.x) + sq(steps_dist_mm.y) + sq(steps_dist_mm.z)
  1629. #endif
  1630. );
  1631. /**
  1632. * At this point at least one of the axes has more steps than
  1633. * MIN_STEPS_PER_SEGMENT, ensuring the segment won't get dropped as
  1634. * zero-length. It's important to not apply corrections
  1635. * to blocks that would get dropped!
  1636. *
  1637. * A correction function is permitted to add steps to an axis, it
  1638. * should *never* remove steps!
  1639. */
  1640. TERN_(BACKLASH_COMPENSATION, backlash.add_correction_steps(da, db, dc, dm, block));
  1641. }
  1642. #if EXTRUDERS
  1643. block->steps.e = esteps;
  1644. #endif
  1645. block->step_event_count = _MAX(block->steps.a, block->steps.b, block->steps.c, esteps);
  1646. // Bail if this is a zero-length block
  1647. if (block->step_event_count < MIN_STEPS_PER_SEGMENT) return false;
  1648. #if ENABLED(MIXING_EXTRUDER)
  1649. MIXER_POPULATE_BLOCK();
  1650. #endif
  1651. TERN_(HAS_CUTTER, block->cutter_power = cutter.power);
  1652. #if HAS_FAN
  1653. FANS_LOOP(i) block->fan_speed[i] = thermalManager.fan_speed[i];
  1654. #endif
  1655. #if ENABLED(BARICUDA)
  1656. block->valve_pressure = baricuda_valve_pressure;
  1657. block->e_to_p_pressure = baricuda_e_to_p_pressure;
  1658. #endif
  1659. #if EXTRUDERS > 1
  1660. block->extruder = extruder;
  1661. #endif
  1662. #if ENABLED(AUTO_POWER_CONTROL)
  1663. if (block->steps.x || block->steps.y || block->steps.z)
  1664. powerManager.power_on();
  1665. #endif
  1666. // Enable active axes
  1667. #if CORE_IS_XY
  1668. if (block->steps.a || block->steps.b) {
  1669. ENABLE_AXIS_X();
  1670. ENABLE_AXIS_Y();
  1671. }
  1672. #if DISABLED(Z_LATE_ENABLE)
  1673. if (block->steps.z) ENABLE_AXIS_Z();
  1674. #endif
  1675. #elif CORE_IS_XZ
  1676. if (block->steps.a || block->steps.c) {
  1677. ENABLE_AXIS_X();
  1678. ENABLE_AXIS_Z();
  1679. }
  1680. if (block->steps.y) ENABLE_AXIS_Y();
  1681. #elif CORE_IS_YZ
  1682. if (block->steps.b || block->steps.c) {
  1683. ENABLE_AXIS_Y();
  1684. ENABLE_AXIS_Z();
  1685. }
  1686. if (block->steps.x) ENABLE_AXIS_X();
  1687. #else
  1688. if (block->steps.x) ENABLE_AXIS_X();
  1689. if (block->steps.y) ENABLE_AXIS_Y();
  1690. #if DISABLED(Z_LATE_ENABLE)
  1691. if (block->steps.z) ENABLE_AXIS_Z();
  1692. #endif
  1693. #endif
  1694. // Enable extruder(s)
  1695. #if EXTRUDERS
  1696. if (esteps) {
  1697. TERN_(AUTO_POWER_CONTROL, powerManager.power_on());
  1698. #if ENABLED(DISABLE_INACTIVE_EXTRUDER) // Enable only the selected extruder
  1699. LOOP_L_N(i, EXTRUDERS)
  1700. if (g_uc_extruder_last_move[i] > 0) g_uc_extruder_last_move[i]--;
  1701. #if HAS_DUPLICATION_MODE
  1702. if (extruder_duplication_enabled && extruder == 0) {
  1703. ENABLE_AXIS_E1();
  1704. g_uc_extruder_last_move[1] = (BLOCK_BUFFER_SIZE) * 2;
  1705. }
  1706. #endif
  1707. #define ENABLE_ONE_E(N) do{ \
  1708. if (extruder == N) { \
  1709. ENABLE_AXIS_E##N(); \
  1710. g_uc_extruder_last_move[N] = (BLOCK_BUFFER_SIZE) * 2; \
  1711. } \
  1712. else if (!g_uc_extruder_last_move[N]) \
  1713. DISABLE_AXIS_E##N(); \
  1714. }while(0);
  1715. #else
  1716. #define ENABLE_ONE_E(N) ENABLE_AXIS_E##N();
  1717. #endif
  1718. REPEAT(EXTRUDERS, ENABLE_ONE_E); // (ENABLE_ONE_E must end with semicolon)
  1719. }
  1720. #endif // EXTRUDERS
  1721. if (esteps)
  1722. NOLESS(fr_mm_s, settings.min_feedrate_mm_s);
  1723. else
  1724. NOLESS(fr_mm_s, settings.min_travel_feedrate_mm_s);
  1725. const float inverse_millimeters = 1.0f / block->millimeters; // Inverse millimeters to remove multiple divides
  1726. // Calculate inverse time for this move. No divide by zero due to previous checks.
  1727. // Example: At 120mm/s a 60mm move takes 0.5s. So this will give 2.0.
  1728. float inverse_secs = fr_mm_s * inverse_millimeters;
  1729. // Get the number of non busy movements in queue (non busy means that they can be altered)
  1730. const uint8_t moves_queued = nonbusy_movesplanned();
  1731. // Slow down when the buffer starts to empty, rather than wait at the corner for a buffer refill
  1732. #if EITHER(SLOWDOWN, ULTRA_LCD) || defined(XY_FREQUENCY_LIMIT)
  1733. // Segment time im micro seconds
  1734. uint32_t segment_time_us = LROUND(1000000.0f / inverse_secs);
  1735. #endif
  1736. #if ENABLED(SLOWDOWN)
  1737. #ifndef SLOWDOWN_DIVISOR
  1738. #define SLOWDOWN_DIVISOR 2
  1739. #endif
  1740. if (WITHIN(moves_queued, 2, (BLOCK_BUFFER_SIZE) / (SLOWDOWN_DIVISOR) - 1)) {
  1741. if (segment_time_us < settings.min_segment_time_us) {
  1742. // buffer is draining, add extra time. The amount of time added increases if the buffer is still emptied more.
  1743. const uint32_t nst = segment_time_us + LROUND(2 * (settings.min_segment_time_us - segment_time_us) / moves_queued);
  1744. inverse_secs = 1000000.0f / nst;
  1745. #if defined(XY_FREQUENCY_LIMIT) || HAS_SPI_LCD
  1746. segment_time_us = nst;
  1747. #endif
  1748. }
  1749. }
  1750. #endif
  1751. #if HAS_SPI_LCD
  1752. // Protect the access to the position.
  1753. const bool was_enabled = stepper.suspend();
  1754. block_buffer_runtime_us += segment_time_us;
  1755. block->segment_time_us = segment_time_us;
  1756. if (was_enabled) stepper.wake_up();
  1757. #endif
  1758. block->nominal_speed_sqr = sq(block->millimeters * inverse_secs); // (mm/sec)^2 Always > 0
  1759. block->nominal_rate = CEIL(block->step_event_count * inverse_secs); // (step/sec) Always > 0
  1760. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  1761. if (extruder == FILAMENT_SENSOR_EXTRUDER_NUM) // Only for extruder with filament sensor
  1762. filwidth.advance_e(steps_dist_mm.e);
  1763. #endif
  1764. // Calculate and limit speed in mm/sec
  1765. xyze_float_t current_speed;
  1766. float speed_factor = 1.0f; // factor <1 decreases speed
  1767. // Linear axes first with less logic
  1768. LOOP_XYZ(i) {
  1769. current_speed[i] = steps_dist_mm[i] * inverse_secs;
  1770. const feedRate_t cs = ABS(current_speed[i]),
  1771. max_fr = settings.max_feedrate_mm_s[i];
  1772. if (cs > max_fr) NOMORE(speed_factor, max_fr / cs);
  1773. }
  1774. // Limit speed on extruders, if any
  1775. #if EXTRUDERS
  1776. {
  1777. current_speed.e = steps_dist_mm.e * inverse_secs;
  1778. #if HAS_MIXER_SYNC_CHANNEL
  1779. // Move all mixing extruders at the specified rate
  1780. if (mixer.get_current_vtool() == MIXER_AUTORETRACT_TOOL)
  1781. current_speed.e *= MIXING_STEPPERS;
  1782. #endif
  1783. const feedRate_t cs = ABS(current_speed.e),
  1784. max_fr = settings.max_feedrate_mm_s[E_AXIS_N(extruder)]
  1785. * TERN(HAS_MIXER_SYNC_CHANNEL, MIXING_STEPPERS, 1);
  1786. if (cs > max_fr) NOMORE(speed_factor, max_fr / cs);
  1787. }
  1788. #endif
  1789. // Max segment time in µs.
  1790. #ifdef XY_FREQUENCY_LIMIT
  1791. // Check and limit the xy direction change frequency
  1792. const unsigned char direction_change = block->direction_bits ^ old_direction_bits;
  1793. old_direction_bits = block->direction_bits;
  1794. segment_time_us = LROUND((float)segment_time_us / speed_factor);
  1795. uint32_t xs0 = axis_segment_time_us[0].x,
  1796. xs1 = axis_segment_time_us[1].x,
  1797. xs2 = axis_segment_time_us[2].x,
  1798. ys0 = axis_segment_time_us[0].y,
  1799. ys1 = axis_segment_time_us[1].y,
  1800. ys2 = axis_segment_time_us[2].y;
  1801. if (TEST(direction_change, X_AXIS)) {
  1802. xs2 = axis_segment_time_us[2].x = xs1;
  1803. xs1 = axis_segment_time_us[1].x = xs0;
  1804. xs0 = 0;
  1805. }
  1806. xs0 = axis_segment_time_us[0].x = xs0 + segment_time_us;
  1807. if (TEST(direction_change, Y_AXIS)) {
  1808. ys2 = axis_segment_time_us[2].y = axis_segment_time_us[1].y;
  1809. ys1 = axis_segment_time_us[1].y = axis_segment_time_us[0].y;
  1810. ys0 = 0;
  1811. }
  1812. ys0 = axis_segment_time_us[0].y = ys0 + segment_time_us;
  1813. const uint32_t max_x_segment_time = _MAX(xs0, xs1, xs2),
  1814. max_y_segment_time = _MAX(ys0, ys1, ys2),
  1815. min_xy_segment_time = _MIN(max_x_segment_time, max_y_segment_time);
  1816. if (min_xy_segment_time < MAX_FREQ_TIME_US) {
  1817. const float low_sf = speed_factor * min_xy_segment_time / (MAX_FREQ_TIME_US);
  1818. NOMORE(speed_factor, low_sf);
  1819. }
  1820. #endif // XY_FREQUENCY_LIMIT
  1821. // Correct the speed
  1822. if (speed_factor < 1.0f) {
  1823. current_speed *= speed_factor;
  1824. block->nominal_rate *= speed_factor;
  1825. block->nominal_speed_sqr = block->nominal_speed_sqr * sq(speed_factor);
  1826. }
  1827. // Compute and limit the acceleration rate for the trapezoid generator.
  1828. const float steps_per_mm = block->step_event_count * inverse_millimeters;
  1829. uint32_t accel;
  1830. if (!block->steps.a && !block->steps.b && !block->steps.c) {
  1831. // convert to: acceleration steps/sec^2
  1832. accel = CEIL(settings.retract_acceleration * steps_per_mm);
  1833. TERN_(LIN_ADVANCE, block->use_advance_lead = false);
  1834. }
  1835. else {
  1836. #define LIMIT_ACCEL_LONG(AXIS,INDX) do{ \
  1837. if (block->steps[AXIS] && max_acceleration_steps_per_s2[AXIS+INDX] < accel) { \
  1838. const uint32_t comp = max_acceleration_steps_per_s2[AXIS+INDX] * block->step_event_count; \
  1839. if (accel * block->steps[AXIS] > comp) accel = comp / block->steps[AXIS]; \
  1840. } \
  1841. }while(0)
  1842. #define LIMIT_ACCEL_FLOAT(AXIS,INDX) do{ \
  1843. if (block->steps[AXIS] && max_acceleration_steps_per_s2[AXIS+INDX] < accel) { \
  1844. const float comp = (float)max_acceleration_steps_per_s2[AXIS+INDX] * (float)block->step_event_count; \
  1845. if ((float)accel * (float)block->steps[AXIS] > comp) accel = comp / (float)block->steps[AXIS]; \
  1846. } \
  1847. }while(0)
  1848. // Start with print or travel acceleration
  1849. accel = CEIL((esteps ? settings.acceleration : settings.travel_acceleration) * steps_per_mm);
  1850. #if ENABLED(LIN_ADVANCE)
  1851. #if HAS_JUNCTION_DEVIATION
  1852. #if ENABLED(DISTINCT_E_FACTORS)
  1853. #define MAX_E_JERK max_e_jerk[extruder]
  1854. #else
  1855. #define MAX_E_JERK max_e_jerk
  1856. #endif
  1857. #else
  1858. #define MAX_E_JERK max_jerk.e
  1859. #endif
  1860. /**
  1861. *
  1862. * Use LIN_ADVANCE for blocks if all these are true:
  1863. *
  1864. * esteps : This is a print move, because we checked for A, B, C steps before.
  1865. *
  1866. * extruder_advance_K[active_extruder] : There is an advance factor set for this extruder.
  1867. *
  1868. * de > 0 : Extruder is running forward (e.g., for "Wipe while retracting" (Slic3r) or "Combing" (Cura) moves)
  1869. */
  1870. block->use_advance_lead = esteps
  1871. && extruder_advance_K[active_extruder]
  1872. && de > 0;
  1873. if (block->use_advance_lead) {
  1874. block->e_D_ratio = (target_float.e - position_float.e) /
  1875. #if IS_KINEMATIC
  1876. block->millimeters
  1877. #else
  1878. SQRT(sq(target_float.x - position_float.x)
  1879. + sq(target_float.y - position_float.y)
  1880. + sq(target_float.z - position_float.z))
  1881. #endif
  1882. ;
  1883. // 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!
  1884. // 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.
  1885. if (block->e_D_ratio > 3.0f)
  1886. block->use_advance_lead = false;
  1887. else {
  1888. const uint32_t max_accel_steps_per_s2 = MAX_E_JERK / (extruder_advance_K[active_extruder] * block->e_D_ratio) * steps_per_mm;
  1889. if (TERN0(LA_DEBUG, accel > max_accel_steps_per_s2))
  1890. SERIAL_ECHOLNPGM("Acceleration limited.");
  1891. NOMORE(accel, max_accel_steps_per_s2);
  1892. }
  1893. }
  1894. #endif
  1895. #if ENABLED(DISTINCT_E_FACTORS)
  1896. #define ACCEL_IDX extruder
  1897. #else
  1898. #define ACCEL_IDX 0
  1899. #endif
  1900. // Limit acceleration per axis
  1901. if (block->step_event_count <= cutoff_long) {
  1902. LIMIT_ACCEL_LONG(A_AXIS, 0);
  1903. LIMIT_ACCEL_LONG(B_AXIS, 0);
  1904. LIMIT_ACCEL_LONG(C_AXIS, 0);
  1905. LIMIT_ACCEL_LONG(E_AXIS, ACCEL_IDX);
  1906. }
  1907. else {
  1908. LIMIT_ACCEL_FLOAT(A_AXIS, 0);
  1909. LIMIT_ACCEL_FLOAT(B_AXIS, 0);
  1910. LIMIT_ACCEL_FLOAT(C_AXIS, 0);
  1911. LIMIT_ACCEL_FLOAT(E_AXIS, ACCEL_IDX);
  1912. }
  1913. }
  1914. block->acceleration_steps_per_s2 = accel;
  1915. block->acceleration = accel / steps_per_mm;
  1916. #if DISABLED(S_CURVE_ACCELERATION)
  1917. block->acceleration_rate = (uint32_t)(accel * (4096.0f * 4096.0f / (STEPPER_TIMER_RATE)));
  1918. #endif
  1919. #if ENABLED(LIN_ADVANCE)
  1920. if (block->use_advance_lead) {
  1921. 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)]);
  1922. #if ENABLED(LA_DEBUG)
  1923. if (extruder_advance_K[active_extruder] * block->e_D_ratio * block->acceleration * 2 < SQRT(block->nominal_speed_sqr) * block->e_D_ratio)
  1924. SERIAL_ECHOLNPGM("More than 2 steps per eISR loop executed.");
  1925. if (block->advance_speed < 200)
  1926. SERIAL_ECHOLNPGM("eISR running at > 10kHz.");
  1927. #endif
  1928. }
  1929. #endif
  1930. float vmax_junction_sqr; // Initial limit on the segment entry velocity (mm/s)^2
  1931. #if HAS_JUNCTION_DEVIATION
  1932. /**
  1933. * Compute maximum allowable entry speed at junction by centripetal acceleration approximation.
  1934. * Let a circle be tangent to both previous and current path line segments, where the junction
  1935. * deviation is defined as the distance from the junction to the closest edge of the circle,
  1936. * colinear with the circle center. The circular segment joining the two paths represents the
  1937. * path of centripetal acceleration. Solve for max velocity based on max acceleration about the
  1938. * radius of the circle, defined indirectly by junction deviation. This may be also viewed as
  1939. * path width or max_jerk in the previous Grbl version. This approach does not actually deviate
  1940. * from path, but used as a robust way to compute cornering speeds, as it takes into account the
  1941. * nonlinearities of both the junction angle and junction velocity.
  1942. *
  1943. * NOTE: If the junction deviation value is finite, Grbl executes the motions in an exact path
  1944. * mode (G61). If the junction deviation value is zero, Grbl will execute the motion in an exact
  1945. * stop mode (G61.1) manner. In the future, if continuous mode (G64) is desired, the math here
  1946. * is exactly the same. Instead of motioning all the way to junction point, the machine will
  1947. * just follow the arc circle defined here. The Arduino doesn't have the CPU cycles to perform
  1948. * a continuous mode path, but ARM-based microcontrollers most certainly do.
  1949. *
  1950. * NOTE: The max junction speed is a fixed value, since machine acceleration limits cannot be
  1951. * changed dynamically during operation nor can the line move geometry. This must be kept in
  1952. * memory in the event of a feedrate override changing the nominal speeds of blocks, which can
  1953. * change the overall maximum entry speed conditions of all blocks.
  1954. *
  1955. * #######
  1956. * https://github.com/MarlinFirmware/Marlin/issues/10341#issuecomment-388191754
  1957. *
  1958. * hoffbaked: on May 10 2018 tuned and improved the GRBL algorithm for Marlin:
  1959. Okay! It seems to be working good. I somewhat arbitrarily cut it off at 1mm
  1960. on then on anything with less sides than an octagon. With this, and the
  1961. reverse pass actually recalculating things, a corner acceleration value
  1962. of 1000 junction deviation of .05 are pretty reasonable. If the cycles
  1963. can be spared, a better acos could be used. For all I know, it may be
  1964. already calculated in a different place. */
  1965. // Unit vector of previous path line segment
  1966. static xyze_float_t prev_unit_vec;
  1967. xyze_float_t unit_vec =
  1968. #if HAS_DIST_MM_ARG
  1969. cart_dist_mm
  1970. #else
  1971. { steps_dist_mm.x, steps_dist_mm.y, steps_dist_mm.z, steps_dist_mm.e }
  1972. #endif
  1973. ;
  1974. unit_vec *= inverse_millimeters;
  1975. #if IS_CORE && HAS_JUNCTION_DEVIATION
  1976. /**
  1977. * On CoreXY the length of the vector [A,B] is SQRT(2) times the length of the head movement vector [X,Y].
  1978. * So taking Z and E into account, we cannot scale to a unit vector with "inverse_millimeters".
  1979. * => normalize the complete junction vector
  1980. */
  1981. normalize_junction_vector(unit_vec);
  1982. #endif
  1983. // Skip first block or when previous_nominal_speed is used as a flag for homing and offset cycles.
  1984. if (moves_queued && !UNEAR_ZERO(previous_nominal_speed_sqr)) {
  1985. // Compute cosine of angle between previous and current path. (prev_unit_vec is negative)
  1986. // NOTE: Max junction velocity is computed without sin() or acos() by trig half angle identity.
  1987. float junction_cos_theta = (-prev_unit_vec.x * unit_vec.x) + (-prev_unit_vec.y * unit_vec.y)
  1988. + (-prev_unit_vec.z * unit_vec.z) + (-prev_unit_vec.e * unit_vec.e);
  1989. // NOTE: Computed without any expensive trig, sin() or acos(), by trig half angle identity of cos(theta).
  1990. if (junction_cos_theta > 0.999999f) {
  1991. // For a 0 degree acute junction, just set minimum junction speed.
  1992. vmax_junction_sqr = sq(float(MINIMUM_PLANNER_SPEED));
  1993. }
  1994. else {
  1995. NOLESS(junction_cos_theta, -0.999999f); // Check for numerical round-off to avoid divide by zero.
  1996. // Convert delta vector to unit vector
  1997. xyze_float_t junction_unit_vec = unit_vec - prev_unit_vec;
  1998. normalize_junction_vector(junction_unit_vec);
  1999. const float junction_acceleration = limit_value_by_axis_maximum(block->acceleration, junction_unit_vec),
  2000. sin_theta_d2 = SQRT(0.5f * (1.0f - junction_cos_theta)); // Trig half angle identity. Always positive.
  2001. vmax_junction_sqr = (junction_acceleration * junction_deviation_mm * sin_theta_d2) / (1.0f - sin_theta_d2);
  2002. if (block->millimeters < 1) {
  2003. // Fast acos approximation (max. error +-0.033 rads)
  2004. // Based on MinMax polynomial published by W. Randolph Franklin, see
  2005. // https://wrf.ecse.rpi.edu/Research/Short_Notes/arcsin/onlyelem.html
  2006. // (acos(x) = pi / 2 - asin(x))
  2007. const float neg = junction_cos_theta < 0 ? -1 : 1,
  2008. t = neg * junction_cos_theta,
  2009. asinx = 0.032843707f
  2010. + t * (-1.451838349f
  2011. + t * ( 29.66153956f
  2012. + t * (-131.1123477f
  2013. + t * ( 262.8130562f
  2014. + t * (-242.7199627f + t * 84.31466202f) )))),
  2015. junction_theta = RADIANS(90) - neg * asinx;
  2016. // If angle is greater than 135 degrees (octagon), find speed for approximate arc
  2017. if (junction_theta > RADIANS(135)) {
  2018. // NOTE: MinMax acos approximation and thereby also junction_theta top out at pi-0.033, which avoids division by 0
  2019. const float limit_sqr = block->millimeters / (RADIANS(180) - junction_theta) * junction_acceleration;
  2020. NOMORE(vmax_junction_sqr, limit_sqr);
  2021. }
  2022. }
  2023. }
  2024. // Get the lowest speed
  2025. vmax_junction_sqr = _MIN(vmax_junction_sqr, block->nominal_speed_sqr, previous_nominal_speed_sqr);
  2026. }
  2027. else // Init entry speed to zero. Assume it starts from rest. Planner will correct this later.
  2028. vmax_junction_sqr = 0;
  2029. prev_unit_vec = unit_vec;
  2030. #endif
  2031. #ifdef USE_CACHED_SQRT
  2032. #define CACHED_SQRT(N, V) \
  2033. static float saved_V, N; \
  2034. if (V != saved_V) { N = SQRT(V); saved_V = V; }
  2035. #else
  2036. #define CACHED_SQRT(N, V) const float N = SQRT(V)
  2037. #endif
  2038. #if HAS_CLASSIC_JERK
  2039. /**
  2040. * Adapted from Průša MKS firmware
  2041. * https://github.com/prusa3d/Prusa-Firmware
  2042. */
  2043. CACHED_SQRT(nominal_speed, block->nominal_speed_sqr);
  2044. // Exit speed limited by a jerk to full halt of a previous last segment
  2045. static float previous_safe_speed;
  2046. // Start with a safe speed (from which the machine may halt to stop immediately).
  2047. float safe_speed = nominal_speed;
  2048. #ifdef TRAVEL_EXTRA_XYJERK
  2049. const float extra_xyjerk = (de <= 0) ? TRAVEL_EXTRA_XYJERK : 0;
  2050. #else
  2051. constexpr float extra_xyjerk = 0;
  2052. #endif
  2053. uint8_t limited = 0;
  2054. TERN(HAS_LINEAR_E_JERK, LOOP_XYZ, LOOP_XYZE)(i) {
  2055. const float jerk = ABS(current_speed[i]), // cs : Starting from zero, change in speed for this axis
  2056. maxj = (max_jerk[i] + (i == X_AXIS || i == Y_AXIS ? extra_xyjerk : 0.0f)); // mj : The max jerk setting for this axis
  2057. if (jerk > maxj) { // cs > mj : New current speed too fast?
  2058. if (limited) { // limited already?
  2059. const float mjerk = nominal_speed * maxj; // ns*mj
  2060. if (jerk * safe_speed > mjerk) safe_speed = mjerk / jerk; // ns*mj/cs
  2061. }
  2062. else {
  2063. safe_speed *= maxj / jerk; // Initial limit: ns*mj/cs
  2064. ++limited; // Initially limited
  2065. }
  2066. }
  2067. }
  2068. float vmax_junction;
  2069. if (moves_queued && !UNEAR_ZERO(previous_nominal_speed_sqr)) {
  2070. // Estimate a maximum velocity allowed at a joint of two successive segments.
  2071. // If this maximum velocity allowed is lower than the minimum of the entry / exit safe velocities,
  2072. // then the machine is not coasting anymore and the safe entry / exit velocities shall be used.
  2073. // Factor to multiply the previous / current nominal velocities to get componentwise limited velocities.
  2074. float v_factor = 1;
  2075. limited = 0;
  2076. // The junction velocity will be shared between successive segments. Limit the junction velocity to their minimum.
  2077. // Pick the smaller of the nominal speeds. Higher speed shall not be achieved at the junction during coasting.
  2078. CACHED_SQRT(previous_nominal_speed, previous_nominal_speed_sqr);
  2079. vmax_junction = _MIN(nominal_speed, previous_nominal_speed);
  2080. // Now limit the jerk in all axes.
  2081. const float smaller_speed_factor = vmax_junction / previous_nominal_speed;
  2082. #if HAS_LINEAR_E_JERK
  2083. LOOP_XYZ(axis)
  2084. #else
  2085. LOOP_XYZE(axis)
  2086. #endif
  2087. {
  2088. // Limit an axis. We have to differentiate: coasting, reversal of an axis, full stop.
  2089. float v_exit = previous_speed[axis] * smaller_speed_factor,
  2090. v_entry = current_speed[axis];
  2091. if (limited) {
  2092. v_exit *= v_factor;
  2093. v_entry *= v_factor;
  2094. }
  2095. // Calculate jerk depending on whether the axis is coasting in the same direction or reversing.
  2096. const float jerk = (v_exit > v_entry)
  2097. ? // coasting axis reversal
  2098. ( (v_entry > 0 || v_exit < 0) ? (v_exit - v_entry) : _MAX(v_exit, -v_entry) )
  2099. : // v_exit <= v_entry coasting axis reversal
  2100. ( (v_entry < 0 || v_exit > 0) ? (v_entry - v_exit) : _MAX(-v_exit, v_entry) );
  2101. const float maxj = (max_jerk[axis] + (axis == X_AXIS || axis == Y_AXIS ? extra_xyjerk : 0.0f));
  2102. if (jerk > maxj) {
  2103. v_factor *= maxj / jerk;
  2104. ++limited;
  2105. }
  2106. }
  2107. if (limited) vmax_junction *= v_factor;
  2108. // Now the transition velocity is known, which maximizes the shared exit / entry velocity while
  2109. // respecting the jerk factors, it may be possible, that applying separate safe exit / entry velocities will achieve faster prints.
  2110. const float vmax_junction_threshold = vmax_junction * 0.99f;
  2111. if (previous_safe_speed > vmax_junction_threshold && safe_speed > vmax_junction_threshold)
  2112. vmax_junction = safe_speed;
  2113. }
  2114. else
  2115. vmax_junction = safe_speed;
  2116. previous_safe_speed = safe_speed;
  2117. #if HAS_JUNCTION_DEVIATION
  2118. vmax_junction_sqr = _MIN(vmax_junction_sqr, sq(vmax_junction));
  2119. #else
  2120. vmax_junction_sqr = sq(vmax_junction);
  2121. #endif
  2122. #endif // Classic Jerk Limiting
  2123. // Max entry speed of this block equals the max exit speed of the previous block.
  2124. block->max_entry_speed_sqr = vmax_junction_sqr;
  2125. // Initialize block entry speed. Compute based on deceleration to user-defined MINIMUM_PLANNER_SPEED.
  2126. const float v_allowable_sqr = max_allowable_speed_sqr(-block->acceleration, sq(float(MINIMUM_PLANNER_SPEED)), block->millimeters);
  2127. // If we are trying to add a split block, start with the
  2128. // max. allowed speed to avoid an interrupted first move.
  2129. block->entry_speed_sqr = !split_move ? sq(float(MINIMUM_PLANNER_SPEED)) : _MIN(vmax_junction_sqr, v_allowable_sqr);
  2130. // Initialize planner efficiency flags
  2131. // Set flag if block will always reach maximum junction speed regardless of entry/exit speeds.
  2132. // If a block can de/ac-celerate from nominal speed to zero within the length of the block, then
  2133. // the current block and next block junction speeds are guaranteed to always be at their maximum
  2134. // junction speeds in deceleration and acceleration, respectively. This is due to how the current
  2135. // block nominal speed limits both the current and next maximum junction speeds. Hence, in both
  2136. // the reverse and forward planners, the corresponding block junction speed will always be at the
  2137. // the maximum junction speed and may always be ignored for any speed reduction checks.
  2138. block->flag |= block->nominal_speed_sqr <= v_allowable_sqr ? BLOCK_FLAG_RECALCULATE | BLOCK_FLAG_NOMINAL_LENGTH : BLOCK_FLAG_RECALCULATE;
  2139. // Update previous path unit_vector and nominal speed
  2140. previous_speed = current_speed;
  2141. previous_nominal_speed_sqr = block->nominal_speed_sqr;
  2142. position = target; // Update the position
  2143. TERN_(HAS_POSITION_FLOAT, position_float = target_float);
  2144. TERN_(GRADIENT_MIX, mixer.gradient_control(target_float.z));
  2145. TERN_(POWER_LOSS_RECOVERY, block->sdpos = recovery.command_sdpos());
  2146. return true; // Movement was accepted
  2147. } // _populate_block()
  2148. /**
  2149. * Planner::buffer_sync_block
  2150. * Add a block to the buffer that just updates the position
  2151. */
  2152. void Planner::buffer_sync_block() {
  2153. // Wait for the next available block
  2154. uint8_t next_buffer_head;
  2155. block_t * const block = get_next_free_block(next_buffer_head);
  2156. // Clear block
  2157. memset(block, 0, sizeof(block_t));
  2158. block->flag = BLOCK_FLAG_SYNC_POSITION;
  2159. block->position = position;
  2160. // If this is the first added movement, reload the delay, otherwise, cancel it.
  2161. if (block_buffer_head == block_buffer_tail) {
  2162. // If it was the first queued block, restart the 1st block delivery delay, to
  2163. // give the planner an opportunity to queue more movements and plan them
  2164. // As there are no queued movements, the Stepper ISR will not touch this
  2165. // variable, so there is no risk setting this here (but it MUST be done
  2166. // before the following line!!)
  2167. delay_before_delivering = BLOCK_DELAY_FOR_1ST_MOVE;
  2168. }
  2169. block_buffer_head = next_buffer_head;
  2170. stepper.wake_up();
  2171. } // buffer_sync_block()
  2172. /**
  2173. * Planner::buffer_segment
  2174. *
  2175. * Add a new linear movement to the buffer in axis units.
  2176. *
  2177. * Leveling and kinematics should be applied ahead of calling this.
  2178. *
  2179. * a,b,c,e - target positions in mm and/or degrees
  2180. * fr_mm_s - (target) speed of the move
  2181. * extruder - target extruder
  2182. * millimeters - the length of the movement, if known
  2183. */
  2184. bool Planner::buffer_segment(const float &a, const float &b, const float &c, const float &e
  2185. #if HAS_DIST_MM_ARG
  2186. , const xyze_float_t &cart_dist_mm
  2187. #endif
  2188. , const feedRate_t &fr_mm_s, const uint8_t extruder, const float &millimeters/*=0.0*/
  2189. ) {
  2190. // If we are cleaning, do not accept queuing of movements
  2191. if (cleaning_buffer_counter) return false;
  2192. // When changing extruders recalculate steps corresponding to the E position
  2193. #if ENABLED(DISTINCT_E_FACTORS)
  2194. if (last_extruder != extruder && settings.axis_steps_per_mm[E_AXIS_N(extruder)] != settings.axis_steps_per_mm[E_AXIS_N(last_extruder)]) {
  2195. position.e = LROUND(position.e * settings.axis_steps_per_mm[E_AXIS_N(extruder)] * steps_to_mm[E_AXIS_N(last_extruder)]);
  2196. last_extruder = extruder;
  2197. }
  2198. #endif
  2199. // The target position of the tool in absolute steps
  2200. // Calculate target position in absolute steps
  2201. const abce_long_t target = {
  2202. int32_t(LROUND(a * settings.axis_steps_per_mm[A_AXIS])),
  2203. int32_t(LROUND(b * settings.axis_steps_per_mm[B_AXIS])),
  2204. int32_t(LROUND(c * settings.axis_steps_per_mm[C_AXIS])),
  2205. int32_t(LROUND(e * settings.axis_steps_per_mm[E_AXIS_N(extruder)]))
  2206. };
  2207. #if HAS_POSITION_FLOAT
  2208. const xyze_pos_t target_float = { a, b, c, e };
  2209. #endif
  2210. // DRYRUN prevents E moves from taking place
  2211. if (DEBUGGING(DRYRUN) || TERN0(CANCEL_OBJECTS, cancelable.skipping)) {
  2212. position.e = target.e;
  2213. TERN_(HAS_POSITION_FLOAT, position_float.e = e);
  2214. }
  2215. /* <-- add a slash to enable
  2216. SERIAL_ECHOPAIR(" buffer_segment FR:", fr_mm_s);
  2217. #if IS_KINEMATIC
  2218. SERIAL_ECHOPAIR(" A:", a);
  2219. SERIAL_ECHOPAIR(" (", position.a);
  2220. SERIAL_ECHOPAIR("->", target.a);
  2221. SERIAL_ECHOPAIR(") B:", b);
  2222. #else
  2223. SERIAL_ECHOPAIR_P(SP_X_LBL, a);
  2224. SERIAL_ECHOPAIR(" (", position.x);
  2225. SERIAL_ECHOPAIR("->", target.x);
  2226. SERIAL_CHAR(')');
  2227. SERIAL_ECHOPAIR_P(SP_Y_LBL, b);
  2228. #endif
  2229. SERIAL_ECHOPAIR(" (", position.y);
  2230. SERIAL_ECHOPAIR("->", target.y);
  2231. #if ENABLED(DELTA)
  2232. SERIAL_ECHOPAIR(") C:", c);
  2233. #else
  2234. SERIAL_CHAR(')');
  2235. SERIAL_ECHOPAIR_P(SP_Z_LBL, c);
  2236. #endif
  2237. SERIAL_ECHOPAIR(" (", position.z);
  2238. SERIAL_ECHOPAIR("->", target.z);
  2239. SERIAL_CHAR(')');
  2240. SERIAL_ECHOPAIR_P(SP_E_LBL, e);
  2241. SERIAL_ECHOPAIR(" (", position.e);
  2242. SERIAL_ECHOPAIR("->", target.e);
  2243. SERIAL_ECHOLNPGM(")");
  2244. //*/
  2245. // Queue the movement
  2246. if (!_buffer_steps(target
  2247. #if HAS_POSITION_FLOAT
  2248. , target_float
  2249. #endif
  2250. #if HAS_DIST_MM_ARG
  2251. , cart_dist_mm
  2252. #endif
  2253. , fr_mm_s, extruder, millimeters)
  2254. ) return false;
  2255. stepper.wake_up();
  2256. return true;
  2257. } // buffer_segment()
  2258. /**
  2259. * Add a new linear movement to the buffer.
  2260. * The target is cartesian. It's translated to
  2261. * delta/scara if needed.
  2262. *
  2263. * rx,ry,rz,e - target position in mm or degrees
  2264. * fr_mm_s - (target) speed of the move (mm/s)
  2265. * extruder - target extruder
  2266. * millimeters - the length of the movement, if known
  2267. * inv_duration - the reciprocal if the duration of the movement, if known (kinematic only if feeedrate scaling is enabled)
  2268. */
  2269. bool Planner::buffer_line(const float &rx, const float &ry, const float &rz, const float &e, const feedRate_t &fr_mm_s, const uint8_t extruder, const float millimeters
  2270. #if ENABLED(SCARA_FEEDRATE_SCALING)
  2271. , const float &inv_duration
  2272. #endif
  2273. ) {
  2274. xyze_pos_t machine = { rx, ry, rz, e };
  2275. TERN_(HAS_POSITION_MODIFIERS, apply_modifiers(machine));
  2276. #if IS_KINEMATIC
  2277. #if HAS_JUNCTION_DEVIATION
  2278. const xyze_pos_t cart_dist_mm = {
  2279. rx - position_cart.x, ry - position_cart.y,
  2280. rz - position_cart.z, e - position_cart.e
  2281. };
  2282. #else
  2283. const xyz_pos_t cart_dist_mm = { rx - position_cart.x, ry - position_cart.y, rz - position_cart.z };
  2284. #endif
  2285. float mm = millimeters;
  2286. if (mm == 0.0)
  2287. mm = (cart_dist_mm.x != 0.0 || cart_dist_mm.y != 0.0) ? cart_dist_mm.magnitude() : ABS(cart_dist_mm.z);
  2288. // Cartesian XYZ to kinematic ABC, stored in global 'delta'
  2289. inverse_kinematics(machine);
  2290. #if ENABLED(SCARA_FEEDRATE_SCALING)
  2291. // For SCARA scale the feed rate from mm/s to degrees/s
  2292. // i.e., Complete the angular vector in the given time.
  2293. const float duration_recip = inv_duration ?: fr_mm_s / mm;
  2294. const xyz_pos_t diff = delta - position_float;
  2295. const feedRate_t feedrate = diff.magnitude() * duration_recip;
  2296. #else
  2297. const feedRate_t feedrate = fr_mm_s;
  2298. #endif
  2299. if (buffer_segment(delta.a, delta.b, delta.c, machine.e
  2300. #if HAS_JUNCTION_DEVIATION
  2301. , cart_dist_mm
  2302. #endif
  2303. , feedrate, extruder, mm
  2304. )) {
  2305. position_cart.set(rx, ry, rz, e);
  2306. return true;
  2307. }
  2308. else
  2309. return false;
  2310. #else
  2311. return buffer_segment(machine, fr_mm_s, extruder, millimeters);
  2312. #endif
  2313. } // buffer_line()
  2314. /**
  2315. * Directly set the planner ABC position (and stepper positions)
  2316. * converting mm (or angles for SCARA) into steps.
  2317. *
  2318. * The provided ABC position is in machine units.
  2319. */
  2320. void Planner::set_machine_position_mm(const float &a, const float &b, const float &c, const float &e) {
  2321. TERN_(DISTINCT_E_FACTORS, last_extruder = active_extruder);
  2322. TERN_(HAS_POSITION_FLOAT, position_float.set(a, b, c, e));
  2323. position.set(LROUND(a * settings.axis_steps_per_mm[A_AXIS]),
  2324. LROUND(b * settings.axis_steps_per_mm[B_AXIS]),
  2325. LROUND(c * settings.axis_steps_per_mm[C_AXIS]),
  2326. LROUND(e * settings.axis_steps_per_mm[E_AXIS_N(active_extruder)]));
  2327. if (has_blocks_queued()) {
  2328. //previous_nominal_speed_sqr = 0.0; // Reset planner junction speeds. Assume start from rest.
  2329. //previous_speed.reset();
  2330. buffer_sync_block();
  2331. }
  2332. else
  2333. stepper.set_position(position);
  2334. }
  2335. void Planner::set_position_mm(const float &rx, const float &ry, const float &rz, const float &e) {
  2336. xyze_pos_t machine = { rx, ry, rz, e };
  2337. #if HAS_POSITION_MODIFIERS
  2338. apply_modifiers(machine
  2339. #if HAS_LEVELING
  2340. , true
  2341. #endif
  2342. );
  2343. #endif
  2344. #if IS_KINEMATIC
  2345. position_cart.set(rx, ry, rz, e);
  2346. inverse_kinematics(machine);
  2347. set_machine_position_mm(delta.a, delta.b, delta.c, machine.e);
  2348. #else
  2349. set_machine_position_mm(machine);
  2350. #endif
  2351. }
  2352. /**
  2353. * Setters for planner position (also setting stepper position).
  2354. */
  2355. void Planner::set_e_position_mm(const float &e) {
  2356. const uint8_t axis_index = E_AXIS_N(active_extruder);
  2357. TERN_(DISTINCT_E_FACTORS, last_extruder = active_extruder);
  2358. const float e_new = e - TERN0(FWRETRACT, fwretract.current_retract[active_extruder]);
  2359. position.e = LROUND(settings.axis_steps_per_mm[axis_index] * e_new);
  2360. TERN_(HAS_POSITION_FLOAT, position_float.e = e_new);
  2361. TERN_(IS_KINEMATIC, position_cart.e = e);
  2362. if (has_blocks_queued())
  2363. buffer_sync_block();
  2364. else
  2365. stepper.set_axis_position(E_AXIS, position.e);
  2366. }
  2367. // Recalculate the steps/s^2 acceleration rates, based on the mm/s^2
  2368. void Planner::reset_acceleration_rates() {
  2369. #if ENABLED(DISTINCT_E_FACTORS)
  2370. #define AXIS_CONDITION (i < E_AXIS || i == E_AXIS_N(active_extruder))
  2371. #else
  2372. #define AXIS_CONDITION true
  2373. #endif
  2374. uint32_t highest_rate = 1;
  2375. LOOP_XYZE_N(i) {
  2376. max_acceleration_steps_per_s2[i] = settings.max_acceleration_mm_per_s2[i] * settings.axis_steps_per_mm[i];
  2377. if (AXIS_CONDITION) NOLESS(highest_rate, max_acceleration_steps_per_s2[i]);
  2378. }
  2379. cutoff_long = 4294967295UL / highest_rate; // 0xFFFFFFFFUL
  2380. TERN_(HAS_LINEAR_E_JERK, recalculate_max_e_jerk());
  2381. }
  2382. // Recalculate position, steps_to_mm if settings.axis_steps_per_mm changes!
  2383. void Planner::refresh_positioning() {
  2384. LOOP_XYZE_N(i) steps_to_mm[i] = 1.0f / settings.axis_steps_per_mm[i];
  2385. set_position_mm(current_position);
  2386. reset_acceleration_rates();
  2387. }
  2388. inline void limit_and_warn(float &val, const uint8_t axis, PGM_P const setting_name, const xyze_float_t &max_limit) {
  2389. const uint8_t lim_axis = axis > E_AXIS ? E_AXIS : axis;
  2390. const float before = val;
  2391. LIMIT(val, 0.1, max_limit[lim_axis]);
  2392. if (before != val) {
  2393. SERIAL_CHAR(axis_codes[lim_axis]);
  2394. SERIAL_ECHOPGM(" Max ");
  2395. serialprintPGM(setting_name);
  2396. SERIAL_ECHOLNPAIR(" limited to ", val);
  2397. }
  2398. }
  2399. void Planner::set_max_acceleration(const uint8_t axis, float targetValue) {
  2400. #if ENABLED(LIMITED_MAX_ACCEL_EDITING)
  2401. #ifdef MAX_ACCEL_EDIT_VALUES
  2402. constexpr xyze_float_t max_accel_edit = MAX_ACCEL_EDIT_VALUES;
  2403. const xyze_float_t &max_acc_edit_scaled = max_accel_edit;
  2404. #else
  2405. constexpr xyze_float_t max_accel_edit = DEFAULT_MAX_ACCELERATION;
  2406. const xyze_float_t max_acc_edit_scaled = max_accel_edit * 2;
  2407. #endif
  2408. limit_and_warn(targetValue, axis, PSTR("Acceleration"), max_acc_edit_scaled);
  2409. #endif
  2410. settings.max_acceleration_mm_per_s2[axis] = targetValue;
  2411. // Update steps per s2 to agree with the units per s2 (since they are used in the planner)
  2412. reset_acceleration_rates();
  2413. }
  2414. void Planner::set_max_feedrate(const uint8_t axis, float targetValue) {
  2415. #if ENABLED(LIMITED_MAX_FR_EDITING)
  2416. #ifdef MAX_FEEDRATE_EDIT_VALUES
  2417. constexpr xyze_float_t max_fr_edit = MAX_FEEDRATE_EDIT_VALUES;
  2418. const xyze_float_t &max_fr_edit_scaled = max_fr_edit;
  2419. #else
  2420. constexpr xyze_float_t max_fr_edit = DEFAULT_MAX_FEEDRATE;
  2421. const xyze_float_t max_fr_edit_scaled = max_fr_edit * 2;
  2422. #endif
  2423. limit_and_warn(targetValue, axis, PSTR("Feedrate"), max_fr_edit_scaled);
  2424. #endif
  2425. settings.max_feedrate_mm_s[axis] = targetValue;
  2426. }
  2427. void Planner::set_max_jerk(const AxisEnum axis, float targetValue) {
  2428. #if HAS_CLASSIC_JERK
  2429. #if ENABLED(LIMITED_JERK_EDITING)
  2430. constexpr xyze_float_t max_jerk_edit =
  2431. #ifdef MAX_JERK_EDIT_VALUES
  2432. MAX_JERK_EDIT_VALUES
  2433. #else
  2434. { (DEFAULT_XJERK) * 2, (DEFAULT_YJERK) * 2,
  2435. (DEFAULT_ZJERK) * 2, (DEFAULT_EJERK) * 2 }
  2436. #endif
  2437. ;
  2438. limit_and_warn(targetValue, axis, PSTR("Jerk"), max_jerk_edit);
  2439. #endif
  2440. max_jerk[axis] = targetValue;
  2441. #else
  2442. UNUSED(axis); UNUSED(targetValue);
  2443. #endif
  2444. }
  2445. #if HAS_SPI_LCD
  2446. uint16_t Planner::block_buffer_runtime() {
  2447. #ifdef __AVR__
  2448. // Protect the access to the variable. Only required for AVR, as
  2449. // any 32bit CPU offers atomic access to 32bit variables
  2450. const bool was_enabled = stepper.suspend();
  2451. #endif
  2452. millis_t bbru = block_buffer_runtime_us;
  2453. #ifdef __AVR__
  2454. // Reenable Stepper ISR
  2455. if (was_enabled) stepper.wake_up();
  2456. #endif
  2457. // To translate µs to ms a division by 1000 would be required.
  2458. // We introduce 2.4% error here by dividing by 1024.
  2459. // Doesn't matter because block_buffer_runtime_us is already too small an estimation.
  2460. bbru >>= 10;
  2461. // limit to about a minute.
  2462. NOMORE(bbru, 0xFFFFul);
  2463. return bbru;
  2464. }
  2465. void Planner::clear_block_buffer_runtime() {
  2466. #ifdef __AVR__
  2467. // Protect the access to the variable. Only required for AVR, as
  2468. // any 32bit CPU offers atomic access to 32bit variables
  2469. const bool was_enabled = stepper.suspend();
  2470. #endif
  2471. block_buffer_runtime_us = 0;
  2472. #ifdef __AVR__
  2473. // Reenable Stepper ISR
  2474. if (was_enabled) stepper.wake_up();
  2475. #endif
  2476. }
  2477. #endif
  2478. #if ENABLED(AUTOTEMP)
  2479. void Planner::autotemp_M104_M109() {
  2480. #if ENABLED(AUTOTEMP_PROPORTIONAL)
  2481. const int16_t target = thermalManager.degTargetHotend(active_extruder);
  2482. autotemp_min = target + AUTOTEMP_MIN_P;
  2483. autotemp_max = target + AUTOTEMP_MAX_P;
  2484. #endif
  2485. if (parser.seenval('S')) autotemp_min = parser.value_celsius();
  2486. if (parser.seenval('B')) autotemp_max = parser.value_celsius();
  2487. // When AUTOTEMP_PROPORTIONAL is enabled, F0 disables autotemp.
  2488. // Normally, leaving off F also disables autotemp.
  2489. autotemp_factor = parser.seen('F') ? parser.value_float() : TERN(AUTOTEMP_PROPORTIONAL, AUTOTEMP_FACTOR_P, 0);
  2490. autotemp_enabled = autotemp_factor != 0;
  2491. }
  2492. #endif