planner.cpp 109 KB

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