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

planner.cpp 140KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
  4. *
  5. * Based on Sprinter and grbl.
  6. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. *
  21. */
  22. /**
  23. * planner.cpp
  24. *
  25. * Buffer movement commands and manage the acceleration profile plan
  26. *
  27. * Derived from Grbl
  28. * Copyright (c) 2009-2011 Simen Svale Skogsrud
  29. *
  30. * The ring buffer implementation gleaned from the wiring_serial library by David A. Mellis.
  31. *
  32. *
  33. * Reasoning behind the mathematics in this module (in the key of 'Mathematica'):
  34. *
  35. * s == speed, a == acceleration, t == time, d == distance
  36. *
  37. * Basic definitions:
  38. * Speed[s_, a_, t_] := s + (a*t)
  39. * Travel[s_, a_, t_] := Integrate[Speed[s, a, t], t]
  40. *
  41. * Distance to reach a specific speed with a constant acceleration:
  42. * Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, d, t]
  43. * d -> (m^2 - s^2)/(2 a) --> estimate_acceleration_distance()
  44. *
  45. * Speed after a given distance of travel with constant acceleration:
  46. * Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, m, t]
  47. * m -> Sqrt[2 a d + s^2]
  48. *
  49. * DestinationSpeed[s_, a_, d_] := Sqrt[2 a d + s^2]
  50. *
  51. * When to start braking (di) to reach a specified destination speed (s2) after accelerating
  52. * from initial speed s1 without ever stopping at a plateau:
  53. * Solve[{DestinationSpeed[s1, a, di] == DestinationSpeed[s2, a, d - di]}, di]
  54. * di -> (2 a d - s1^2 + s2^2)/(4 a) --> intersection_distance()
  55. *
  56. * IntersectionDistance[s1_, s2_, a_, d_] := (2 a d - s1^2 + s2^2)/(4 a)
  57. *
  58. * --
  59. *
  60. * The fast inverse function needed for Bézier interpolation for AVR
  61. * was designed, written and tested by Eduardo José Tagle on April/2018
  62. */
  63. #include "planner.h"
  64. #include "stepper.h"
  65. #include "motion.h"
  66. #include "temperature.h"
  67. #include "../lcd/marlinui.h"
  68. #include "../gcode/parser.h"
  69. #include "../MarlinCore.h"
  70. #if HAS_LEVELING
  71. #include "../feature/bedlevel/bedlevel.h"
  72. #endif
  73. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  74. #include "../feature/filwidth.h"
  75. #endif
  76. #if ENABLED(BARICUDA)
  77. #include "../feature/baricuda.h"
  78. #endif
  79. #if ENABLED(MIXING_EXTRUDER)
  80. #include "../feature/mixing.h"
  81. #endif
  82. #if ENABLED(AUTO_POWER_CONTROL)
  83. #include "../feature/power.h"
  84. #endif
  85. #if ENABLED(BACKLASH_COMPENSATION)
  86. #include "../feature/backlash.h"
  87. #endif
  88. #if ENABLED(CANCEL_OBJECTS)
  89. #include "../feature/cancel_object.h"
  90. #endif
  91. #if ENABLED(POWER_LOSS_RECOVERY)
  92. #include "../feature/powerloss.h"
  93. #endif
  94. #if HAS_CUTTER
  95. #include "../feature/spindle_laser.h"
  96. #endif
  97. // Delay for delivery of first block to the stepper ISR, if the queue contains 2 or
  98. // fewer movements. The delay is measured in milliseconds, and must be less than 250ms
  99. #define BLOCK_DELAY_FOR_1ST_MOVE 100
  100. Planner planner;
  101. // public:
  102. /**
  103. * A ring buffer of moves described in steps
  104. */
  105. block_t Planner::block_buffer[BLOCK_BUFFER_SIZE];
  106. volatile uint8_t Planner::block_buffer_head, // Index of the next block to be pushed
  107. Planner::block_buffer_nonbusy, // Index of the first non-busy block
  108. Planner::block_buffer_planned, // Index of the optimally planned block
  109. Planner::block_buffer_tail; // Index of the busy block, if any
  110. uint16_t Planner::cleaning_buffer_counter; // A counter to disable queuing of blocks
  111. uint8_t Planner::delay_before_delivering; // This counter delays delivery of blocks when queue becomes empty to allow the opportunity of merging blocks
  112. planner_settings_t Planner::settings; // Initialized by settings.load()
  113. /**
  114. * Set up inline block variables
  115. * Set laser_power_floor based on SPEED_POWER_MIN to pevent a zero power output state with LASER_POWER_TRAP
  116. */
  117. #if ENABLED(LASER_FEATURE)
  118. laser_state_t Planner::laser_inline; // Current state for blocks
  119. const uint8_t laser_power_floor = cutter.pct_to_ocr(SPEED_POWER_MIN);
  120. #endif
  121. uint32_t Planner::max_acceleration_steps_per_s2[DISTINCT_AXES]; // (steps/s^2) Derived from mm_per_s2
  122. float Planner::mm_per_step[DISTINCT_AXES]; // (mm) Millimeters per step
  123. #if HAS_JUNCTION_DEVIATION
  124. float Planner::junction_deviation_mm; // (mm) M205 J
  125. #if HAS_LINEAR_E_JERK
  126. float Planner::max_e_jerk[DISTINCT_E]; // Calculated from junction_deviation_mm
  127. #endif
  128. #endif
  129. #if HAS_CLASSIC_JERK
  130. TERN(HAS_LINEAR_E_JERK, xyz_pos_t, xyze_pos_t) Planner::max_jerk;
  131. #endif
  132. #if ENABLED(SD_ABORT_ON_ENDSTOP_HIT)
  133. bool Planner::abort_on_endstop_hit = false;
  134. #endif
  135. #if ENABLED(DISTINCT_E_FACTORS)
  136. uint8_t Planner::last_extruder = 0; // Respond to extruder change
  137. #endif
  138. #if ENABLED(DIRECT_STEPPING)
  139. uint32_t Planner::last_page_step_rate = 0;
  140. xyze_bool_t Planner::last_page_dir{0};
  141. #endif
  142. #if HAS_EXTRUDERS
  143. int16_t Planner::flow_percentage[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(100); // Extrusion factor for each extruder
  144. float Planner::e_factor[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(1.0f); // The flow percentage and volumetric multiplier combine to scale E movement
  145. #endif
  146. #if DISABLED(NO_VOLUMETRICS)
  147. 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
  148. Planner::volumetric_area_nominal = CIRCLE_AREA(float(DEFAULT_NOMINAL_FILAMENT_DIA) * 0.5f), // Nominal cross-sectional area
  149. Planner::volumetric_multiplier[EXTRUDERS]; // Reciprocal of cross-sectional area of filament (in mm^2). Pre-calculated to reduce computation in the planner
  150. #endif
  151. #if ENABLED(VOLUMETRIC_EXTRUDER_LIMIT)
  152. float Planner::volumetric_extruder_limit[EXTRUDERS], // max mm^3/sec the extruder is able to handle
  153. Planner::volumetric_extruder_feedrate_limit[EXTRUDERS]; // pre calculated extruder feedrate limit based on volumetric_extruder_limit; pre-calculated to reduce computation in the planner
  154. #endif
  155. #if HAS_LEVELING
  156. bool Planner::leveling_active = false; // Flag that auto bed leveling is enabled
  157. #if ABL_PLANAR
  158. matrix_3x3 Planner::bed_level_matrix; // Transform to compensate for bed level
  159. #endif
  160. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  161. float Planner::z_fade_height, // Initialized by settings.load()
  162. Planner::inverse_z_fade_height,
  163. Planner::last_fade_z;
  164. #endif
  165. #else
  166. constexpr bool Planner::leveling_active;
  167. #endif
  168. skew_factor_t Planner::skew_factor; // Initialized by settings.load()
  169. #if ENABLED(AUTOTEMP)
  170. celsius_t Planner::autotemp_max = 250,
  171. Planner::autotemp_min = 210;
  172. float Planner::autotemp_factor = 0.1f;
  173. bool Planner::autotemp_enabled = false;
  174. #endif
  175. // private:
  176. xyze_long_t Planner::position{0};
  177. uint32_t Planner::acceleration_long_cutoff;
  178. xyze_float_t Planner::previous_speed;
  179. float Planner::previous_nominal_speed_sqr;
  180. #if ENABLED(DISABLE_INACTIVE_EXTRUDER)
  181. last_move_t Planner::g_uc_extruder_last_move[E_STEPPERS] = { 0 };
  182. #endif
  183. #ifdef XY_FREQUENCY_LIMIT
  184. int8_t Planner::xy_freq_limit_hz = XY_FREQUENCY_LIMIT;
  185. float Planner::xy_freq_min_speed_factor = (XY_FREQUENCY_MIN_PERCENT) * 0.01f;
  186. int32_t Planner::xy_freq_min_interval_us = LROUND(1000000.0 / (XY_FREQUENCY_LIMIT));
  187. #endif
  188. #if ENABLED(LIN_ADVANCE)
  189. float Planner::extruder_advance_K[EXTRUDERS]; // Initialized by settings.load()
  190. #endif
  191. #if HAS_POSITION_FLOAT
  192. xyze_pos_t Planner::position_float; // Needed for accurate maths. Steps cannot be used!
  193. #endif
  194. #if IS_KINEMATIC
  195. xyze_pos_t Planner::position_cart;
  196. #endif
  197. #if HAS_WIRED_LCD
  198. volatile uint32_t Planner::block_buffer_runtime_us = 0;
  199. #endif
  200. /**
  201. * Class and Instance Methods
  202. */
  203. Planner::Planner() { init(); }
  204. void Planner::init() {
  205. position.reset();
  206. TERN_(HAS_POSITION_FLOAT, position_float.reset());
  207. TERN_(IS_KINEMATIC, position_cart.reset());
  208. previous_speed.reset();
  209. previous_nominal_speed_sqr = 0;
  210. TERN_(ABL_PLANAR, bed_level_matrix.set_to_identity());
  211. clear_block_buffer();
  212. delay_before_delivering = 0;
  213. #if ENABLED(DIRECT_STEPPING)
  214. last_page_step_rate = 0;
  215. last_page_dir.reset();
  216. #endif
  217. }
  218. #if ENABLED(S_CURVE_ACCELERATION)
  219. #ifdef __AVR__
  220. /**
  221. * This routine returns 0x1000000 / d, getting the inverse as fast as possible.
  222. * A fast-converging iterative Newton-Raphson method can reach full precision in
  223. * just 1 iteration, and takes 211 cycles (worst case; the mean case is less, up
  224. * to 30 cycles for small divisors), instead of the 500 cycles a normal division
  225. * would take.
  226. *
  227. * Inspired by the following page:
  228. * https://stackoverflow.com/questions/27801397/newton-raphson-division-with-big-integers
  229. *
  230. * Suppose we want to calculate floor(2 ^ k / B) where B is a positive integer
  231. * Then, B must be <= 2^k, otherwise, the quotient is 0.
  232. *
  233. * The Newton - Raphson iteration for x = B / 2 ^ k yields:
  234. * q[n + 1] = q[n] * (2 - q[n] * B / 2 ^ k)
  235. *
  236. * This can be rearranged to:
  237. * q[n + 1] = q[n] * (2 ^ (k + 1) - q[n] * B) >> k
  238. *
  239. * Each iteration requires only integer multiplications and bit shifts.
  240. * It doesn't necessarily converge to floor(2 ^ k / B) but in the worst case
  241. * it eventually alternates between floor(2 ^ k / B) and ceil(2 ^ k / B).
  242. * So it checks for this case and extracts floor(2 ^ k / B).
  243. *
  244. * A simple but important optimization for this approach is to truncate
  245. * multiplications (i.e., calculate only the higher bits of the product) in the
  246. * early iterations of the Newton - Raphson method. This is done so the results
  247. * of the early iterations are far from the quotient. Then it doesn't matter if
  248. * they are done inaccurately.
  249. * It's important to pick a good starting value for x. Knowing how many
  250. * digits the divisor has, it can be estimated:
  251. *
  252. * 2^k / x = 2 ^ log2(2^k / x)
  253. * 2^k / x = 2 ^(log2(2^k)-log2(x))
  254. * 2^k / x = 2 ^(k*log2(2)-log2(x))
  255. * 2^k / x = 2 ^ (k-log2(x))
  256. * 2^k / x >= 2 ^ (k-floor(log2(x)))
  257. * floor(log2(x)) is simply the index of the most significant bit set.
  258. *
  259. * If this estimation can be improved even further the number of iterations can be
  260. * reduced a lot, saving valuable execution time.
  261. * The paper "Software Integer Division" by Thomas L.Rodeheffer, Microsoft
  262. * Research, Silicon Valley,August 26, 2008, available at
  263. * https://www.microsoft.com/en-us/research/wp-content/uploads/2008/08/tr-2008-141.pdf
  264. * suggests, for its integer division algorithm, using a table to supply the first
  265. * 8 bits of precision, then, due to the quadratic convergence nature of the
  266. * Newton-Raphon iteration, just 2 iterations should be enough to get maximum
  267. * precision of the division.
  268. * By precomputing values of inverses for small denominator values, just one
  269. * Newton-Raphson iteration is enough to reach full precision.
  270. * This code uses the top 9 bits of the denominator as index.
  271. *
  272. * The AVR assembly function implements this C code using the data below:
  273. *
  274. * // For small divisors, it is best to directly retrieve the results
  275. * if (d <= 110) return pgm_read_dword(&small_inv_tab[d]);
  276. *
  277. * // Compute initial estimation of 0x1000000/x -
  278. * // Get most significant bit set on divider
  279. * uint8_t idx = 0;
  280. * uint32_t nr = d;
  281. * if (!(nr & 0xFF0000)) {
  282. * nr <<= 8; idx += 8;
  283. * if (!(nr & 0xFF0000)) { nr <<= 8; idx += 8; }
  284. * }
  285. * if (!(nr & 0xF00000)) { nr <<= 4; idx += 4; }
  286. * if (!(nr & 0xC00000)) { nr <<= 2; idx += 2; }
  287. * if (!(nr & 0x800000)) { nr <<= 1; idx += 1; }
  288. *
  289. * // Isolate top 9 bits of the denominator, to be used as index into the initial estimation table
  290. * uint32_t tidx = nr >> 15, // top 9 bits. bit8 is always set
  291. * ie = inv_tab[tidx & 0xFF] + 256, // Get the table value. bit9 is always set
  292. * x = idx <= 8 ? (ie >> (8 - idx)) : (ie << (idx - 8)); // Position the estimation at the proper place
  293. *
  294. * x = uint32_t((x * uint64_t(_BV(25) - x * d)) >> 24); // Refine estimation by newton-raphson. 1 iteration is enough
  295. * const uint32_t r = _BV(24) - x * d; // Estimate remainder
  296. * if (r >= d) x++; // Check whether to adjust result
  297. * return uint32_t(x); // x holds the proper estimation
  298. */
  299. static uint32_t get_period_inverse(uint32_t d) {
  300. static const uint8_t inv_tab[256] PROGMEM = {
  301. 255,253,252,250,248,246,244,242,240,238,236,234,233,231,229,227,
  302. 225,224,222,220,218,217,215,213,212,210,208,207,205,203,202,200,
  303. 199,197,195,194,192,191,189,188,186,185,183,182,180,179,178,176,
  304. 175,173,172,170,169,168,166,165,164,162,161,160,158,157,156,154,
  305. 153,152,151,149,148,147,146,144,143,142,141,139,138,137,136,135,
  306. 134,132,131,130,129,128,127,126,125,123,122,121,120,119,118,117,
  307. 116,115,114,113,112,111,110,109,108,107,106,105,104,103,102,101,
  308. 100,99,98,97,96,95,94,93,92,91,90,89,88,88,87,86,
  309. 85,84,83,82,81,80,80,79,78,77,76,75,74,74,73,72,
  310. 71,70,70,69,68,67,66,66,65,64,63,62,62,61,60,59,
  311. 59,58,57,56,56,55,54,53,53,52,51,50,50,49,48,48,
  312. 47,46,46,45,44,43,43,42,41,41,40,39,39,38,37,37,
  313. 36,35,35,34,33,33,32,32,31,30,30,29,28,28,27,27,
  314. 26,25,25,24,24,23,22,22,21,21,20,19,19,18,18,17,
  315. 17,16,15,15,14,14,13,13,12,12,11,10,10,9,9,8,
  316. 8,7,7,6,6,5,5,4,4,3,3,2,2,1,0,0
  317. };
  318. // For small denominators, it is cheaper to directly store the result.
  319. // For bigger ones, just ONE Newton-Raphson iteration is enough to get
  320. // maximum precision we need
  321. static const uint32_t small_inv_tab[111] PROGMEM = {
  322. 16777216,16777216,8388608,5592405,4194304,3355443,2796202,2396745,2097152,1864135,1677721,1525201,1398101,1290555,1198372,1118481,
  323. 1048576,986895,932067,883011,838860,798915,762600,729444,699050,671088,645277,621378,599186,578524,559240,541200,
  324. 524288,508400,493447,479349,466033,453438,441505,430185,419430,409200,399457,390167,381300,372827,364722,356962,
  325. 349525,342392,335544,328965,322638,316551,310689,305040,299593,294337,289262,284359,279620,275036,270600,266305,
  326. 262144,258111,254200,250406,246723,243148,239674,236298,233016,229824,226719,223696,220752,217885,215092,212369,
  327. 209715,207126,204600,202135,199728,197379,195083,192841,190650,188508,186413,184365,182361,180400,178481,176602,
  328. 174762,172960,171196,169466,167772,166111,164482,162885,161319,159783,158275,156796,155344,153919,152520
  329. };
  330. // For small divisors, it is best to directly retrieve the results
  331. if (d <= 110) return pgm_read_dword(&small_inv_tab[d]);
  332. uint8_t r8 = d & 0xFF,
  333. r9 = (d >> 8) & 0xFF,
  334. r10 = (d >> 16) & 0xFF,
  335. r2,r3,r4,r5,r6,r7,r11,r12,r13,r14,r15,r16,r17,r18;
  336. const uint8_t *ptab = inv_tab;
  337. __asm__ __volatile__(
  338. // %8:%7:%6 = interval
  339. // r31:r30: MUST be those registers, and they must point to the inv_tab
  340. A("clr %13") // %13 = 0
  341. // Now we must compute
  342. // result = 0xFFFFFF / d
  343. // %8:%7:%6 = interval
  344. // %16:%15:%14 = nr
  345. // %13 = 0
  346. // A plain division of 24x24 bits should take 388 cycles to complete. We will
  347. // use Newton-Raphson for the calculation, and will strive to get way less cycles
  348. // for the same result - Using C division, it takes 500cycles to complete .
  349. A("clr %3") // idx = 0
  350. A("mov %14,%6")
  351. A("mov %15,%7")
  352. A("mov %16,%8") // nr = interval
  353. A("tst %16") // nr & 0xFF0000 == 0 ?
  354. A("brne 2f") // No, skip this
  355. A("mov %16,%15")
  356. A("mov %15,%14") // nr <<= 8, %14 not needed
  357. A("subi %3,-8") // idx += 8
  358. A("tst %16") // nr & 0xFF0000 == 0 ?
  359. A("brne 2f") // No, skip this
  360. A("mov %16,%15") // nr <<= 8, %14 not needed
  361. A("clr %15") // We clear %14
  362. A("subi %3,-8") // idx += 8
  363. // here %16 != 0 and %16:%15 contains at least 9 MSBits, or both %16:%15 are 0
  364. L("2")
  365. A("cpi %16,0x10") // (nr & 0xF00000) == 0 ?
  366. A("brcc 3f") // No, skip this
  367. A("swap %15") // Swap nybbles
  368. A("swap %16") // Swap nybbles. Low nybble is 0
  369. A("mov %14, %15")
  370. A("andi %14,0x0F") // Isolate low nybble
  371. A("andi %15,0xF0") // Keep proper nybble in %15
  372. A("or %16, %14") // %16:%15 <<= 4
  373. A("subi %3,-4") // idx += 4
  374. L("3")
  375. A("cpi %16,0x40") // (nr & 0xC00000) == 0 ?
  376. A("brcc 4f") // No, skip this
  377. A("add %15,%15")
  378. A("adc %16,%16")
  379. A("add %15,%15")
  380. A("adc %16,%16") // %16:%15 <<= 2
  381. A("subi %3,-2") // idx += 2
  382. L("4")
  383. A("cpi %16,0x80") // (nr & 0x800000) == 0 ?
  384. A("brcc 5f") // No, skip this
  385. A("add %15,%15")
  386. A("adc %16,%16") // %16:%15 <<= 1
  387. A("inc %3") // idx += 1
  388. // Now %16:%15 contains its MSBit set to 1, or %16:%15 is == 0. We are now absolutely sure
  389. // we have at least 9 MSBits available to enter the initial estimation table
  390. L("5")
  391. A("add %15,%15")
  392. 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)
  393. A("add r30,%16") // Only use top 8 bits
  394. A("adc r31,%13") // r31:r30 = inv_tab + (tidx)
  395. A("lpm %14, Z") // %14 = inv_tab[tidx]
  396. A("ldi %15, 1") // %15 = 1 %15:%14 = inv_tab[tidx] + 256
  397. // We must scale the approximation to the proper place
  398. A("clr %16") // %16 will always be 0 here
  399. A("subi %3,8") // idx == 8 ?
  400. A("breq 6f") // yes, no need to scale
  401. A("brcs 7f") // If C=1, means idx < 8, result was negative!
  402. // idx > 8, now %3 = idx - 8. We must perform a left shift. idx range:[1-8]
  403. A("sbrs %3,0") // shift by 1bit position?
  404. A("rjmp 8f") // No
  405. A("add %14,%14")
  406. A("adc %15,%15") // %15:16 <<= 1
  407. L("8")
  408. A("sbrs %3,1") // shift by 2bit position?
  409. A("rjmp 9f") // No
  410. A("add %14,%14")
  411. A("adc %15,%15")
  412. A("add %14,%14")
  413. A("adc %15,%15") // %15:16 <<= 1
  414. L("9")
  415. A("sbrs %3,2") // shift by 4bits position?
  416. A("rjmp 16f") // No
  417. A("swap %15") // Swap nybbles. lo nybble of %15 will always be 0
  418. A("swap %14") // Swap nybbles
  419. A("mov %12,%14")
  420. A("andi %12,0x0F") // isolate low nybble
  421. A("andi %14,0xF0") // and clear it
  422. A("or %15,%12") // %15:%16 <<= 4
  423. L("16")
  424. A("sbrs %3,3") // shift by 8bits position?
  425. A("rjmp 6f") // No, we are done
  426. A("mov %16,%15")
  427. A("mov %15,%14")
  428. A("clr %14")
  429. A("jmp 6f")
  430. // idx < 8, now %3 = idx - 8. Get the count of bits
  431. L("7")
  432. A("neg %3") // %3 = -idx = count of bits to move right. idx range:[1...8]
  433. A("sbrs %3,0") // shift by 1 bit position ?
  434. A("rjmp 10f") // No, skip it
  435. A("asr %15") // (bit7 is always 0 here)
  436. A("ror %14")
  437. L("10")
  438. A("sbrs %3,1") // shift by 2 bit position ?
  439. A("rjmp 11f") // No, skip it
  440. A("asr %15") // (bit7 is always 0 here)
  441. A("ror %14")
  442. A("asr %15") // (bit7 is always 0 here)
  443. A("ror %14")
  444. L("11")
  445. A("sbrs %3,2") // shift by 4 bit position ?
  446. A("rjmp 12f") // No, skip it
  447. A("swap %15") // Swap nybbles
  448. A("andi %14, 0xF0") // Lose the lowest nybble
  449. A("swap %14") // Swap nybbles. Upper nybble is 0
  450. A("or %14,%15") // Pass nybble from upper byte
  451. A("andi %15, 0x0F") // And get rid of that nybble
  452. L("12")
  453. A("sbrs %3,3") // shift by 8 bit position ?
  454. A("rjmp 6f") // No, skip it
  455. A("mov %14,%15")
  456. A("clr %15")
  457. L("6") // %16:%15:%14 = initial estimation of 0x1000000 / d
  458. // Now, we must refine the estimation present on %16:%15:%14 using 1 iteration
  459. // of Newton-Raphson. As it has a quadratic convergence, 1 iteration is enough
  460. // to get more than 18bits of precision (the initial table lookup gives 9 bits of
  461. // precision to start from). 18bits of precision is all what is needed here for result
  462. // %8:%7:%6 = d = interval
  463. // %16:%15:%14 = x = initial estimation of 0x1000000 / d
  464. // %13 = 0
  465. // %3:%2:%1:%0 = working accumulator
  466. // Compute 1<<25 - x*d. Result should never exceed 25 bits and should always be positive
  467. A("clr %0")
  468. A("clr %1")
  469. A("clr %2")
  470. A("ldi %3,2") // %3:%2:%1:%0 = 0x2000000
  471. A("mul %6,%14") // r1:r0 = LO(d) * LO(x)
  472. A("sub %0,r0")
  473. A("sbc %1,r1")
  474. A("sbc %2,%13")
  475. A("sbc %3,%13") // %3:%2:%1:%0 -= LO(d) * LO(x)
  476. A("mul %7,%14") // r1:r0 = MI(d) * LO(x)
  477. A("sub %1,r0")
  478. A("sbc %2,r1" )
  479. A("sbc %3,%13") // %3:%2:%1:%0 -= MI(d) * LO(x) << 8
  480. A("mul %8,%14") // r1:r0 = HI(d) * LO(x)
  481. A("sub %2,r0")
  482. A("sbc %3,r1") // %3:%2:%1:%0 -= MIL(d) * LO(x) << 16
  483. A("mul %6,%15") // r1:r0 = LO(d) * MI(x)
  484. A("sub %1,r0")
  485. A("sbc %2,r1")
  486. A("sbc %3,%13") // %3:%2:%1:%0 -= LO(d) * MI(x) << 8
  487. A("mul %7,%15") // r1:r0 = MI(d) * MI(x)
  488. A("sub %2,r0")
  489. A("sbc %3,r1") // %3:%2:%1:%0 -= MI(d) * MI(x) << 16
  490. A("mul %8,%15") // r1:r0 = HI(d) * MI(x)
  491. A("sub %3,r0") // %3:%2:%1:%0 -= MIL(d) * MI(x) << 24
  492. A("mul %6,%16") // r1:r0 = LO(d) * HI(x)
  493. A("sub %2,r0")
  494. A("sbc %3,r1") // %3:%2:%1:%0 -= LO(d) * HI(x) << 16
  495. A("mul %7,%16") // r1:r0 = MI(d) * HI(x)
  496. A("sub %3,r0") // %3:%2:%1:%0 -= MI(d) * HI(x) << 24
  497. // %3:%2:%1:%0 = (1<<25) - x*d [169]
  498. // We need to multiply that result by x, and we are only interested in the top 24bits of that multiply
  499. // %16:%15:%14 = x = initial estimation of 0x1000000 / d
  500. // %3:%2:%1:%0 = (1<<25) - x*d = acc
  501. // %13 = 0
  502. // result = %11:%10:%9:%5:%4
  503. A("mul %14,%0") // r1:r0 = LO(x) * LO(acc)
  504. A("mov %4,r1")
  505. A("clr %5")
  506. A("clr %9")
  507. A("clr %10")
  508. A("clr %11") // %11:%10:%9:%5:%4 = LO(x) * LO(acc) >> 8
  509. A("mul %15,%0") // r1:r0 = MI(x) * LO(acc)
  510. A("add %4,r0")
  511. A("adc %5,r1")
  512. A("adc %9,%13")
  513. A("adc %10,%13")
  514. A("adc %11,%13") // %11:%10:%9:%5:%4 += MI(x) * LO(acc)
  515. A("mul %16,%0") // r1:r0 = HI(x) * LO(acc)
  516. A("add %5,r0")
  517. A("adc %9,r1")
  518. A("adc %10,%13")
  519. A("adc %11,%13") // %11:%10:%9:%5:%4 += MI(x) * LO(acc) << 8
  520. A("mul %14,%1") // r1:r0 = LO(x) * MIL(acc)
  521. A("add %4,r0")
  522. A("adc %5,r1")
  523. A("adc %9,%13")
  524. A("adc %10,%13")
  525. A("adc %11,%13") // %11:%10:%9:%5:%4 = LO(x) * MIL(acc)
  526. A("mul %15,%1") // r1:r0 = MI(x) * MIL(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 += MI(x) * MIL(acc) << 8
  531. A("mul %16,%1") // r1:r0 = HI(x) * MIL(acc)
  532. A("add %9,r0")
  533. A("adc %10,r1")
  534. A("adc %11,%13") // %11:%10:%9:%5:%4 += MI(x) * MIL(acc) << 16
  535. A("mul %14,%2") // r1:r0 = LO(x) * MIH(acc)
  536. A("add %5,r0")
  537. A("adc %9,r1")
  538. A("adc %10,%13")
  539. A("adc %11,%13") // %11:%10:%9:%5:%4 = LO(x) * MIH(acc) << 8
  540. A("mul %15,%2") // r1:r0 = MI(x) * MIH(acc)
  541. A("add %9,r0")
  542. A("adc %10,r1")
  543. A("adc %11,%13") // %11:%10:%9:%5:%4 += MI(x) * MIH(acc) << 16
  544. A("mul %16,%2") // r1:r0 = HI(x) * MIH(acc)
  545. A("add %10,r0")
  546. A("adc %11,r1") // %11:%10:%9:%5:%4 += MI(x) * MIH(acc) << 24
  547. A("mul %14,%3") // r1:r0 = LO(x) * HI(acc)
  548. A("add %9,r0")
  549. A("adc %10,r1")
  550. A("adc %11,%13") // %11:%10:%9:%5:%4 = LO(x) * HI(acc) << 16
  551. A("mul %15,%3") // r1:r0 = MI(x) * HI(acc)
  552. A("add %10,r0")
  553. A("adc %11,r1") // %11:%10:%9:%5:%4 += MI(x) * HI(acc) << 24
  554. A("mul %16,%3") // r1:r0 = HI(x) * HI(acc)
  555. A("add %11,r0") // %11:%10:%9:%5:%4 += MI(x) * HI(acc) << 32
  556. // At this point, %11:%10:%9 contains the new estimation of x.
  557. // Finally, we must correct the result. Estimate remainder as
  558. // (1<<24) - x*d
  559. // %11:%10:%9 = x
  560. // %8:%7:%6 = d = interval" "\n\t"
  561. A("ldi %3,1")
  562. A("clr %2")
  563. A("clr %1")
  564. A("clr %0") // %3:%2:%1:%0 = 0x1000000
  565. A("mul %6,%9") // r1:r0 = LO(d) * LO(x)
  566. A("sub %0,r0")
  567. A("sbc %1,r1")
  568. A("sbc %2,%13")
  569. A("sbc %3,%13") // %3:%2:%1:%0 -= LO(d) * LO(x)
  570. A("mul %7,%9") // r1:r0 = MI(d) * LO(x)
  571. A("sub %1,r0")
  572. A("sbc %2,r1")
  573. A("sbc %3,%13") // %3:%2:%1:%0 -= MI(d) * LO(x) << 8
  574. A("mul %8,%9") // r1:r0 = HI(d) * LO(x)
  575. A("sub %2,r0")
  576. A("sbc %3,r1") // %3:%2:%1:%0 -= MIL(d) * LO(x) << 16
  577. A("mul %6,%10") // r1:r0 = LO(d) * MI(x)
  578. A("sub %1,r0")
  579. A("sbc %2,r1")
  580. A("sbc %3,%13") // %3:%2:%1:%0 -= LO(d) * MI(x) << 8
  581. A("mul %7,%10") // r1:r0 = MI(d) * MI(x)
  582. A("sub %2,r0")
  583. A("sbc %3,r1") // %3:%2:%1:%0 -= MI(d) * MI(x) << 16
  584. A("mul %8,%10") // r1:r0 = HI(d) * MI(x)
  585. A("sub %3,r0") // %3:%2:%1:%0 -= MIL(d) * MI(x) << 24
  586. A("mul %6,%11") // r1:r0 = LO(d) * HI(x)
  587. A("sub %2,r0")
  588. A("sbc %3,r1") // %3:%2:%1:%0 -= LO(d) * HI(x) << 16
  589. A("mul %7,%11") // r1:r0 = MI(d) * HI(x)
  590. A("sub %3,r0") // %3:%2:%1:%0 -= MI(d) * HI(x) << 24
  591. // %3:%2:%1:%0 = r = (1<<24) - x*d
  592. // %8:%7:%6 = d = interval
  593. // Perform the final correction
  594. A("sub %0,%6")
  595. A("sbc %1,%7")
  596. A("sbc %2,%8") // r -= d
  597. A("brcs 14f") // if ( r >= d)
  598. // %11:%10:%9 = x
  599. A("ldi %3,1")
  600. A("add %9,%3")
  601. A("adc %10,%13")
  602. A("adc %11,%13") // x++
  603. L("14")
  604. // Estimation is done. %11:%10:%9 = x
  605. A("clr __zero_reg__") // Make C runtime happy
  606. // [211 cycles total]
  607. : "=r" (r2),
  608. "=r" (r3),
  609. "=r" (r4),
  610. "=d" (r5),
  611. "=r" (r6),
  612. "=r" (r7),
  613. "+r" (r8),
  614. "+r" (r9),
  615. "+r" (r10),
  616. "=d" (r11),
  617. "=r" (r12),
  618. "=r" (r13),
  619. "=d" (r14),
  620. "=d" (r15),
  621. "=d" (r16),
  622. "=d" (r17),
  623. "=d" (r18),
  624. "+z" (ptab)
  625. :
  626. : "r0", "r1", "cc"
  627. );
  628. // Return the result
  629. return r11 | (uint16_t(r12) << 8) | (uint32_t(r13) << 16);
  630. }
  631. #else
  632. // All other 32-bit MPUs can easily do inverse using hardware division,
  633. // so we don't need to reduce precision or to use assembly language at all.
  634. // This routine, for all other archs, returns 0x100000000 / d ~= 0xFFFFFFFF / d
  635. FORCE_INLINE static uint32_t get_period_inverse(const uint32_t d) {
  636. return d ? 0xFFFFFFFF / d : 0xFFFFFFFF;
  637. }
  638. #endif
  639. #endif
  640. #define MINIMAL_STEP_RATE 120
  641. /**
  642. * Get the current block for processing
  643. * and mark the block as busy.
  644. * Return nullptr if the buffer is empty
  645. * or if there is a first-block delay.
  646. *
  647. * WARNING: Called from Stepper ISR context!
  648. */
  649. block_t* Planner::get_current_block() {
  650. // Get the number of moves in the planner queue so far
  651. const uint8_t nr_moves = movesplanned();
  652. // If there are any moves queued ...
  653. if (nr_moves) {
  654. // If there is still delay of delivery of blocks running, decrement it
  655. if (delay_before_delivering) {
  656. --delay_before_delivering;
  657. // If the number of movements queued is less than 3, and there is still time
  658. // to wait, do not deliver anything
  659. if (nr_moves < 3 && delay_before_delivering) return nullptr;
  660. delay_before_delivering = 0;
  661. }
  662. // If we are here, there is no excuse to deliver the block
  663. block_t * const block = &block_buffer[block_buffer_tail];
  664. // No trapezoid calculated? Don't execute yet.
  665. if (block->flag.recalculate) return nullptr;
  666. // We can't be sure how long an active block will take, so don't count it.
  667. TERN_(HAS_WIRED_LCD, block_buffer_runtime_us -= block->segment_time_us);
  668. // As this block is busy, advance the nonbusy block pointer
  669. block_buffer_nonbusy = next_block_index(block_buffer_tail);
  670. // Push block_buffer_planned pointer, if encountered.
  671. if (block_buffer_tail == block_buffer_planned)
  672. block_buffer_planned = block_buffer_nonbusy;
  673. // Return the block
  674. return block;
  675. }
  676. // The queue became empty
  677. TERN_(HAS_WIRED_LCD, clear_block_buffer_runtime()); // paranoia. Buffer is empty now - so reset accumulated time to zero.
  678. return nullptr;
  679. }
  680. /**
  681. * Calculate trapezoid parameters, multiplying the entry- and exit-speeds
  682. * by the provided factors.
  683. **
  684. * ############ VERY IMPORTANT ############
  685. * NOTE that the PRECONDITION to call this function is that the block is
  686. * NOT BUSY and it is marked as RECALCULATE. That WARRANTIES the Stepper ISR
  687. * is not and will not use the block while we modify it, so it is safe to
  688. * alter its values.
  689. */
  690. void Planner::calculate_trapezoid_for_block(block_t * const block, const_float_t entry_factor, const_float_t exit_factor) {
  691. uint32_t initial_rate = CEIL(block->nominal_rate * entry_factor),
  692. final_rate = CEIL(block->nominal_rate * exit_factor); // (steps per second)
  693. // Limit minimal step rate (Otherwise the timer will overflow.)
  694. NOLESS(initial_rate, uint32_t(MINIMAL_STEP_RATE));
  695. NOLESS(final_rate, uint32_t(MINIMAL_STEP_RATE));
  696. #if ENABLED(S_CURVE_ACCELERATION)
  697. uint32_t cruise_rate = initial_rate;
  698. #endif
  699. const int32_t accel = block->acceleration_steps_per_s2;
  700. // Steps required for acceleration, deceleration to/from nominal rate
  701. uint32_t accelerate_steps = CEIL(estimate_acceleration_distance(initial_rate, block->nominal_rate, accel)),
  702. decelerate_steps = FLOOR(estimate_acceleration_distance(block->nominal_rate, final_rate, -accel));
  703. // Steps between acceleration and deceleration, if any
  704. int32_t plateau_steps = block->step_event_count - accelerate_steps - decelerate_steps;
  705. // Does accelerate_steps + decelerate_steps exceed step_event_count?
  706. // Then we can't possibly reach the nominal rate, there will be no cruising.
  707. // Use intersection_distance() to calculate accel / braking time in order to
  708. // reach the final_rate exactly at the end of this block.
  709. if (plateau_steps < 0) {
  710. const float accelerate_steps_float = CEIL(intersection_distance(initial_rate, final_rate, accel, block->step_event_count));
  711. accelerate_steps = _MIN(uint32_t(_MAX(accelerate_steps_float, 0)), block->step_event_count);
  712. decelerate_steps = block->step_event_count - accelerate_steps;
  713. plateau_steps = 0;
  714. #if ENABLED(S_CURVE_ACCELERATION)
  715. // We won't reach the cruising rate. Let's calculate the speed we will reach
  716. cruise_rate = final_speed(initial_rate, accel, accelerate_steps);
  717. #endif
  718. }
  719. #if ENABLED(S_CURVE_ACCELERATION)
  720. else // We have some plateau time, so the cruise rate will be the nominal rate
  721. cruise_rate = block->nominal_rate;
  722. #endif
  723. #if ENABLED(S_CURVE_ACCELERATION)
  724. // Jerk controlled speed requires to express speed versus time, NOT steps
  725. uint32_t acceleration_time = ((float)(cruise_rate - initial_rate) / accel) * (STEPPER_TIMER_RATE),
  726. deceleration_time = ((float)(cruise_rate - final_rate) / accel) * (STEPPER_TIMER_RATE),
  727. // And to offload calculations from the ISR, we also calculate the inverse of those times here
  728. acceleration_time_inverse = get_period_inverse(acceleration_time),
  729. deceleration_time_inverse = get_period_inverse(deceleration_time);
  730. #endif
  731. // Store new block parameters
  732. block->accelerate_until = accelerate_steps;
  733. block->decelerate_after = block->step_event_count - decelerate_steps;
  734. block->initial_rate = initial_rate;
  735. #if ENABLED(S_CURVE_ACCELERATION)
  736. block->acceleration_time = acceleration_time;
  737. block->deceleration_time = deceleration_time;
  738. block->acceleration_time_inverse = acceleration_time_inverse;
  739. block->deceleration_time_inverse = deceleration_time_inverse;
  740. block->cruise_rate = cruise_rate;
  741. #endif
  742. block->final_rate = final_rate;
  743. #if ENABLED(LASER_POWER_TRAP)
  744. /**
  745. * Laser Trapezoid Calculations
  746. *
  747. * Approximate the trapezoid with the laser, incrementing the power every `trap_ramp_entry_incr` steps while accelerating,
  748. * and decrementing the power every `trap_ramp_exit_decr` while decelerating, to keep power proportional to feedrate.
  749. * Laser power trap will reduce the initial power to no less than the laser_power_floor value. Based on the number
  750. * of calculated accel/decel steps the power is distributed over the trapezoid entry- and exit-ramp steps.
  751. *
  752. * trap_ramp_active_pwr - The active power is initially set at a reduced level factor of initial power / accel steps and
  753. * will be additively incremented using a trap_ramp_entry_incr value for each accel step processed later in the stepper code.
  754. * The trap_ramp_exit_decr value is calculated as power / decel steps and is also adjusted to no less than the power floor.
  755. *
  756. * If the power == 0 the inline mode variables need to be set to zero to prevent stepper processing. The method allows
  757. * for simpler non-powered moves like G0 or G28.
  758. *
  759. * Laser Trap Power works for all Jerk and Curve modes; however Arc-based moves will have issues since the segments are
  760. * usually too small.
  761. */
  762. if (cutter.cutter_mode == CUTTER_MODE_CONTINUOUS) {
  763. if (planner.laser_inline.status.isPowered && planner.laser_inline.status.isEnabled) {
  764. if (block->laser.power > 0) {
  765. NOLESS(block->laser.power, laser_power_floor);
  766. block->laser.trap_ramp_active_pwr = (block->laser.power - laser_power_floor) * (initial_rate / float(block->nominal_rate)) + laser_power_floor;
  767. block->laser.trap_ramp_entry_incr = (block->laser.power - block->laser.trap_ramp_active_pwr) / accelerate_steps;
  768. float laser_pwr = block->laser.power * (final_rate / float(block->nominal_rate));
  769. NOLESS(laser_pwr, laser_power_floor);
  770. block->laser.trap_ramp_exit_decr = (block->laser.power - laser_pwr) / decelerate_steps;
  771. #if ENABLED(DEBUG_LASER_TRAP)
  772. SERIAL_ECHO_MSG("lp:",block->laser.power);
  773. SERIAL_ECHO_MSG("as:",accelerate_steps);
  774. SERIAL_ECHO_MSG("ds:",decelerate_steps);
  775. SERIAL_ECHO_MSG("p.trap:",block->laser.trap_ramp_active_pwr);
  776. SERIAL_ECHO_MSG("p.incr:",block->laser.trap_ramp_entry_incr);
  777. SERIAL_ECHO_MSG("p.decr:",block->laser.trap_ramp_exit_decr);
  778. #endif
  779. }
  780. else {
  781. block->laser.trap_ramp_active_pwr = 0;
  782. block->laser.trap_ramp_entry_incr = 0;
  783. block->laser.trap_ramp_exit_decr = 0;
  784. }
  785. }
  786. }
  787. #endif // LASER_POWER_TRAP
  788. }
  789. /* PLANNER SPEED DEFINITION
  790. +--------+ <- current->nominal_speed
  791. / \
  792. current->entry_speed -> + \
  793. | + <- next->entry_speed (aka exit speed)
  794. +-------------+
  795. time -->
  796. Recalculates the motion plan according to the following basic guidelines:
  797. 1. Go over every feasible block sequentially in reverse order and calculate the junction speeds
  798. (i.e. current->entry_speed) such that:
  799. a. No junction speed exceeds the pre-computed maximum junction speed limit or nominal speeds of
  800. neighboring blocks.
  801. b. A block entry speed cannot exceed one reverse-computed from its exit speed (next->entry_speed)
  802. with a maximum allowable deceleration over the block travel distance.
  803. c. The last (or newest appended) block is planned from a complete stop (an exit speed of zero).
  804. 2. Go over every block in chronological (forward) order and dial down junction speed values if
  805. a. The exit speed exceeds the one forward-computed from its entry speed with the maximum allowable
  806. acceleration over the block travel distance.
  807. When these stages are complete, the planner will have maximized the velocity profiles throughout the all
  808. of the planner blocks, where every block is operating at its maximum allowable acceleration limits. In
  809. other words, for all of the blocks in the planner, the plan is optimal and no further speed improvements
  810. are possible. If a new block is added to the buffer, the plan is recomputed according to the said
  811. guidelines for a new optimal plan.
  812. To increase computational efficiency of these guidelines, a set of planner block pointers have been
  813. created to indicate stop-compute points for when the planner guidelines cannot logically make any further
  814. changes or improvements to the plan when in normal operation and new blocks are streamed and added to the
  815. planner buffer. For example, if a subset of sequential blocks in the planner have been planned and are
  816. bracketed by junction velocities at their maximums (or by the first planner block as well), no new block
  817. added to the planner buffer will alter the velocity profiles within them. So we no longer have to compute
  818. them. Or, if a set of sequential blocks from the first block in the planner (or a optimal stop-compute
  819. point) are all accelerating, they are all optimal and can not be altered by a new block added to the
  820. planner buffer, as this will only further increase the plan speed to chronological blocks until a maximum
  821. junction velocity is reached. However, if the operational conditions of the plan changes from infrequently
  822. used feed holds or feedrate overrides, the stop-compute pointers will be reset and the entire plan is
  823. recomputed as stated in the general guidelines.
  824. Planner buffer index mapping:
  825. - block_buffer_tail: Points to the beginning of the planner buffer. First to be executed or being executed.
  826. - block_buffer_head: Points to the buffer block after the last block in the buffer. Used to indicate whether
  827. the buffer is full or empty. As described for standard ring buffers, this block is always empty.
  828. - block_buffer_planned: Points to the first buffer block after the last optimally planned block for normal
  829. streaming operating conditions. Use for planning optimizations by avoiding recomputing parts of the
  830. planner buffer that don't change with the addition of a new block, as describe above. In addition,
  831. this block can never be less than block_buffer_tail and will always be pushed forward and maintain
  832. this requirement when encountered by the Planner::release_current_block() routine during a cycle.
  833. NOTE: Since the planner only computes on what's in the planner buffer, some motions with lots of short
  834. line segments, like G2/3 arcs or complex curves, may seem to move slow. This is because there simply isn't
  835. enough combined distance traveled in the entire buffer to accelerate up to the nominal speed and then
  836. decelerate to a complete stop at the end of the buffer, as stated by the guidelines. If this happens and
  837. becomes an annoyance, there are a few simple solutions: (1) Maximize the machine acceleration. The planner
  838. will be able to compute higher velocity profiles within the same combined distance. (2) Maximize line
  839. motion(s) distance per block to a desired tolerance. The more combined distance the planner has to use,
  840. the faster it can go. (3) Maximize the planner buffer size. This also will increase the combined distance
  841. for the planner to compute over. It also increases the number of computations the planner has to perform
  842. to compute an optimal plan, so select carefully.
  843. */
  844. // The kernel called by recalculate() when scanning the plan from last to first entry.
  845. void Planner::reverse_pass_kernel(block_t * const current, const block_t * const next) {
  846. if (current) {
  847. // If entry speed is already at the maximum entry speed, and there was no change of speed
  848. // in the next block, there is no need to recheck. Block is cruising and there is no need to
  849. // compute anything for this block,
  850. // If not, block entry speed needs to be recalculated to ensure maximum possible planned speed.
  851. const float max_entry_speed_sqr = current->max_entry_speed_sqr;
  852. // Compute maximum entry speed decelerating over the current block from its exit speed.
  853. // If not at the maximum entry speed, or the previous block entry speed changed
  854. if (current->entry_speed_sqr != max_entry_speed_sqr || (next && next->flag.recalculate)) {
  855. // If nominal length true, max junction speed is guaranteed to be reached.
  856. // If a block can de/ac-celerate from nominal speed to zero within the length of the block, then
  857. // the current block and next block junction speeds are guaranteed to always be at their maximum
  858. // junction speeds in deceleration and acceleration, respectively. This is due to how the current
  859. // block nominal speed limits both the current and next maximum junction speeds. Hence, in both
  860. // the reverse and forward planners, the corresponding block junction speed will always be at the
  861. // the maximum junction speed and may always be ignored for any speed reduction checks.
  862. const float new_entry_speed_sqr = current->flag.nominal_length
  863. ? max_entry_speed_sqr
  864. : _MIN(max_entry_speed_sqr, max_allowable_speed_sqr(-current->acceleration, next ? next->entry_speed_sqr : sq(float(MINIMUM_PLANNER_SPEED)), current->millimeters));
  865. if (current->entry_speed_sqr != new_entry_speed_sqr) {
  866. // Need to recalculate the block speed - Mark it now, so the stepper
  867. // ISR does not consume the block before being recalculated
  868. current->flag.recalculate = true;
  869. // But there is an inherent race condition here, as the block may have
  870. // become BUSY just before being marked RECALCULATE, so check for that!
  871. if (stepper.is_block_busy(current)) {
  872. // Block became busy. Clear the RECALCULATE flag (no point in
  873. // recalculating BUSY blocks). And don't set its speed, as it can't
  874. // be updated at this time.
  875. current->flag.recalculate = false;
  876. }
  877. else {
  878. // Block is not BUSY so this is ahead of the Stepper ISR:
  879. // Just Set the new entry speed.
  880. current->entry_speed_sqr = new_entry_speed_sqr;
  881. }
  882. }
  883. }
  884. }
  885. }
  886. /**
  887. * recalculate() needs to go over the current plan twice.
  888. * Once in reverse and once forward. This implements the reverse pass.
  889. */
  890. void Planner::reverse_pass() {
  891. // Initialize block index to the last block in the planner buffer.
  892. uint8_t block_index = prev_block_index(block_buffer_head);
  893. // Read the index of the last buffer planned block.
  894. // The ISR may change it so get a stable local copy.
  895. uint8_t planned_block_index = block_buffer_planned;
  896. // If there was a race condition and block_buffer_planned was incremented
  897. // or was pointing at the head (queue empty) break loop now and avoid
  898. // planning already consumed blocks
  899. if (planned_block_index == block_buffer_head) return;
  900. // Reverse Pass: Coarsely maximize all possible deceleration curves back-planning from the last
  901. // block in buffer. Cease planning when the last optimal planned or tail pointer is reached.
  902. // NOTE: Forward pass will later refine and correct the reverse pass to create an optimal plan.
  903. const block_t *next = nullptr;
  904. while (block_index != planned_block_index) {
  905. // Perform the reverse pass
  906. block_t *current = &block_buffer[block_index];
  907. // Only process movement blocks
  908. if (current->is_move()) {
  909. reverse_pass_kernel(current, next);
  910. next = current;
  911. }
  912. // Advance to the next
  913. block_index = prev_block_index(block_index);
  914. // The ISR could advance the block_buffer_planned while we were doing the reverse pass.
  915. // We must try to avoid using an already consumed block as the last one - So follow
  916. // changes to the pointer and make sure to limit the loop to the currently busy block
  917. while (planned_block_index != block_buffer_planned) {
  918. // If we reached the busy block or an already processed block, break the loop now
  919. if (block_index == planned_block_index) return;
  920. // Advance the pointer, following the busy block
  921. planned_block_index = next_block_index(planned_block_index);
  922. }
  923. }
  924. }
  925. // The kernel called by recalculate() when scanning the plan from first to last entry.
  926. void Planner::forward_pass_kernel(const block_t * const previous, block_t * const current, const uint8_t block_index) {
  927. if (previous) {
  928. // If the previous block is an acceleration block, too short to complete the full speed
  929. // change, adjust the entry speed accordingly. Entry speeds have already been reset,
  930. // maximized, and reverse-planned. If nominal length is set, max junction speed is
  931. // guaranteed to be reached. No need to recheck.
  932. if (!previous->flag.nominal_length && previous->entry_speed_sqr < current->entry_speed_sqr) {
  933. // Compute the maximum allowable speed
  934. const float new_entry_speed_sqr = max_allowable_speed_sqr(-previous->acceleration, previous->entry_speed_sqr, previous->millimeters);
  935. // If true, current block is full-acceleration and we can move the planned pointer forward.
  936. if (new_entry_speed_sqr < current->entry_speed_sqr) {
  937. // Mark we need to recompute the trapezoidal shape, and do it now,
  938. // so the stepper ISR does not consume the block before being recalculated
  939. current->flag.recalculate = true;
  940. // But there is an inherent race condition here, as the block maybe
  941. // became BUSY, just before it was marked as RECALCULATE, so check
  942. // if that is the case!
  943. if (stepper.is_block_busy(current)) {
  944. // Block became busy. Clear the RECALCULATE flag (no point in
  945. // recalculating BUSY blocks and don't set its speed, as it can't
  946. // be updated at this time.
  947. current->flag.recalculate = false;
  948. }
  949. else {
  950. // Block is not BUSY, we won the race against the Stepper ISR:
  951. // Always <= max_entry_speed_sqr. Backward pass sets this.
  952. current->entry_speed_sqr = new_entry_speed_sqr; // Always <= max_entry_speed_sqr. Backward pass sets this.
  953. // Set optimal plan pointer.
  954. block_buffer_planned = block_index;
  955. }
  956. }
  957. }
  958. // Any block set at its maximum entry speed also creates an optimal plan up to this
  959. // point in the buffer. When the plan is bracketed by either the beginning of the
  960. // buffer and a maximum entry speed or two maximum entry speeds, every block in between
  961. // cannot logically be further improved. Hence, we don't have to recompute them anymore.
  962. if (current->entry_speed_sqr == current->max_entry_speed_sqr)
  963. block_buffer_planned = block_index;
  964. }
  965. }
  966. /**
  967. * recalculate() needs to go over the current plan twice.
  968. * Once in reverse and once forward. This implements the forward pass.
  969. */
  970. void Planner::forward_pass() {
  971. // Forward Pass: Forward plan the acceleration curve from the planned pointer onward.
  972. // Also scans for optimal plan breakpoints and appropriately updates the planned pointer.
  973. // Begin at buffer planned pointer. Note that block_buffer_planned can be modified
  974. // by the stepper ISR, so read it ONCE. It it guaranteed that block_buffer_planned
  975. // will never lead head, so the loop is safe to execute. Also note that the forward
  976. // pass will never modify the values at the tail.
  977. uint8_t block_index = block_buffer_planned;
  978. block_t *block;
  979. const block_t * previous = nullptr;
  980. while (block_index != block_buffer_head) {
  981. // Perform the forward pass
  982. block = &block_buffer[block_index];
  983. // Only process movement blocks
  984. if (block->is_move()) {
  985. // If there's no previous block or the previous block is not
  986. // BUSY (thus, modifiable) run the forward_pass_kernel. Otherwise,
  987. // the previous block became BUSY, so assume the current block's
  988. // entry speed can't be altered (since that would also require
  989. // updating the exit speed of the previous block).
  990. if (!previous || !stepper.is_block_busy(previous))
  991. forward_pass_kernel(previous, block, block_index);
  992. previous = block;
  993. }
  994. // Advance to the previous
  995. block_index = next_block_index(block_index);
  996. }
  997. }
  998. /**
  999. * Recalculate the trapezoid speed profiles for all blocks in the plan
  1000. * according to the entry_factor for each junction. Must be called by
  1001. * recalculate() after updating the blocks.
  1002. */
  1003. void Planner::recalculate_trapezoids() {
  1004. // The tail may be changed by the ISR so get a local copy.
  1005. uint8_t block_index = block_buffer_tail,
  1006. head_block_index = block_buffer_head;
  1007. // Since there could be a sync block in the head of the queue, and the
  1008. // next loop must not recalculate the head block (as it needs to be
  1009. // specially handled), scan backwards to the first non-SYNC block.
  1010. while (head_block_index != block_index) {
  1011. // Go back (head always point to the first free block)
  1012. const uint8_t prev_index = prev_block_index(head_block_index);
  1013. // Get the pointer to the block
  1014. block_t *prev = &block_buffer[prev_index];
  1015. // It the block is a move, we're done with this loop
  1016. if (prev->is_move()) break;
  1017. // Examine the previous block. This and all following are SYNC blocks
  1018. head_block_index = prev_index;
  1019. }
  1020. // Go from the tail (currently executed block) to the first block, without including it)
  1021. block_t *block = nullptr, *next = nullptr;
  1022. float current_entry_speed = 0.0, next_entry_speed = 0.0;
  1023. while (block_index != head_block_index) {
  1024. next = &block_buffer[block_index];
  1025. // Only process movement blocks
  1026. if (next->is_move()) {
  1027. next_entry_speed = SQRT(next->entry_speed_sqr);
  1028. if (block) {
  1029. // If the next block is marked to RECALCULATE, also mark the previously-fetched one
  1030. if (next->flag.recalculate) block->flag.recalculate = true;
  1031. // Recalculate if current block entry or exit junction speed has changed.
  1032. if (block->flag.recalculate) {
  1033. // But there is an inherent race condition here, as the block maybe
  1034. // became BUSY, just before it was marked as RECALCULATE, so check
  1035. // if that is the case!
  1036. if (!stepper.is_block_busy(block)) {
  1037. // Block is not BUSY, we won the race against the Stepper ISR:
  1038. // NOTE: Entry and exit factors always > 0 by all previous logic operations.
  1039. const float current_nominal_speed = SQRT(block->nominal_speed_sqr),
  1040. nomr = 1.0f / current_nominal_speed;
  1041. calculate_trapezoid_for_block(block, current_entry_speed * nomr, next_entry_speed * nomr);
  1042. #if ENABLED(LIN_ADVANCE)
  1043. if (block->use_advance_lead) {
  1044. const float comp = block->e_D_ratio * extruder_advance_K[active_extruder] * settings.axis_steps_per_mm[E_AXIS];
  1045. block->max_adv_steps = current_nominal_speed * comp;
  1046. block->final_adv_steps = next_entry_speed * comp;
  1047. }
  1048. #endif
  1049. }
  1050. // Reset current only to ensure next trapezoid is computed - The
  1051. // stepper is free to use the block from now on.
  1052. block->flag.recalculate = false;
  1053. }
  1054. }
  1055. block = next;
  1056. current_entry_speed = next_entry_speed;
  1057. }
  1058. block_index = next_block_index(block_index);
  1059. }
  1060. // Last/newest block in buffer. Exit speed is set with MINIMUM_PLANNER_SPEED. Always recalculated.
  1061. if (next) {
  1062. // Mark the next(last) block as RECALCULATE, to prevent the Stepper ISR running it.
  1063. // As the last block is always recalculated here, there is a chance the block isn't
  1064. // marked as RECALCULATE yet. That's the reason for the following line.
  1065. block->flag.recalculate = true;
  1066. // But there is an inherent race condition here, as the block maybe
  1067. // became BUSY, just before it was marked as RECALCULATE, so check
  1068. // if that is the case!
  1069. if (!stepper.is_block_busy(block)) {
  1070. // Block is not BUSY, we won the race against the Stepper ISR:
  1071. const float next_nominal_speed = SQRT(next->nominal_speed_sqr),
  1072. nomr = 1.0f / next_nominal_speed;
  1073. calculate_trapezoid_for_block(next, next_entry_speed * nomr, float(MINIMUM_PLANNER_SPEED) * nomr);
  1074. #if ENABLED(LIN_ADVANCE)
  1075. if (next->use_advance_lead) {
  1076. const float comp = next->e_D_ratio * extruder_advance_K[active_extruder] * settings.axis_steps_per_mm[E_AXIS];
  1077. next->max_adv_steps = next_nominal_speed * comp;
  1078. next->final_adv_steps = (MINIMUM_PLANNER_SPEED) * comp;
  1079. }
  1080. #endif
  1081. }
  1082. // Reset next only to ensure its trapezoid is computed - The stepper is free to use
  1083. // the block from now on.
  1084. next->flag.recalculate = false;
  1085. }
  1086. }
  1087. void Planner::recalculate() {
  1088. // Initialize block index to the last block in the planner buffer.
  1089. const uint8_t block_index = prev_block_index(block_buffer_head);
  1090. // If there is just one block, no planning can be done. Avoid it!
  1091. if (block_index != block_buffer_planned) {
  1092. reverse_pass();
  1093. forward_pass();
  1094. }
  1095. recalculate_trapezoids();
  1096. }
  1097. /**
  1098. * Apply fan speeds
  1099. */
  1100. #if HAS_FAN
  1101. void Planner::sync_fan_speeds(uint8_t (&fan_speed)[FAN_COUNT]) {
  1102. #if FAN_MIN_PWM != 0 || FAN_MAX_PWM != 255
  1103. #define CALC_FAN_SPEED(f) (fan_speed[f] ? map(fan_speed[f], 1, 255, FAN_MIN_PWM, FAN_MAX_PWM) : FAN_OFF_PWM)
  1104. #else
  1105. #define CALC_FAN_SPEED(f) (fan_speed[f] ?: FAN_OFF_PWM)
  1106. #endif
  1107. #if ENABLED(FAN_SOFT_PWM)
  1108. #define _FAN_SET(F) thermalManager.soft_pwm_amount_fan[F] = CALC_FAN_SPEED(F);
  1109. #else
  1110. #define _FAN_SET(F) hal.set_pwm_duty(pin_t(FAN##F##_PIN), CALC_FAN_SPEED(F));
  1111. #endif
  1112. #define FAN_SET(F) do{ kickstart_fan(fan_speed, ms, F); _FAN_SET(F); }while(0)
  1113. const millis_t ms = millis();
  1114. TERN_(HAS_FAN0, FAN_SET(0));
  1115. TERN_(HAS_FAN1, FAN_SET(1));
  1116. TERN_(HAS_FAN2, FAN_SET(2));
  1117. TERN_(HAS_FAN3, FAN_SET(3));
  1118. TERN_(HAS_FAN4, FAN_SET(4));
  1119. TERN_(HAS_FAN5, FAN_SET(5));
  1120. TERN_(HAS_FAN6, FAN_SET(6));
  1121. TERN_(HAS_FAN7, FAN_SET(7));
  1122. }
  1123. #if FAN_KICKSTART_TIME
  1124. void Planner::kickstart_fan(uint8_t (&fan_speed)[FAN_COUNT], const millis_t &ms, const uint8_t f) {
  1125. static millis_t fan_kick_end[FAN_COUNT] = { 0 };
  1126. if (fan_speed[f]) {
  1127. if (fan_kick_end[f] == 0) {
  1128. fan_kick_end[f] = ms + FAN_KICKSTART_TIME;
  1129. fan_speed[f] = 255;
  1130. }
  1131. else if (PENDING(ms, fan_kick_end[f]))
  1132. fan_speed[f] = 255;
  1133. }
  1134. else
  1135. fan_kick_end[f] = 0;
  1136. }
  1137. #endif
  1138. #endif // HAS_FAN
  1139. /**
  1140. * Maintain fans, paste extruder pressure, spindle/laser power
  1141. */
  1142. void Planner::check_axes_activity() {
  1143. #if ANY(DISABLE_X, DISABLE_Y, DISABLE_Z, DISABLE_I, DISABLE_J, DISABLE_K, DISABLE_U, DISABLE_V, DISABLE_W, DISABLE_E)
  1144. xyze_bool_t axis_active = { false };
  1145. #endif
  1146. #if HAS_FAN && DISABLED(LASER_SYNCHRONOUS_M106_M107)
  1147. #define HAS_TAIL_FAN_SPEED 1
  1148. static uint8_t tail_fan_speed[FAN_COUNT] = ARRAY_N_1(FAN_COUNT, 13);
  1149. bool fans_need_update = false;
  1150. #endif
  1151. #if ENABLED(BARICUDA)
  1152. #if HAS_HEATER_1
  1153. uint8_t tail_valve_pressure;
  1154. #endif
  1155. #if HAS_HEATER_2
  1156. uint8_t tail_e_to_p_pressure;
  1157. #endif
  1158. #endif
  1159. if (has_blocks_queued()) {
  1160. #if EITHER(HAS_TAIL_FAN_SPEED, BARICUDA)
  1161. block_t *block = &block_buffer[block_buffer_tail];
  1162. #endif
  1163. #if HAS_TAIL_FAN_SPEED
  1164. FANS_LOOP(i) {
  1165. const uint8_t spd = thermalManager.scaledFanSpeed(i, block->fan_speed[i]);
  1166. if (tail_fan_speed[i] != spd) {
  1167. fans_need_update = true;
  1168. tail_fan_speed[i] = spd;
  1169. }
  1170. }
  1171. #endif
  1172. #if ENABLED(BARICUDA)
  1173. TERN_(HAS_HEATER_1, tail_valve_pressure = block->valve_pressure);
  1174. TERN_(HAS_HEATER_2, tail_e_to_p_pressure = block->e_to_p_pressure);
  1175. #endif
  1176. #if ANY(DISABLE_X, DISABLE_Y, DISABLE_Z, DISABLE_I, DISABLE_J, DISABLE_K, DISABLE_E)
  1177. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  1178. block_t * const bnext = &block_buffer[b];
  1179. LOGICAL_AXIS_CODE(
  1180. if (TERN0(DISABLE_E, bnext->steps.e)) axis_active.e = true,
  1181. if (TERN0(DISABLE_X, bnext->steps.x)) axis_active.x = true,
  1182. if (TERN0(DISABLE_Y, bnext->steps.y)) axis_active.y = true,
  1183. if (TERN0(DISABLE_Z, bnext->steps.z)) axis_active.z = true,
  1184. if (TERN0(DISABLE_I, bnext->steps.i)) axis_active.i = true,
  1185. if (TERN0(DISABLE_J, bnext->steps.j)) axis_active.j = true,
  1186. if (TERN0(DISABLE_K, bnext->steps.k)) axis_active.k = true,
  1187. if (TERN0(DISABLE_U, bnext->steps.u)) axis_active.u = true,
  1188. if (TERN0(DISABLE_V, bnext->steps.v)) axis_active.v = true,
  1189. if (TERN0(DISABLE_W, bnext->steps.w)) axis_active.w = true
  1190. );
  1191. }
  1192. #endif
  1193. }
  1194. else {
  1195. TERN_(HAS_CUTTER, if (cutter.cutter_mode == CUTTER_MODE_STANDARD) cutter.refresh());
  1196. #if HAS_TAIL_FAN_SPEED
  1197. FANS_LOOP(i) {
  1198. const uint8_t spd = thermalManager.scaledFanSpeed(i);
  1199. if (tail_fan_speed[i] != spd) {
  1200. fans_need_update = true;
  1201. tail_fan_speed[i] = spd;
  1202. }
  1203. }
  1204. #endif
  1205. #if ENABLED(BARICUDA)
  1206. TERN_(HAS_HEATER_1, tail_valve_pressure = baricuda_valve_pressure);
  1207. TERN_(HAS_HEATER_2, tail_e_to_p_pressure = baricuda_e_to_p_pressure);
  1208. #endif
  1209. }
  1210. //
  1211. // Disable inactive axes
  1212. //
  1213. LOGICAL_AXIS_CODE(
  1214. if (TERN0(DISABLE_E, !axis_active.e)) stepper.disable_e_steppers(),
  1215. if (TERN0(DISABLE_X, !axis_active.x)) stepper.disable_axis(X_AXIS),
  1216. if (TERN0(DISABLE_Y, !axis_active.y)) stepper.disable_axis(Y_AXIS),
  1217. if (TERN0(DISABLE_Z, !axis_active.z)) stepper.disable_axis(Z_AXIS),
  1218. if (TERN0(DISABLE_I, !axis_active.i)) stepper.disable_axis(I_AXIS),
  1219. if (TERN0(DISABLE_J, !axis_active.j)) stepper.disable_axis(J_AXIS),
  1220. if (TERN0(DISABLE_K, !axis_active.k)) stepper.disable_axis(K_AXIS),
  1221. if (TERN0(DISABLE_U, !axis_active.u)) stepper.disable_axis(U_AXIS),
  1222. if (TERN0(DISABLE_V, !axis_active.v)) stepper.disable_axis(V_AXIS),
  1223. if (TERN0(DISABLE_W, !axis_active.w)) stepper.disable_axis(W_AXIS)
  1224. );
  1225. //
  1226. // Update Fan speeds
  1227. // Only if synchronous M106/M107 is disabled
  1228. //
  1229. TERN_(HAS_TAIL_FAN_SPEED, if (fans_need_update) sync_fan_speeds(tail_fan_speed));
  1230. TERN_(AUTOTEMP, autotemp_task());
  1231. #if ENABLED(BARICUDA)
  1232. TERN_(HAS_HEATER_1, hal.set_pwm_duty(pin_t(HEATER_1_PIN), tail_valve_pressure));
  1233. TERN_(HAS_HEATER_2, hal.set_pwm_duty(pin_t(HEATER_2_PIN), tail_e_to_p_pressure));
  1234. #endif
  1235. }
  1236. #if ENABLED(AUTOTEMP)
  1237. #if ENABLED(AUTOTEMP_PROPORTIONAL)
  1238. void Planner::_autotemp_update_from_hotend() {
  1239. const celsius_t target = thermalManager.degTargetHotend(active_extruder);
  1240. autotemp_min = target + AUTOTEMP_MIN_P;
  1241. autotemp_max = target + AUTOTEMP_MAX_P;
  1242. }
  1243. #endif
  1244. /**
  1245. * Called after changing tools to:
  1246. * - Reset or re-apply the default proportional autotemp factor.
  1247. * - Enable autotemp if the factor is non-zero.
  1248. */
  1249. void Planner::autotemp_update() {
  1250. _autotemp_update_from_hotend();
  1251. autotemp_factor = TERN(AUTOTEMP_PROPORTIONAL, AUTOTEMP_FACTOR_P, 0);
  1252. autotemp_enabled = autotemp_factor != 0;
  1253. }
  1254. /**
  1255. * Called by the M104/M109 commands after setting Hotend Temperature
  1256. *
  1257. */
  1258. void Planner::autotemp_M104_M109() {
  1259. _autotemp_update_from_hotend();
  1260. if (parser.seenval('S')) autotemp_min = parser.value_celsius();
  1261. if (parser.seenval('B')) autotemp_max = parser.value_celsius();
  1262. // When AUTOTEMP_PROPORTIONAL is enabled, F0 disables autotemp.
  1263. // Normally, leaving off F also disables autotemp.
  1264. autotemp_factor = parser.seen('F') ? parser.value_float() : TERN(AUTOTEMP_PROPORTIONAL, AUTOTEMP_FACTOR_P, 0);
  1265. autotemp_enabled = autotemp_factor != 0;
  1266. }
  1267. /**
  1268. * Called every so often to adjust the hotend target temperature
  1269. * based on the extrusion speed, which is calculated from the blocks
  1270. * currently in the planner.
  1271. */
  1272. void Planner::autotemp_task() {
  1273. static float oldt = 0.0f;
  1274. if (!autotemp_enabled) return;
  1275. if (thermalManager.degTargetHotend(active_extruder) < autotemp_min - 2) return; // Below the min?
  1276. float high = 0.0f;
  1277. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  1278. const block_t * const block = &block_buffer[b];
  1279. if (NUM_AXIS_GANG(block->steps.x, || block->steps.y, || block->steps.z, || block->steps.i, || block->steps.j, || block->steps.k, || block->steps.u, || block->steps.v, || block->steps.w)) {
  1280. const float se = (float)block->steps.e / block->step_event_count * SQRT(block->nominal_speed_sqr); // mm/sec;
  1281. NOLESS(high, se);
  1282. }
  1283. }
  1284. float t = autotemp_min + high * autotemp_factor;
  1285. LIMIT(t, autotemp_min, autotemp_max);
  1286. if (t < oldt) t = t * (1.0f - (AUTOTEMP_OLDWEIGHT)) + oldt * (AUTOTEMP_OLDWEIGHT);
  1287. oldt = t;
  1288. thermalManager.setTargetHotend(t, active_extruder);
  1289. }
  1290. #endif
  1291. #if DISABLED(NO_VOLUMETRICS)
  1292. /**
  1293. * Get a volumetric multiplier from a filament diameter.
  1294. * This is the reciprocal of the circular cross-section area.
  1295. * Return 1.0 with volumetric off or a diameter of 0.0.
  1296. */
  1297. inline float calculate_volumetric_multiplier(const_float_t diameter) {
  1298. return (parser.volumetric_enabled && diameter) ? 1.0f / CIRCLE_AREA(diameter * 0.5f) : 1;
  1299. }
  1300. /**
  1301. * Convert the filament sizes into volumetric multipliers.
  1302. * The multiplier converts a given E value into a length.
  1303. */
  1304. void Planner::calculate_volumetric_multipliers() {
  1305. LOOP_L_N(i, COUNT(filament_size)) {
  1306. volumetric_multiplier[i] = calculate_volumetric_multiplier(filament_size[i]);
  1307. refresh_e_factor(i);
  1308. }
  1309. #if ENABLED(VOLUMETRIC_EXTRUDER_LIMIT)
  1310. calculate_volumetric_extruder_limits(); // update volumetric_extruder_limits as well.
  1311. #endif
  1312. }
  1313. #endif // !NO_VOLUMETRICS
  1314. #if ENABLED(VOLUMETRIC_EXTRUDER_LIMIT)
  1315. /**
  1316. * Convert volumetric based limits into pre calculated extruder feedrate limits.
  1317. */
  1318. void Planner::calculate_volumetric_extruder_limit(const uint8_t e) {
  1319. const float &lim = volumetric_extruder_limit[e], &siz = filament_size[e];
  1320. volumetric_extruder_feedrate_limit[e] = (lim && siz) ? lim / CIRCLE_AREA(siz * 0.5f) : 0;
  1321. }
  1322. void Planner::calculate_volumetric_extruder_limits() {
  1323. EXTRUDER_LOOP() calculate_volumetric_extruder_limit(e);
  1324. }
  1325. #endif
  1326. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  1327. /**
  1328. * Convert the ratio value given by the filament width sensor
  1329. * into a volumetric multiplier. Conversion differs when using
  1330. * linear extrusion vs volumetric extrusion.
  1331. */
  1332. void Planner::apply_filament_width_sensor(const int8_t encoded_ratio) {
  1333. // Reconstitute the nominal/measured ratio
  1334. const float nom_meas_ratio = 1 + 0.01f * encoded_ratio,
  1335. ratio_2 = sq(nom_meas_ratio);
  1336. volumetric_multiplier[FILAMENT_SENSOR_EXTRUDER_NUM] = parser.volumetric_enabled
  1337. ? ratio_2 / CIRCLE_AREA(filwidth.nominal_mm * 0.5f) // Volumetric uses a true volumetric multiplier
  1338. : ratio_2; // Linear squares the ratio, which scales the volume
  1339. refresh_e_factor(FILAMENT_SENSOR_EXTRUDER_NUM);
  1340. }
  1341. #endif
  1342. #if ENABLED(IMPROVE_HOMING_RELIABILITY)
  1343. void Planner::enable_stall_prevention(const bool onoff) {
  1344. static motion_state_t saved_motion_state;
  1345. if (onoff) {
  1346. saved_motion_state.acceleration.x = settings.max_acceleration_mm_per_s2[X_AXIS];
  1347. saved_motion_state.acceleration.y = settings.max_acceleration_mm_per_s2[Y_AXIS];
  1348. settings.max_acceleration_mm_per_s2[X_AXIS] = settings.max_acceleration_mm_per_s2[Y_AXIS] = 100;
  1349. #if ENABLED(DELTA)
  1350. saved_motion_state.acceleration.z = settings.max_acceleration_mm_per_s2[Z_AXIS];
  1351. settings.max_acceleration_mm_per_s2[Z_AXIS] = 100;
  1352. #endif
  1353. #if HAS_CLASSIC_JERK
  1354. saved_motion_state.jerk_state = max_jerk;
  1355. max_jerk.set(0, 0 OPTARG(DELTA, 0));
  1356. #endif
  1357. }
  1358. else {
  1359. settings.max_acceleration_mm_per_s2[X_AXIS] = saved_motion_state.acceleration.x;
  1360. settings.max_acceleration_mm_per_s2[Y_AXIS] = saved_motion_state.acceleration.y;
  1361. TERN_(DELTA, settings.max_acceleration_mm_per_s2[Z_AXIS] = saved_motion_state.acceleration.z);
  1362. TERN_(HAS_CLASSIC_JERK, max_jerk = saved_motion_state.jerk_state);
  1363. }
  1364. refresh_acceleration_rates();
  1365. }
  1366. #endif
  1367. #if HAS_LEVELING
  1368. constexpr xy_pos_t level_fulcrum = {
  1369. TERN(Z_SAFE_HOMING, Z_SAFE_HOMING_X_POINT, X_HOME_POS),
  1370. TERN(Z_SAFE_HOMING, Z_SAFE_HOMING_Y_POINT, Y_HOME_POS)
  1371. };
  1372. /**
  1373. * rx, ry, rz - Cartesian positions in mm
  1374. * Leveled XYZ on completion
  1375. */
  1376. void Planner::apply_leveling(xyz_pos_t &raw) {
  1377. if (!leveling_active) return;
  1378. #if ABL_PLANAR
  1379. xy_pos_t d = raw - level_fulcrum;
  1380. bed_level_matrix.apply_rotation_xyz(d.x, d.y, raw.z);
  1381. raw = d + level_fulcrum;
  1382. #elif HAS_MESH
  1383. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1384. const float fade_scaling_factor = fade_scaling_factor_for_z(raw.z);
  1385. if (fade_scaling_factor) raw.z += fade_scaling_factor * bedlevel.get_z_correction(raw);
  1386. #else
  1387. raw.z += bedlevel.get_z_correction(raw);
  1388. #endif
  1389. TERN_(MESH_BED_LEVELING, raw.z += bedlevel.get_z_offset());
  1390. #endif
  1391. }
  1392. void Planner::unapply_leveling(xyz_pos_t &raw) {
  1393. if (!leveling_active) return;
  1394. #if ABL_PLANAR
  1395. matrix_3x3 inverse = matrix_3x3::transpose(bed_level_matrix);
  1396. xy_pos_t d = raw - level_fulcrum;
  1397. inverse.apply_rotation_xyz(d.x, d.y, raw.z);
  1398. raw = d + level_fulcrum;
  1399. #elif HAS_MESH
  1400. const float z_correction = bedlevel.get_z_correction(raw),
  1401. z_full_fade = DIFF_TERN(MESH_BED_LEVELING, raw.z, bedlevel.get_z_offset()),
  1402. z_no_fade = z_full_fade - z_correction;
  1403. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1404. if (!z_fade_height || z_no_fade <= 0.0f) // Not fading or at bed level?
  1405. raw.z = z_no_fade; // Unapply full mesh Z.
  1406. else if (z_full_fade >= z_fade_height) // Above the fade height?
  1407. raw.z = z_full_fade; // Nothing more to unapply.
  1408. else // Within the fade zone?
  1409. raw.z = z_no_fade / (1.0f - z_correction * inverse_z_fade_height); // Unapply the faded Z offset
  1410. #else
  1411. raw.z = z_no_fade;
  1412. #endif
  1413. #endif
  1414. }
  1415. #endif // HAS_LEVELING
  1416. #if ENABLED(FWRETRACT)
  1417. /**
  1418. * rz, e - Cartesian positions in mm
  1419. */
  1420. void Planner::apply_retract(float &rz, float &e) {
  1421. rz += fwretract.current_hop;
  1422. e -= fwretract.current_retract[active_extruder];
  1423. }
  1424. void Planner::unapply_retract(float &rz, float &e) {
  1425. rz -= fwretract.current_hop;
  1426. e += fwretract.current_retract[active_extruder];
  1427. }
  1428. #endif
  1429. void Planner::quick_stop() {
  1430. // Remove all the queued blocks. Note that this function is NOT
  1431. // called from the Stepper ISR, so we must consider tail as readonly!
  1432. // that is why we set head to tail - But there is a race condition that
  1433. // must be handled: The tail could change between the read and the assignment
  1434. // so this must be enclosed in a critical section
  1435. const bool was_enabled = stepper.suspend();
  1436. // Drop all queue entries
  1437. block_buffer_nonbusy = block_buffer_planned = block_buffer_head = block_buffer_tail;
  1438. // Restart the block delay for the first movement - As the queue was
  1439. // forced to empty, there's no risk the ISR will touch this.
  1440. delay_before_delivering = BLOCK_DELAY_FOR_1ST_MOVE;
  1441. TERN_(HAS_WIRED_LCD, clear_block_buffer_runtime()); // Clear the accumulated runtime
  1442. // Make sure to drop any attempt of queuing moves for 1 second
  1443. cleaning_buffer_counter = TEMP_TIMER_FREQUENCY;
  1444. // Reenable Stepper ISR
  1445. if (was_enabled) stepper.wake_up();
  1446. // And stop the stepper ISR
  1447. stepper.quick_stop();
  1448. }
  1449. #if ENABLED(REALTIME_REPORTING_COMMANDS)
  1450. void Planner::quick_pause() {
  1451. // Suspend until quick_resume is called
  1452. // Don't empty buffers or queues
  1453. const bool did_suspend = stepper.suspend();
  1454. if (did_suspend)
  1455. TERN_(FULL_REPORT_TO_HOST_FEATURE, set_and_report_grblstate(M_HOLD));
  1456. }
  1457. // Resume if suspended
  1458. void Planner::quick_resume() {
  1459. TERN_(FULL_REPORT_TO_HOST_FEATURE, set_and_report_grblstate(grbl_state_for_marlin_state()));
  1460. stepper.wake_up();
  1461. }
  1462. #endif
  1463. void Planner::endstop_triggered(const AxisEnum axis) {
  1464. // Record stepper position and discard the current block
  1465. stepper.endstop_triggered(axis);
  1466. }
  1467. float Planner::triggered_position_mm(const AxisEnum axis) {
  1468. const float result = DIFF_TERN(BACKLASH_COMPENSATION, stepper.triggered_position(axis), backlash.get_applied_steps(axis));
  1469. return result * mm_per_step[axis];
  1470. }
  1471. void Planner::finish_and_disable() {
  1472. while (has_blocks_queued() || cleaning_buffer_counter) idle();
  1473. stepper.disable_all_steppers();
  1474. }
  1475. /**
  1476. * Get an axis position according to stepper position(s)
  1477. * For CORE machines apply translation from ABC to XYZ.
  1478. */
  1479. float Planner::get_axis_position_mm(const AxisEnum axis) {
  1480. float axis_steps;
  1481. #if IS_CORE
  1482. // Requesting one of the "core" axes?
  1483. if (axis == CORE_AXIS_1 || axis == CORE_AXIS_2) {
  1484. // Protect the access to the position.
  1485. const bool was_enabled = stepper.suspend();
  1486. const int32_t p1 = DIFF_TERN(BACKLASH_COMPENSATION, stepper.position(CORE_AXIS_1), backlash.get_applied_steps(CORE_AXIS_1)),
  1487. p2 = DIFF_TERN(BACKLASH_COMPENSATION, stepper.position(CORE_AXIS_2), backlash.get_applied_steps(CORE_AXIS_2));
  1488. if (was_enabled) stepper.wake_up();
  1489. // ((a1+a2)+(a1-a2))/2 -> (a1+a2+a1-a2)/2 -> (a1+a1)/2 -> a1
  1490. // ((a1+a2)-(a1-a2))/2 -> (a1+a2-a1+a2)/2 -> (a2+a2)/2 -> a2
  1491. axis_steps = (axis == CORE_AXIS_2 ? CORESIGN(p1 - p2) : p1 + p2) * 0.5f;
  1492. }
  1493. else
  1494. axis_steps = DIFF_TERN(BACKLASH_COMPENSATION, stepper.position(axis), backlash.get_applied_steps(axis));
  1495. #elif EITHER(MARKFORGED_XY, MARKFORGED_YX)
  1496. // Requesting one of the joined axes?
  1497. if (axis == CORE_AXIS_1 || axis == CORE_AXIS_2) {
  1498. // Protect the access to the position.
  1499. const bool was_enabled = stepper.suspend();
  1500. const int32_t p1 = stepper.position(CORE_AXIS_1),
  1501. p2 = stepper.position(CORE_AXIS_2);
  1502. if (was_enabled) stepper.wake_up();
  1503. axis_steps = ((axis == CORE_AXIS_1) ? p1 - p2 : p2);
  1504. }
  1505. else
  1506. axis_steps = DIFF_TERN(BACKLASH_COMPENSATION, stepper.position(axis), backlash.get_applied_steps(axis));
  1507. #else
  1508. axis_steps = stepper.position(axis);
  1509. TERN_(BACKLASH_COMPENSATION, axis_steps -= backlash.get_applied_steps(axis));
  1510. #endif
  1511. return axis_steps * mm_per_step[axis];
  1512. }
  1513. /**
  1514. * Block until the planner is finished processing
  1515. */
  1516. void Planner::synchronize() { while (busy()) idle(); }
  1517. /**
  1518. * Planner::_buffer_steps
  1519. *
  1520. * Add a new linear movement to the planner queue (in terms of steps).
  1521. *
  1522. * target - target position in steps units
  1523. * target_float - target position in direct (mm, degrees) units. optional
  1524. * fr_mm_s - (target) speed of the move
  1525. * extruder - target extruder
  1526. * millimeters - the length of the movement, if known
  1527. *
  1528. * Returns true if movement was properly queued, false otherwise (if cleaning)
  1529. */
  1530. bool Planner::_buffer_steps(const xyze_long_t &target
  1531. OPTARG(HAS_POSITION_FLOAT, const xyze_pos_t &target_float)
  1532. OPTARG(HAS_DIST_MM_ARG, const xyze_float_t &cart_dist_mm)
  1533. , feedRate_t fr_mm_s, const uint8_t extruder, const_float_t millimeters
  1534. ) {
  1535. // Wait for the next available block
  1536. uint8_t next_buffer_head;
  1537. block_t * const block = get_next_free_block(next_buffer_head);
  1538. // If we are cleaning, do not accept queuing of movements
  1539. // This must be after get_next_free_block() because it calls idle()
  1540. // where cleaning_buffer_counter can be changed
  1541. if (cleaning_buffer_counter) return false;
  1542. // Fill the block with the specified movement
  1543. if (!_populate_block(block, target
  1544. OPTARG(HAS_POSITION_FLOAT, target_float)
  1545. OPTARG(HAS_DIST_MM_ARG, cart_dist_mm)
  1546. , fr_mm_s, extruder, millimeters
  1547. )
  1548. ) {
  1549. // Movement was not queued, probably because it was too short.
  1550. // Simply accept that as movement queued and done
  1551. return true;
  1552. }
  1553. // If this is the first added movement, reload the delay, otherwise, cancel it.
  1554. if (block_buffer_head == block_buffer_tail) {
  1555. // If it was the first queued block, restart the 1st block delivery delay, to
  1556. // give the planner an opportunity to queue more movements and plan them
  1557. // As there are no queued movements, the Stepper ISR will not touch this
  1558. // variable, so there is no risk setting this here (but it MUST be done
  1559. // before the following line!!)
  1560. delay_before_delivering = BLOCK_DELAY_FOR_1ST_MOVE;
  1561. }
  1562. // Move buffer head
  1563. block_buffer_head = next_buffer_head;
  1564. // Recalculate and optimize trapezoidal speed profiles
  1565. recalculate();
  1566. // Movement successfully queued!
  1567. return true;
  1568. }
  1569. /**
  1570. * @brief Populate a block in preparation for insertion
  1571. * @details Populate the fields of a new linear movement block
  1572. * that will be added to the queue and processed soon
  1573. * by the Stepper ISR.
  1574. *
  1575. * @param block A block to populate
  1576. * @param target Target position in steps units
  1577. * @param target_float Target position in native mm
  1578. * @param cart_dist_mm The pre-calculated move lengths for all axes, in mm
  1579. * @param fr_mm_s (target) speed of the move
  1580. * @param extruder target extruder
  1581. * @param millimeters A pre-calculated linear distance for the move, in mm,
  1582. * or 0.0 to have the distance calculated here.
  1583. *
  1584. * @return true if movement is acceptable, false otherwise
  1585. */
  1586. bool Planner::_populate_block(
  1587. block_t * const block,
  1588. const abce_long_t &target
  1589. OPTARG(HAS_POSITION_FLOAT, const xyze_pos_t &target_float)
  1590. OPTARG(HAS_DIST_MM_ARG, const xyze_float_t &cart_dist_mm)
  1591. , feedRate_t fr_mm_s, const uint8_t extruder, const_float_t millimeters/*=0.0*/
  1592. ) {
  1593. int32_t LOGICAL_AXIS_LIST(
  1594. de = target.e - position.e,
  1595. da = target.a - position.a,
  1596. db = target.b - position.b,
  1597. dc = target.c - position.c,
  1598. di = target.i - position.i,
  1599. dj = target.j - position.j,
  1600. dk = target.k - position.k,
  1601. du = target.u - position.u,
  1602. dv = target.v - position.v,
  1603. dw = target.w - position.w
  1604. );
  1605. /* <-- add a slash to enable
  1606. SERIAL_ECHOLNPGM(
  1607. " _populate_block FR:", fr_mm_s,
  1608. " A:", target.a, " (", da, " steps)"
  1609. #if HAS_Y_AXIS
  1610. " B:", target.b, " (", db, " steps)"
  1611. #endif
  1612. #if HAS_Z_AXIS
  1613. " C:", target.c, " (", dc, " steps)"
  1614. #endif
  1615. #if HAS_I_AXIS
  1616. " " STR_I ":", target.i, " (", di, " steps)"
  1617. #endif
  1618. #if HAS_J_AXIS
  1619. " " STR_J ":", target.j, " (", dj, " steps)"
  1620. #endif
  1621. #if HAS_K_AXIS
  1622. " " STR_K ":", target.k, " (", dk, " steps)"
  1623. #endif
  1624. #if HAS_U_AXIS
  1625. " " STR_U ":", target.u, " (", du, " steps)"
  1626. #endif
  1627. #if HAS_V_AXIS
  1628. " " STR_V ":", target.v, " (", dv, " steps)"
  1629. #endif
  1630. #if HAS_W_AXIS
  1631. " " STR_W ":", target.w, " (", dw, " steps)"
  1632. #if HAS_EXTRUDERS
  1633. " E:", target.e, " (", de, " steps)"
  1634. #endif
  1635. );
  1636. //*/
  1637. #if EITHER(PREVENT_COLD_EXTRUSION, PREVENT_LENGTHY_EXTRUDE)
  1638. if (de) {
  1639. #if ENABLED(PREVENT_COLD_EXTRUSION)
  1640. if (thermalManager.tooColdToExtrude(extruder)) {
  1641. position.e = target.e; // Behave as if the move really took place, but ignore E part
  1642. TERN_(HAS_POSITION_FLOAT, position_float.e = target_float.e);
  1643. de = 0; // no difference
  1644. SERIAL_ECHO_MSG(STR_ERR_COLD_EXTRUDE_STOP);
  1645. }
  1646. #endif // PREVENT_COLD_EXTRUSION
  1647. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  1648. const float e_steps = ABS(de * e_factor[extruder]);
  1649. const float max_e_steps = settings.axis_steps_per_mm[E_AXIS_N(extruder)] * (EXTRUDE_MAXLENGTH);
  1650. if (e_steps > max_e_steps) {
  1651. #if ENABLED(MIXING_EXTRUDER)
  1652. bool ignore_e = false;
  1653. float collector[MIXING_STEPPERS];
  1654. mixer.refresh_collector(1.0, mixer.get_current_vtool(), collector);
  1655. MIXER_STEPPER_LOOP(e)
  1656. if (e_steps * collector[e] > max_e_steps) { ignore_e = true; break; }
  1657. #else
  1658. constexpr bool ignore_e = true;
  1659. #endif
  1660. if (ignore_e) {
  1661. position.e = target.e; // Behave as if the move really took place, but ignore E part
  1662. TERN_(HAS_POSITION_FLOAT, position_float.e = target_float.e);
  1663. de = 0; // no difference
  1664. SERIAL_ECHO_MSG(STR_ERR_LONG_EXTRUDE_STOP);
  1665. }
  1666. }
  1667. #endif // PREVENT_LENGTHY_EXTRUDE
  1668. }
  1669. #endif // PREVENT_COLD_EXTRUSION || PREVENT_LENGTHY_EXTRUDE
  1670. // Compute direction bit-mask for this block
  1671. axis_bits_t dm = 0;
  1672. #if ANY(CORE_IS_XY, MARKFORGED_XY, MARKFORGED_YX)
  1673. if (da < 0) SBI(dm, X_HEAD); // Save the toolhead's true direction in X
  1674. if (db < 0) SBI(dm, Y_HEAD); // ...and Y
  1675. if (dc < 0) SBI(dm, Z_AXIS);
  1676. #endif
  1677. #if IS_CORE
  1678. #if CORE_IS_XY
  1679. if (da + db < 0) SBI(dm, A_AXIS); // Motor A direction
  1680. if (CORESIGN(da - db) < 0) SBI(dm, B_AXIS); // Motor B direction
  1681. #elif CORE_IS_XZ
  1682. if (da < 0) SBI(dm, X_HEAD); // Save the toolhead's true direction in X
  1683. if (db < 0) SBI(dm, Y_AXIS);
  1684. if (dc < 0) SBI(dm, Z_HEAD); // ...and Z
  1685. if (da + dc < 0) SBI(dm, A_AXIS); // Motor A direction
  1686. if (CORESIGN(da - dc) < 0) SBI(dm, C_AXIS); // Motor C direction
  1687. #elif CORE_IS_YZ
  1688. if (da < 0) SBI(dm, X_AXIS);
  1689. if (db < 0) SBI(dm, Y_HEAD); // Save the toolhead's true direction in Y
  1690. if (dc < 0) SBI(dm, Z_HEAD); // ...and Z
  1691. if (db + dc < 0) SBI(dm, B_AXIS); // Motor B direction
  1692. if (CORESIGN(db - dc) < 0) SBI(dm, C_AXIS); // Motor C direction
  1693. #endif
  1694. #elif ENABLED(MARKFORGED_XY)
  1695. if (da + db < 0) SBI(dm, A_AXIS); // Motor A direction
  1696. if (db < 0) SBI(dm, B_AXIS); // Motor B direction
  1697. #elif ENABLED(MARKFORGED_YX)
  1698. if (da < 0) SBI(dm, A_AXIS); // Motor A direction
  1699. if (db + da < 0) SBI(dm, B_AXIS); // Motor B direction
  1700. #else
  1701. XYZ_CODE(
  1702. if (da < 0) SBI(dm, X_AXIS),
  1703. if (db < 0) SBI(dm, Y_AXIS),
  1704. if (dc < 0) SBI(dm, Z_AXIS)
  1705. );
  1706. #endif
  1707. SECONDARY_AXIS_CODE(
  1708. if (di < 0) SBI(dm, I_AXIS),
  1709. if (dj < 0) SBI(dm, J_AXIS),
  1710. if (dk < 0) SBI(dm, K_AXIS),
  1711. if (du < 0) SBI(dm, U_AXIS),
  1712. if (dv < 0) SBI(dm, V_AXIS),
  1713. if (dw < 0) SBI(dm, W_AXIS)
  1714. );
  1715. #if HAS_EXTRUDERS
  1716. if (de < 0) SBI(dm, E_AXIS);
  1717. const float esteps_float = de * e_factor[extruder];
  1718. const uint32_t esteps = ABS(esteps_float) + 0.5f;
  1719. #else
  1720. constexpr uint32_t esteps = 0;
  1721. #endif
  1722. // Clear all flags, including the "busy" bit
  1723. block->flag.clear();
  1724. // Set direction bits
  1725. block->direction_bits = dm;
  1726. /**
  1727. * Update block laser power
  1728. * For standard mode get the cutter.power value for processing, since it's
  1729. * only set by apply_power().
  1730. */
  1731. #if HAS_CUTTER
  1732. switch (cutter.cutter_mode) {
  1733. default: break;
  1734. case CUTTER_MODE_STANDARD: block->cutter_power = cutter.power; break;
  1735. #if ENABLED(LASER_FEATURE)
  1736. /**
  1737. * For inline mode get the laser_inline variables, including power and status.
  1738. * Dynamic mode only needs to update if the feedrate has changed, since it's
  1739. * calculated from the current feedrate and power level.
  1740. */
  1741. case CUTTER_MODE_CONTINUOUS:
  1742. block->laser.power = laser_inline.power;
  1743. block->laser.status = laser_inline.status;
  1744. break;
  1745. case CUTTER_MODE_DYNAMIC:
  1746. if (cutter.laser_feedrate_changed()) // Only process changes in rate
  1747. block->laser.power = laser_inline.power = cutter.calc_dynamic_power();
  1748. break;
  1749. #endif
  1750. }
  1751. #endif
  1752. // Number of steps for each axis
  1753. // See https://www.corexy.com/theory.html
  1754. block->steps.set(NUM_AXIS_LIST(
  1755. #if CORE_IS_XY
  1756. ABS(da + db), ABS(da - db), ABS(dc)
  1757. #elif CORE_IS_XZ
  1758. ABS(da + dc), ABS(db), ABS(da - dc)
  1759. #elif CORE_IS_YZ
  1760. ABS(da), ABS(db + dc), ABS(db - dc)
  1761. #elif ENABLED(MARKFORGED_XY)
  1762. ABS(da + db), ABS(db), ABS(dc)
  1763. #elif ENABLED(MARKFORGED_YX)
  1764. ABS(da), ABS(db + da), ABS(dc)
  1765. #elif IS_SCARA
  1766. ABS(da), ABS(db), ABS(dc)
  1767. #else // default non-h-bot planning
  1768. ABS(da), ABS(db), ABS(dc)
  1769. #endif
  1770. , ABS(di), ABS(dj), ABS(dk), ABS(du), ABS(dv), ABS(dw)
  1771. ));
  1772. /**
  1773. * This part of the code calculates the total length of the movement.
  1774. * For cartesian bots, the X_AXIS is the real X movement and same for Y_AXIS.
  1775. * But for corexy bots, that is not true. The "X_AXIS" and "Y_AXIS" motors (that should be named to A_AXIS
  1776. * and B_AXIS) cannot be used for X and Y length, because A=X+Y and B=X-Y.
  1777. * So we need to create other 2 "AXIS", named X_HEAD and Y_HEAD, meaning the real displacement of the Head.
  1778. * Having the real displacement of the head, we can calculate the total movement length and apply the desired speed.
  1779. */
  1780. struct DistanceMM : abce_float_t {
  1781. #if ANY(IS_CORE, MARKFORGED_XY, MARKFORGED_YX)
  1782. struct { float x, y, z; } head;
  1783. #endif
  1784. } steps_dist_mm;
  1785. #if ANY(CORE_IS_XY, MARKFORGED_XY, MARKFORGED_YX)
  1786. steps_dist_mm.head.x = da * mm_per_step[A_AXIS];
  1787. steps_dist_mm.head.y = db * mm_per_step[B_AXIS];
  1788. steps_dist_mm.z = dc * mm_per_step[Z_AXIS];
  1789. #endif
  1790. #if IS_CORE
  1791. #if CORE_IS_XY
  1792. steps_dist_mm.a = (da + db) * mm_per_step[A_AXIS];
  1793. steps_dist_mm.b = CORESIGN(da - db) * mm_per_step[B_AXIS];
  1794. #elif CORE_IS_XZ
  1795. steps_dist_mm.head.x = da * mm_per_step[A_AXIS];
  1796. steps_dist_mm.y = db * mm_per_step[Y_AXIS];
  1797. steps_dist_mm.head.z = dc * mm_per_step[C_AXIS];
  1798. steps_dist_mm.a = (da + dc) * mm_per_step[A_AXIS];
  1799. steps_dist_mm.c = CORESIGN(da - dc) * mm_per_step[C_AXIS];
  1800. #elif CORE_IS_YZ
  1801. steps_dist_mm.x = da * mm_per_step[X_AXIS];
  1802. steps_dist_mm.head.y = db * mm_per_step[B_AXIS];
  1803. steps_dist_mm.head.z = dc * mm_per_step[C_AXIS];
  1804. steps_dist_mm.b = (db + dc) * mm_per_step[B_AXIS];
  1805. steps_dist_mm.c = CORESIGN(db - dc) * mm_per_step[C_AXIS];
  1806. #endif
  1807. #elif ENABLED(MARKFORGED_XY)
  1808. steps_dist_mm.a = (da - db) * mm_per_step[A_AXIS];
  1809. steps_dist_mm.b = db * mm_per_step[B_AXIS];
  1810. #elif ENABLED(MARKFORGED_YX)
  1811. steps_dist_mm.a = da * mm_per_step[A_AXIS];
  1812. steps_dist_mm.b = (db - da) * mm_per_step[B_AXIS];
  1813. #else
  1814. XYZ_CODE(
  1815. steps_dist_mm.a = da * mm_per_step[A_AXIS],
  1816. steps_dist_mm.b = db * mm_per_step[B_AXIS],
  1817. steps_dist_mm.c = dc * mm_per_step[C_AXIS]
  1818. );
  1819. #endif
  1820. SECONDARY_AXIS_CODE(
  1821. steps_dist_mm.i = di * mm_per_step[I_AXIS],
  1822. steps_dist_mm.j = dj * mm_per_step[J_AXIS],
  1823. steps_dist_mm.k = dk * mm_per_step[K_AXIS],
  1824. steps_dist_mm.u = du * mm_per_step[U_AXIS],
  1825. steps_dist_mm.v = dv * mm_per_step[V_AXIS],
  1826. steps_dist_mm.w = dw * mm_per_step[W_AXIS]
  1827. );
  1828. TERN_(HAS_EXTRUDERS, steps_dist_mm.e = esteps_float * mm_per_step[E_AXIS_N(extruder)]);
  1829. TERN_(LCD_SHOW_E_TOTAL, e_move_accumulator += steps_dist_mm.e);
  1830. #if BOTH(HAS_ROTATIONAL_AXES, INCH_MODE_SUPPORT)
  1831. bool cartesian_move = true;
  1832. #endif
  1833. if (true NUM_AXIS_GANG(
  1834. && block->steps.a < MIN_STEPS_PER_SEGMENT,
  1835. && block->steps.b < MIN_STEPS_PER_SEGMENT,
  1836. && block->steps.c < MIN_STEPS_PER_SEGMENT,
  1837. && block->steps.i < MIN_STEPS_PER_SEGMENT,
  1838. && block->steps.j < MIN_STEPS_PER_SEGMENT,
  1839. && block->steps.k < MIN_STEPS_PER_SEGMENT,
  1840. && block->steps.u < MIN_STEPS_PER_SEGMENT,
  1841. && block->steps.v < MIN_STEPS_PER_SEGMENT,
  1842. && block->steps.w < MIN_STEPS_PER_SEGMENT
  1843. )
  1844. ) {
  1845. block->millimeters = TERN0(HAS_EXTRUDERS, ABS(steps_dist_mm.e));
  1846. }
  1847. else {
  1848. if (millimeters)
  1849. block->millimeters = millimeters;
  1850. else {
  1851. /**
  1852. * Distance for interpretation of feedrate in accordance with LinuxCNC (the successor of NIST
  1853. * RS274NGC interpreter - version 3) and its default CANON_XYZ feed reference mode.
  1854. * Assume that X, Y, Z are the primary linear axes and U, V, W are secondary linear axes and A, B, C are
  1855. * rotational axes. Then dX, dY, dZ are the displacements of the primary linear axes and dU, dV, dW are the displacements of linear axes and
  1856. * dA, dB, dC are the displacements of rotational axes.
  1857. * The time it takes to execute move command with feedrate F is t = D/F, where D is the total distance, calculated as follows:
  1858. * D^2 = dX^2 + dY^2 + dZ^2
  1859. * if D^2 == 0 (none of XYZ move but any secondary linear axes move, whether other axes are moved or not):
  1860. * D^2 = dU^2 + dV^2 + dW^2
  1861. * if D^2 == 0 (only rotational axes are moved):
  1862. * D^2 = dA^2 + dB^2 + dC^2
  1863. */
  1864. float distance_sqr = (
  1865. #if ENABLED(ARTICULATED_ROBOT_ARM)
  1866. // For articulated robots, interpreting feedrate like LinuxCNC would require inverse kinematics. As a workaround, pretend that motors sit on n mutually orthogonal
  1867. // axes and assume that we could think of distance as magnitude of an n-vector in an n-dimensional Euclidian space.
  1868. NUM_AXIS_GANG(
  1869. sq(steps_dist_mm.x), + sq(steps_dist_mm.y), + sq(steps_dist_mm.z),
  1870. + sq(steps_dist_mm.i), + sq(steps_dist_mm.j), + sq(steps_dist_mm.k),
  1871. + sq(steps_dist_mm.u), + sq(steps_dist_mm.v), + sq(steps_dist_mm.w)
  1872. );
  1873. #elif ENABLED(FOAMCUTTER_XYUV)
  1874. #if HAS_J_AXIS
  1875. // Special 5 axis kinematics. Return the largest distance move from either X/Y or I/J plane
  1876. _MAX(sq(steps_dist_mm.x) + sq(steps_dist_mm.y), sq(steps_dist_mm.i) + sq(steps_dist_mm.j))
  1877. #else // Foamcutter with only two axes (XY)
  1878. sq(steps_dist_mm.x) + sq(steps_dist_mm.y)
  1879. #endif
  1880. #elif ANY(CORE_IS_XY, MARKFORGED_XY, MARKFORGED_YX)
  1881. XYZ_GANG(sq(steps_dist_mm.head.x), + sq(steps_dist_mm.head.y), + sq(steps_dist_mm.z))
  1882. #elif CORE_IS_XZ
  1883. XYZ_GANG(sq(steps_dist_mm.head.x), + sq(steps_dist_mm.y), + sq(steps_dist_mm.head.z))
  1884. #elif CORE_IS_YZ
  1885. XYZ_GANG(sq(steps_dist_mm.x), + sq(steps_dist_mm.head.y), + sq(steps_dist_mm.head.z))
  1886. #else
  1887. XYZ_GANG(sq(steps_dist_mm.x), + sq(steps_dist_mm.y), + sq(steps_dist_mm.z))
  1888. #endif
  1889. );
  1890. #if SECONDARY_LINEAR_AXES >= 1 && NONE(FOAMCUTTER_XYUV, ARTICULATED_ROBOT_ARM)
  1891. if (NEAR_ZERO(distance_sqr)) {
  1892. // Move does not involve any primary linear axes (xyz) but might involve secondary linear axes
  1893. distance_sqr = (0.0
  1894. SECONDARY_AXIS_GANG(
  1895. IF_DISABLED(AXIS4_ROTATES, + sq(steps_dist_mm.i)),
  1896. IF_DISABLED(AXIS5_ROTATES, + sq(steps_dist_mm.j)),
  1897. IF_DISABLED(AXIS6_ROTATES, + sq(steps_dist_mm.k)),
  1898. IF_DISABLED(AXIS7_ROTATES, + sq(steps_dist_mm.u)),
  1899. IF_DISABLED(AXIS8_ROTATES, + sq(steps_dist_mm.v)),
  1900. IF_DISABLED(AXIS9_ROTATES, + sq(steps_dist_mm.w))
  1901. )
  1902. );
  1903. }
  1904. #endif
  1905. #if HAS_ROTATIONAL_AXES && NONE(FOAMCUTTER_XYUV, ARTICULATED_ROBOT_ARM)
  1906. if (NEAR_ZERO(distance_sqr)) {
  1907. // Move involves only rotational axes. Calculate angular distance in accordance with LinuxCNC
  1908. TERN_(INCH_MODE_SUPPORT, cartesian_move = false);
  1909. distance_sqr = ROTATIONAL_AXIS_GANG(sq(steps_dist_mm.i), + sq(steps_dist_mm.j), + sq(steps_dist_mm.k), + sq(steps_dist_mm.u), + sq(steps_dist_mm.v), + sq(steps_dist_mm.w));
  1910. }
  1911. #endif
  1912. block->millimeters = SQRT(distance_sqr);
  1913. }
  1914. /**
  1915. * At this point at least one of the axes has more steps than
  1916. * MIN_STEPS_PER_SEGMENT, ensuring the segment won't get dropped as
  1917. * zero-length. It's important to not apply corrections
  1918. * to blocks that would get dropped!
  1919. *
  1920. * A correction function is permitted to add steps to an axis, it
  1921. * should *never* remove steps!
  1922. */
  1923. TERN_(BACKLASH_COMPENSATION, backlash.add_correction_steps(da, db, dc, dm, block));
  1924. }
  1925. TERN_(HAS_EXTRUDERS, block->steps.e = esteps);
  1926. block->step_event_count = _MAX(LOGICAL_AXIS_LIST(esteps,
  1927. block->steps.a, block->steps.b, block->steps.c,
  1928. block->steps.i, block->steps.j, block->steps.k,
  1929. block->steps.u, block->steps.v, block->steps.w
  1930. ));
  1931. // Bail if this is a zero-length block
  1932. if (block->step_event_count < MIN_STEPS_PER_SEGMENT) return false;
  1933. TERN_(MIXING_EXTRUDER, mixer.populate_block(block->b_color));
  1934. #if HAS_FAN
  1935. FANS_LOOP(i) block->fan_speed[i] = thermalManager.fan_speed[i];
  1936. #endif
  1937. #if ENABLED(BARICUDA)
  1938. block->valve_pressure = baricuda_valve_pressure;
  1939. block->e_to_p_pressure = baricuda_e_to_p_pressure;
  1940. #endif
  1941. E_TERN_(block->extruder = extruder);
  1942. #if ENABLED(AUTO_POWER_CONTROL)
  1943. if (NUM_AXIS_GANG(
  1944. block->steps.x,
  1945. || block->steps.y,
  1946. || block->steps.z,
  1947. || block->steps.i,
  1948. || block->steps.j,
  1949. || block->steps.k,
  1950. || block->steps.u,
  1951. || block->steps.v,
  1952. || block->steps.w
  1953. )) powerManager.power_on();
  1954. #endif
  1955. // Enable active axes
  1956. #if ANY(CORE_IS_XY, MARKFORGED_XY, MARKFORGED_YX)
  1957. if (block->steps.a || block->steps.b) {
  1958. stepper.enable_axis(X_AXIS);
  1959. stepper.enable_axis(Y_AXIS);
  1960. }
  1961. #if DISABLED(Z_LATE_ENABLE)
  1962. if (block->steps.z) stepper.enable_axis(Z_AXIS);
  1963. #endif
  1964. #elif CORE_IS_XZ
  1965. if (block->steps.a || block->steps.c) {
  1966. stepper.enable_axis(X_AXIS);
  1967. stepper.enable_axis(Z_AXIS);
  1968. }
  1969. if (block->steps.y) stepper.enable_axis(Y_AXIS);
  1970. #elif CORE_IS_YZ
  1971. if (block->steps.b || block->steps.c) {
  1972. stepper.enable_axis(Y_AXIS);
  1973. stepper.enable_axis(Z_AXIS);
  1974. }
  1975. if (block->steps.x) stepper.enable_axis(X_AXIS);
  1976. #else
  1977. NUM_AXIS_CODE(
  1978. if (block->steps.x) stepper.enable_axis(X_AXIS),
  1979. if (block->steps.y) stepper.enable_axis(Y_AXIS),
  1980. if (TERN(Z_LATE_ENABLE, 0, block->steps.z)) stepper.enable_axis(Z_AXIS),
  1981. if (block->steps.i) stepper.enable_axis(I_AXIS),
  1982. if (block->steps.j) stepper.enable_axis(J_AXIS),
  1983. if (block->steps.k) stepper.enable_axis(K_AXIS),
  1984. if (block->steps.u) stepper.enable_axis(U_AXIS),
  1985. if (block->steps.v) stepper.enable_axis(V_AXIS),
  1986. if (block->steps.w) stepper.enable_axis(W_AXIS)
  1987. );
  1988. #endif
  1989. #if ANY(CORE_IS_XY, MARKFORGED_XY, MARKFORGED_YX)
  1990. SECONDARY_AXIS_CODE(
  1991. if (block->steps.i) stepper.enable_axis(I_AXIS),
  1992. if (block->steps.j) stepper.enable_axis(J_AXIS),
  1993. if (block->steps.k) stepper.enable_axis(K_AXIS),
  1994. if (block->steps.u) stepper.enable_axis(U_AXIS),
  1995. if (block->steps.v) stepper.enable_axis(V_AXIS),
  1996. if (block->steps.w) stepper.enable_axis(W_AXIS)
  1997. );
  1998. #endif
  1999. // Enable extruder(s)
  2000. #if HAS_EXTRUDERS
  2001. if (esteps) {
  2002. TERN_(AUTO_POWER_CONTROL, powerManager.power_on());
  2003. #if ENABLED(DISABLE_INACTIVE_EXTRUDER) // Enable only the selected extruder
  2004. // Count down all steppers that were recently moved
  2005. LOOP_L_N(i, E_STEPPERS)
  2006. if (g_uc_extruder_last_move[i]) g_uc_extruder_last_move[i]--;
  2007. // Switching Extruder uses one E stepper motor per two nozzles
  2008. #define E_STEPPER_INDEX(E) TERN(SWITCHING_EXTRUDER, (E) / 2, E)
  2009. // Enable all (i.e., both) E steppers for IDEX-style duplication, but only active E steppers for multi-nozzle (i.e., single wide X carriage) duplication
  2010. #define _IS_DUPE(N) TERN0(HAS_DUPLICATION_MODE, (extruder_duplication_enabled && TERN1(MULTI_NOZZLE_DUPLICATION, TEST(duplication_e_mask, N))))
  2011. #define ENABLE_ONE_E(N) do{ \
  2012. if (N == E_STEPPER_INDEX(extruder) || _IS_DUPE(N)) { /* N is 'extruder', or N is duplicating */ \
  2013. stepper.ENABLE_EXTRUDER(N); /* Enable the relevant E stepper... */ \
  2014. g_uc_extruder_last_move[N] = (BLOCK_BUFFER_SIZE) * 2; /* ...and reset its counter */ \
  2015. } \
  2016. else if (!g_uc_extruder_last_move[N]) /* Counter expired since last E stepper enable */ \
  2017. stepper.DISABLE_EXTRUDER(N); /* Disable the E stepper */ \
  2018. }while(0);
  2019. #else
  2020. #define ENABLE_ONE_E(N) stepper.ENABLE_EXTRUDER(N);
  2021. #endif
  2022. REPEAT(E_STEPPERS, ENABLE_ONE_E); // (ENABLE_ONE_E must end with semicolon)
  2023. }
  2024. #endif // HAS_EXTRUDERS
  2025. if (esteps)
  2026. NOLESS(fr_mm_s, settings.min_feedrate_mm_s);
  2027. else
  2028. NOLESS(fr_mm_s, settings.min_travel_feedrate_mm_s);
  2029. const float inverse_millimeters = 1.0f / block->millimeters; // Inverse millimeters to remove multiple divides
  2030. // Calculate inverse time for this move. No divide by zero due to previous checks.
  2031. // Example: At 120mm/s a 60mm move involving XYZ axes takes 0.5s. So this will give 2.0.
  2032. // Example 2: At 120°/s a 60° move involving only rotational axes takes 0.5s. So this will give 2.0.
  2033. float inverse_secs;
  2034. #if BOTH(HAS_ROTATIONAL_AXES, INCH_MODE_SUPPORT)
  2035. inverse_secs = inverse_millimeters * (cartesian_move ? fr_mm_s : LINEAR_UNIT(fr_mm_s));
  2036. #else
  2037. inverse_secs = fr_mm_s * inverse_millimeters;
  2038. #endif
  2039. // Get the number of non busy movements in queue (non busy means that they can be altered)
  2040. const uint8_t moves_queued = nonbusy_movesplanned();
  2041. // Slow down when the buffer starts to empty, rather than wait at the corner for a buffer refill
  2042. #if EITHER(SLOWDOWN, HAS_WIRED_LCD) || defined(XY_FREQUENCY_LIMIT)
  2043. // Segment time in microseconds
  2044. int32_t segment_time_us = LROUND(1000000.0f / inverse_secs);
  2045. #endif
  2046. #if ENABLED(SLOWDOWN)
  2047. #ifndef SLOWDOWN_DIVISOR
  2048. #define SLOWDOWN_DIVISOR 2
  2049. #endif
  2050. if (WITHIN(moves_queued, 2, (BLOCK_BUFFER_SIZE) / (SLOWDOWN_DIVISOR) - 1)) {
  2051. const int32_t time_diff = settings.min_segment_time_us - segment_time_us;
  2052. if (time_diff > 0) {
  2053. // Buffer is draining so add extra time. The amount of time added increases if the buffer is still emptied more.
  2054. const int32_t nst = segment_time_us + LROUND(2 * time_diff / moves_queued);
  2055. inverse_secs = 1000000.0f / nst;
  2056. #if defined(XY_FREQUENCY_LIMIT) || HAS_WIRED_LCD
  2057. segment_time_us = nst;
  2058. #endif
  2059. }
  2060. }
  2061. #endif
  2062. #if HAS_WIRED_LCD
  2063. // Protect the access to the position.
  2064. const bool was_enabled = stepper.suspend();
  2065. block_buffer_runtime_us += segment_time_us;
  2066. block->segment_time_us = segment_time_us;
  2067. if (was_enabled) stepper.wake_up();
  2068. #endif
  2069. block->nominal_speed_sqr = sq(block->millimeters * inverse_secs); // (mm/sec)^2 Always > 0
  2070. block->nominal_rate = CEIL(block->step_event_count * inverse_secs); // (step/sec) Always > 0
  2071. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  2072. if (extruder == FILAMENT_SENSOR_EXTRUDER_NUM) // Only for extruder with filament sensor
  2073. filwidth.advance_e(steps_dist_mm.e);
  2074. #endif
  2075. // Calculate and limit speed in mm/sec (linear) or degrees/sec (rotational)
  2076. xyze_float_t current_speed;
  2077. float speed_factor = 1.0f; // factor <1 decreases speed
  2078. // Linear axes first with less logic
  2079. LOOP_NUM_AXES(i) {
  2080. current_speed[i] = steps_dist_mm[i] * inverse_secs;
  2081. const feedRate_t cs = ABS(current_speed[i]),
  2082. max_fr = settings.max_feedrate_mm_s[i];
  2083. if (cs > max_fr) NOMORE(speed_factor, max_fr / cs);
  2084. }
  2085. // Limit speed on extruders, if any
  2086. #if HAS_EXTRUDERS
  2087. {
  2088. current_speed.e = steps_dist_mm.e * inverse_secs;
  2089. #if HAS_MIXER_SYNC_CHANNEL
  2090. // Move all mixing extruders at the specified rate
  2091. if (mixer.get_current_vtool() == MIXER_AUTORETRACT_TOOL)
  2092. current_speed.e *= MIXING_STEPPERS;
  2093. #endif
  2094. const feedRate_t cs = ABS(current_speed.e),
  2095. max_fr = settings.max_feedrate_mm_s[E_AXIS_N(extruder)]
  2096. * TERN(HAS_MIXER_SYNC_CHANNEL, MIXING_STEPPERS, 1);
  2097. if (cs > max_fr) NOMORE(speed_factor, max_fr / cs); //respect max feedrate on any movement (doesn't matter if E axes only or not)
  2098. #if ENABLED(VOLUMETRIC_EXTRUDER_LIMIT)
  2099. const feedRate_t max_vfr = volumetric_extruder_feedrate_limit[extruder]
  2100. * TERN(HAS_MIXER_SYNC_CHANNEL, MIXING_STEPPERS, 1);
  2101. // TODO: Doesn't work properly for joined segments. Set MIN_STEPS_PER_SEGMENT 1 as workaround.
  2102. if (block->steps.a || block->steps.b || block->steps.c) {
  2103. if (max_vfr > 0 && cs > max_vfr) {
  2104. NOMORE(speed_factor, max_vfr / cs); // respect volumetric extruder limit (if any)
  2105. /* <-- add a slash to enable
  2106. SERIAL_ECHOPGM("volumetric extruder limit enforced: ", (cs * CIRCLE_AREA(filament_size[extruder] * 0.5f)));
  2107. SERIAL_ECHOPGM(" mm^3/s (", cs);
  2108. SERIAL_ECHOPGM(" mm/s) limited to ", (max_vfr * CIRCLE_AREA(filament_size[extruder] * 0.5f)));
  2109. SERIAL_ECHOPGM(" mm^3/s (", max_vfr);
  2110. SERIAL_ECHOLNPGM(" mm/s)");
  2111. //*/
  2112. }
  2113. }
  2114. #endif
  2115. }
  2116. #endif
  2117. #ifdef XY_FREQUENCY_LIMIT
  2118. static axis_bits_t old_direction_bits; // = 0
  2119. if (xy_freq_limit_hz) {
  2120. // Check and limit the xy direction change frequency
  2121. const axis_bits_t direction_change = block->direction_bits ^ old_direction_bits;
  2122. old_direction_bits = block->direction_bits;
  2123. segment_time_us = LROUND(float(segment_time_us) / speed_factor);
  2124. static int32_t xs0, xs1, xs2, ys0, ys1, ys2;
  2125. if (segment_time_us > xy_freq_min_interval_us)
  2126. xs2 = xs1 = ys2 = ys1 = xy_freq_min_interval_us;
  2127. else {
  2128. xs2 = xs1; xs1 = xs0;
  2129. ys2 = ys1; ys1 = ys0;
  2130. }
  2131. xs0 = TEST(direction_change, X_AXIS) ? segment_time_us : xy_freq_min_interval_us;
  2132. ys0 = TEST(direction_change, Y_AXIS) ? segment_time_us : xy_freq_min_interval_us;
  2133. if (segment_time_us < xy_freq_min_interval_us) {
  2134. const int32_t least_xy_segment_time = _MIN(_MAX(xs0, xs1, xs2), _MAX(ys0, ys1, ys2));
  2135. if (least_xy_segment_time < xy_freq_min_interval_us) {
  2136. float freq_xy_feedrate = (speed_factor * least_xy_segment_time) / xy_freq_min_interval_us;
  2137. NOLESS(freq_xy_feedrate, xy_freq_min_speed_factor);
  2138. NOMORE(speed_factor, freq_xy_feedrate);
  2139. }
  2140. }
  2141. }
  2142. #endif // XY_FREQUENCY_LIMIT
  2143. // Correct the speed
  2144. if (speed_factor < 1.0f) {
  2145. current_speed *= speed_factor;
  2146. block->nominal_rate *= speed_factor;
  2147. block->nominal_speed_sqr = block->nominal_speed_sqr * sq(speed_factor);
  2148. }
  2149. // Compute and limit the acceleration rate for the trapezoid generator.
  2150. const float steps_per_mm = block->step_event_count * inverse_millimeters;
  2151. uint32_t accel;
  2152. if (NUM_AXIS_GANG(
  2153. !block->steps.a, && !block->steps.b, && !block->steps.c,
  2154. && !block->steps.i, && !block->steps.j, && !block->steps.k,
  2155. && !block->steps.u, && !block->steps.v, && !block->steps.w)
  2156. ) { // Is this a retract / recover move?
  2157. accel = CEIL(settings.retract_acceleration * steps_per_mm); // Convert to: acceleration steps/sec^2
  2158. TERN_(LIN_ADVANCE, block->use_advance_lead = false); // No linear advance for simple retract/recover
  2159. }
  2160. else {
  2161. #define LIMIT_ACCEL_LONG(AXIS,INDX) do{ \
  2162. if (block->steps[AXIS] && max_acceleration_steps_per_s2[AXIS+INDX] < accel) { \
  2163. const uint32_t max_possible = max_acceleration_steps_per_s2[AXIS+INDX] * block->step_event_count / block->steps[AXIS]; \
  2164. NOMORE(accel, max_possible); \
  2165. } \
  2166. }while(0)
  2167. #define LIMIT_ACCEL_FLOAT(AXIS,INDX) do{ \
  2168. if (block->steps[AXIS] && max_acceleration_steps_per_s2[AXIS+INDX] < accel) { \
  2169. const float max_possible = float(max_acceleration_steps_per_s2[AXIS+INDX]) * float(block->step_event_count) / float(block->steps[AXIS]); \
  2170. NOMORE(accel, max_possible); \
  2171. } \
  2172. }while(0)
  2173. // Start with print or travel acceleration
  2174. accel = CEIL((esteps ? settings.acceleration : settings.travel_acceleration) * steps_per_mm);
  2175. #if ENABLED(LIN_ADVANCE)
  2176. // Linear advance is currently not ready for HAS_I_AXIS
  2177. #define MAX_E_JERK(N) TERN(HAS_LINEAR_E_JERK, max_e_jerk[E_INDEX_N(N)], max_jerk.e)
  2178. /**
  2179. * Use LIN_ADVANCE for blocks if all these are true:
  2180. *
  2181. * esteps : This is a print move, because we checked for A, B, C steps before.
  2182. *
  2183. * extruder_advance_K[active_extruder] : There is an advance factor set for this extruder.
  2184. *
  2185. * de > 0 : Extruder is running forward (e.g., for "Wipe while retracting" (Slic3r) or "Combing" (Cura) moves)
  2186. */
  2187. block->use_advance_lead = esteps
  2188. && extruder_advance_K[active_extruder]
  2189. && de > 0;
  2190. if (block->use_advance_lead) {
  2191. block->e_D_ratio = (target_float.e - position_float.e) /
  2192. #if IS_KINEMATIC
  2193. block->millimeters
  2194. #else
  2195. SQRT(sq(target_float.x - position_float.x)
  2196. + sq(target_float.y - position_float.y)
  2197. + sq(target_float.z - position_float.z))
  2198. #endif
  2199. ;
  2200. // 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!
  2201. // 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.
  2202. if (block->e_D_ratio > 3.0f)
  2203. block->use_advance_lead = false;
  2204. else {
  2205. const uint32_t max_accel_steps_per_s2 = MAX_E_JERK(extruder) / (extruder_advance_K[active_extruder] * block->e_D_ratio) * steps_per_mm;
  2206. if (TERN0(LA_DEBUG, accel > max_accel_steps_per_s2))
  2207. SERIAL_ECHOLNPGM("Acceleration limited.");
  2208. NOMORE(accel, max_accel_steps_per_s2);
  2209. }
  2210. }
  2211. #endif
  2212. // Limit acceleration per axis
  2213. if (block->step_event_count <= acceleration_long_cutoff) {
  2214. LOGICAL_AXIS_CODE(
  2215. LIMIT_ACCEL_LONG(E_AXIS, E_INDEX_N(extruder)),
  2216. LIMIT_ACCEL_LONG(A_AXIS, 0),
  2217. LIMIT_ACCEL_LONG(B_AXIS, 0),
  2218. LIMIT_ACCEL_LONG(C_AXIS, 0),
  2219. LIMIT_ACCEL_LONG(I_AXIS, 0),
  2220. LIMIT_ACCEL_LONG(J_AXIS, 0),
  2221. LIMIT_ACCEL_LONG(K_AXIS, 0),
  2222. LIMIT_ACCEL_LONG(U_AXIS, 0),
  2223. LIMIT_ACCEL_LONG(V_AXIS, 0),
  2224. LIMIT_ACCEL_LONG(W_AXIS, 0)
  2225. );
  2226. }
  2227. else {
  2228. LOGICAL_AXIS_CODE(
  2229. LIMIT_ACCEL_FLOAT(E_AXIS, E_INDEX_N(extruder)),
  2230. LIMIT_ACCEL_FLOAT(A_AXIS, 0),
  2231. LIMIT_ACCEL_FLOAT(B_AXIS, 0),
  2232. LIMIT_ACCEL_FLOAT(C_AXIS, 0),
  2233. LIMIT_ACCEL_FLOAT(I_AXIS, 0),
  2234. LIMIT_ACCEL_FLOAT(J_AXIS, 0),
  2235. LIMIT_ACCEL_FLOAT(K_AXIS, 0),
  2236. LIMIT_ACCEL_FLOAT(U_AXIS, 0),
  2237. LIMIT_ACCEL_FLOAT(V_AXIS, 0),
  2238. LIMIT_ACCEL_FLOAT(W_AXIS, 0)
  2239. );
  2240. }
  2241. }
  2242. block->acceleration_steps_per_s2 = accel;
  2243. block->acceleration = accel / steps_per_mm;
  2244. #if DISABLED(S_CURVE_ACCELERATION)
  2245. block->acceleration_rate = (uint32_t)(accel * (float(1UL << 24) / (STEPPER_TIMER_RATE)));
  2246. #endif
  2247. #if ENABLED(LIN_ADVANCE)
  2248. if (block->use_advance_lead) {
  2249. block->advance_speed = (STEPPER_TIMER_RATE) / (extruder_advance_K[active_extruder] * block->e_D_ratio * block->acceleration * settings.axis_steps_per_mm[E_AXIS_N(extruder)]);
  2250. #if ENABLED(LA_DEBUG)
  2251. if (extruder_advance_K[active_extruder] * block->e_D_ratio * block->acceleration * 2 < SQRT(block->nominal_speed_sqr) * block->e_D_ratio)
  2252. SERIAL_ECHOLNPGM("More than 2 steps per eISR loop executed.");
  2253. if (block->advance_speed < 200)
  2254. SERIAL_ECHOLNPGM("eISR running at > 10kHz.");
  2255. #endif
  2256. }
  2257. #endif
  2258. float vmax_junction_sqr; // Initial limit on the segment entry velocity (mm/s)^2
  2259. #if HAS_JUNCTION_DEVIATION
  2260. /**
  2261. * Compute maximum allowable entry speed at junction by centripetal acceleration approximation.
  2262. * Let a circle be tangent to both previous and current path line segments, where the junction
  2263. * deviation is defined as the distance from the junction to the closest edge of the circle,
  2264. * colinear with the circle center. The circular segment joining the two paths represents the
  2265. * path of centripetal acceleration. Solve for max velocity based on max acceleration about the
  2266. * radius of the circle, defined indirectly by junction deviation. This may be also viewed as
  2267. * path width or max_jerk in the previous Grbl version. This approach does not actually deviate
  2268. * from path, but used as a robust way to compute cornering speeds, as it takes into account the
  2269. * nonlinearities of both the junction angle and junction velocity.
  2270. *
  2271. * NOTE: If the junction deviation value is finite, Grbl executes the motions in an exact path
  2272. * mode (G61). If the junction deviation value is zero, Grbl will execute the motion in an exact
  2273. * stop mode (G61.1) manner. In the future, if continuous mode (G64) is desired, the math here
  2274. * is exactly the same. Instead of motioning all the way to junction point, the machine will
  2275. * just follow the arc circle defined here. The Arduino doesn't have the CPU cycles to perform
  2276. * a continuous mode path, but ARM-based microcontrollers most certainly do.
  2277. *
  2278. * NOTE: The max junction speed is a fixed value, since machine acceleration limits cannot be
  2279. * changed dynamically during operation nor can the line move geometry. This must be kept in
  2280. * memory in the event of a feedrate override changing the nominal speeds of blocks, which can
  2281. * change the overall maximum entry speed conditions of all blocks.
  2282. *
  2283. * #######
  2284. * https://github.com/MarlinFirmware/Marlin/issues/10341#issuecomment-388191754
  2285. *
  2286. * hoffbaked: on May 10 2018 tuned and improved the GRBL algorithm for Marlin:
  2287. Okay! It seems to be working good. I somewhat arbitrarily cut it off at 1mm
  2288. on then on anything with less sides than an octagon. With this, and the
  2289. reverse pass actually recalculating things, a corner acceleration value
  2290. of 1000 junction deviation of .05 are pretty reasonable. If the cycles
  2291. can be spared, a better acos could be used. For all I know, it may be
  2292. already calculated in a different place. */
  2293. // Unit vector of previous path line segment
  2294. static xyze_float_t prev_unit_vec;
  2295. xyze_float_t unit_vec =
  2296. #if HAS_DIST_MM_ARG
  2297. cart_dist_mm
  2298. #else
  2299. LOGICAL_AXIS_ARRAY(steps_dist_mm.e, steps_dist_mm.x, steps_dist_mm.y, steps_dist_mm.z, steps_dist_mm.i, steps_dist_mm.j, steps_dist_mm.k, steps_dist_mm.u, steps_dist_mm.v, steps_dist_mm.w)
  2300. #endif
  2301. ;
  2302. /**
  2303. * On CoreXY the length of the vector [A,B] is SQRT(2) times the length of the head movement vector [X,Y].
  2304. * So taking Z and E into account, we cannot scale to a unit vector with "inverse_millimeters".
  2305. * => normalize the complete junction vector.
  2306. * Elsewise, when needed JD will factor-in the E component
  2307. */
  2308. if (ANY(IS_CORE, MARKFORGED_XY, MARKFORGED_YX) || esteps > 0)
  2309. normalize_junction_vector(unit_vec); // Normalize with XYZE components
  2310. else
  2311. unit_vec *= inverse_millimeters; // Use pre-calculated (1 / SQRT(x^2 + y^2 + z^2))
  2312. // Skip first block or when previous_nominal_speed is used as a flag for homing and offset cycles.
  2313. if (moves_queued && !UNEAR_ZERO(previous_nominal_speed_sqr)) {
  2314. // Compute cosine of angle between previous and current path. (prev_unit_vec is negative)
  2315. // NOTE: Max junction velocity is computed without sin() or acos() by trig half angle identity.
  2316. float junction_cos_theta = LOGICAL_AXIS_GANG(
  2317. + (-prev_unit_vec.e * unit_vec.e),
  2318. (-prev_unit_vec.x * unit_vec.x),
  2319. + (-prev_unit_vec.y * unit_vec.y),
  2320. + (-prev_unit_vec.z * unit_vec.z),
  2321. + (-prev_unit_vec.i * unit_vec.i),
  2322. + (-prev_unit_vec.j * unit_vec.j),
  2323. + (-prev_unit_vec.k * unit_vec.k),
  2324. + (-prev_unit_vec.u * unit_vec.u),
  2325. + (-prev_unit_vec.v * unit_vec.v),
  2326. + (-prev_unit_vec.w * unit_vec.w)
  2327. );
  2328. // NOTE: Computed without any expensive trig, sin() or acos(), by trig half angle identity of cos(theta).
  2329. if (junction_cos_theta > 0.999999f) {
  2330. // For a 0 degree acute junction, just set minimum junction speed.
  2331. vmax_junction_sqr = sq(float(MINIMUM_PLANNER_SPEED));
  2332. }
  2333. else {
  2334. NOLESS(junction_cos_theta, -0.999999f); // Check for numerical round-off to avoid divide by zero.
  2335. // Convert delta vector to unit vector
  2336. xyze_float_t junction_unit_vec = unit_vec - prev_unit_vec;
  2337. normalize_junction_vector(junction_unit_vec);
  2338. const float junction_acceleration = limit_value_by_axis_maximum(block->acceleration, junction_unit_vec),
  2339. sin_theta_d2 = SQRT(0.5f * (1.0f - junction_cos_theta)); // Trig half angle identity. Always positive.
  2340. vmax_junction_sqr = junction_acceleration * junction_deviation_mm * sin_theta_d2 / (1.0f - sin_theta_d2);
  2341. #if ENABLED(JD_HANDLE_SMALL_SEGMENTS)
  2342. // For small moves with >135° junction (octagon) find speed for approximate arc
  2343. if (block->millimeters < 1 && junction_cos_theta < -0.7071067812f) {
  2344. #if ENABLED(JD_USE_MATH_ACOS)
  2345. #error "TODO: Inline maths with the MCU / FPU."
  2346. #elif ENABLED(JD_USE_LOOKUP_TABLE)
  2347. // Fast acos approximation (max. error +-0.01 rads)
  2348. // Based on LUT table and linear interpolation
  2349. /**
  2350. * // Generate the JD Lookup Table
  2351. * constexpr float c = 1.00751495f; // Correction factor to center error around 0
  2352. * for (int i = 0; i < jd_lut_count - 1; ++i) {
  2353. * const float x0 = (sq(i) - 1) / sq(i),
  2354. * y0 = acos(x0) * (i == 0 ? 1 : c),
  2355. * x1 = i < jd_lut_count - 1 ? 0.5 * x0 + 0.5 : 0.999999f,
  2356. * y1 = acos(x1) * (i < jd_lut_count - 1 ? c : 1);
  2357. * jd_lut_k[i] = (y0 - y1) / (x0 - x1);
  2358. * jd_lut_b[i] = (y1 * x0 - y0 * x1) / (x0 - x1);
  2359. * }
  2360. *
  2361. * // Compute correction factor (Set c to 1.0f first!)
  2362. * float min = INFINITY, max = -min;
  2363. * for (float t = 0; t <= 1; t += 0.0003f) {
  2364. * const float e = acos(t) / approx(t);
  2365. * if (isfinite(e)) {
  2366. * if (e < min) min = e;
  2367. * if (e > max) max = e;
  2368. * }
  2369. * }
  2370. * fprintf(stderr, "%.9gf, ", (min + max) / 2);
  2371. */
  2372. static constexpr int16_t jd_lut_count = 16;
  2373. static constexpr uint16_t jd_lut_tll = _BV(jd_lut_count - 1);
  2374. static constexpr int16_t jd_lut_tll0 = __builtin_clz(jd_lut_tll) + 1; // i.e., 16 - jd_lut_count + 1
  2375. static constexpr float jd_lut_k[jd_lut_count] PROGMEM = {
  2376. -1.03145837f, -1.30760646f, -1.75205851f, -2.41705704f,
  2377. -3.37769222f, -4.74888992f, -6.69649887f, -9.45661736f,
  2378. -13.3640480f, -18.8928222f, -26.7136841f, -37.7754593f,
  2379. -53.4201813f, -75.5458374f, -106.836761f, -218.532821f };
  2380. static constexpr float jd_lut_b[jd_lut_count] PROGMEM = {
  2381. 1.57079637f, 1.70887053f, 2.04220939f, 2.62408352f,
  2382. 3.52467871f, 4.85302639f, 6.77020454f, 9.50875854f,
  2383. 13.4009285f, 18.9188995f, 26.7321243f, 37.7885055f,
  2384. 53.4293975f, 75.5523529f, 106.841369f, 218.534011f };
  2385. const float neg = junction_cos_theta < 0 ? -1 : 1,
  2386. t = neg * junction_cos_theta;
  2387. const int16_t idx = (t < 0.00000003f) ? 0 : __builtin_clz(uint16_t((1.0f - t) * jd_lut_tll)) - jd_lut_tll0;
  2388. float junction_theta = t * pgm_read_float(&jd_lut_k[idx]) + pgm_read_float(&jd_lut_b[idx]);
  2389. if (neg > 0) junction_theta = RADIANS(180) - junction_theta; // acos(-t)
  2390. #else
  2391. // Fast acos(-t) approximation (max. error +-0.033rad = 1.89°)
  2392. // Based on MinMax polynomial published by W. Randolph Franklin, see
  2393. // https://wrf.ecse.rpi.edu/Research/Short_Notes/arcsin/onlyelem.html
  2394. // acos( t) = pi / 2 - asin(x)
  2395. // acos(-t) = pi - acos(t) ... pi / 2 + asin(x)
  2396. const float neg = junction_cos_theta < 0 ? -1 : 1,
  2397. t = neg * junction_cos_theta,
  2398. asinx = 0.032843707f
  2399. + t * (-1.451838349f
  2400. + t * ( 29.66153956f
  2401. + t * (-131.1123477f
  2402. + t * ( 262.8130562f
  2403. + t * (-242.7199627f
  2404. + t * ( 84.31466202f ) ))))),
  2405. junction_theta = RADIANS(90) + neg * asinx; // acos(-t)
  2406. // NOTE: junction_theta bottoms out at 0.033 which avoids divide by 0.
  2407. #endif
  2408. const float limit_sqr = (block->millimeters * junction_acceleration) / junction_theta;
  2409. NOMORE(vmax_junction_sqr, limit_sqr);
  2410. }
  2411. #endif // JD_HANDLE_SMALL_SEGMENTS
  2412. }
  2413. // Get the lowest speed
  2414. vmax_junction_sqr = _MIN(vmax_junction_sqr, block->nominal_speed_sqr, previous_nominal_speed_sqr);
  2415. }
  2416. else // Init entry speed to zero. Assume it starts from rest. Planner will correct this later.
  2417. vmax_junction_sqr = 0;
  2418. prev_unit_vec = unit_vec;
  2419. #endif
  2420. #ifdef USE_CACHED_SQRT
  2421. #define CACHED_SQRT(N, V) \
  2422. static float saved_V, N; \
  2423. if (V != saved_V) { N = SQRT(V); saved_V = V; }
  2424. #else
  2425. #define CACHED_SQRT(N, V) const float N = SQRT(V)
  2426. #endif
  2427. #if HAS_CLASSIC_JERK
  2428. /**
  2429. * Adapted from Průša MKS firmware
  2430. * https://github.com/prusa3d/Prusa-Firmware
  2431. */
  2432. CACHED_SQRT(nominal_speed, block->nominal_speed_sqr);
  2433. // Exit speed limited by a jerk to full halt of a previous last segment
  2434. static float previous_safe_speed;
  2435. // Start with a safe speed (from which the machine may halt to stop immediately).
  2436. float safe_speed = nominal_speed;
  2437. #ifndef TRAVEL_EXTRA_XYJERK
  2438. #define TRAVEL_EXTRA_XYJERK 0
  2439. #endif
  2440. const float extra_xyjerk = TERN0(HAS_EXTRUDERS, de <= 0) ? TRAVEL_EXTRA_XYJERK : 0;
  2441. uint8_t limited = 0;
  2442. TERN(HAS_LINEAR_E_JERK, LOOP_NUM_AXES, LOOP_LOGICAL_AXES)(i) {
  2443. const float jerk = ABS(current_speed[i]), // cs : Starting from zero, change in speed for this axis
  2444. maxj = (max_jerk[i] + (i == X_AXIS || i == Y_AXIS ? extra_xyjerk : 0.0f)); // mj : The max jerk setting for this axis
  2445. if (jerk > maxj) { // cs > mj : New current speed too fast?
  2446. if (limited) { // limited already?
  2447. const float mjerk = nominal_speed * maxj; // ns*mj
  2448. if (jerk * safe_speed > mjerk) safe_speed = mjerk / jerk; // ns*mj/cs
  2449. }
  2450. else {
  2451. safe_speed *= maxj / jerk; // Initial limit: ns*mj/cs
  2452. ++limited; // Initially limited
  2453. }
  2454. }
  2455. }
  2456. float vmax_junction;
  2457. if (moves_queued && !UNEAR_ZERO(previous_nominal_speed_sqr)) {
  2458. // Estimate a maximum velocity allowed at a joint of two successive segments.
  2459. // If this maximum velocity allowed is lower than the minimum of the entry / exit safe velocities,
  2460. // then the machine is not coasting anymore and the safe entry / exit velocities shall be used.
  2461. // Factor to multiply the previous / current nominal velocities to get componentwise limited velocities.
  2462. float v_factor = 1;
  2463. limited = 0;
  2464. // The junction velocity will be shared between successive segments. Limit the junction velocity to their minimum.
  2465. // Pick the smaller of the nominal speeds. Higher speed shall not be achieved at the junction during coasting.
  2466. CACHED_SQRT(previous_nominal_speed, previous_nominal_speed_sqr);
  2467. float smaller_speed_factor = 1.0f;
  2468. if (nominal_speed < previous_nominal_speed) {
  2469. vmax_junction = nominal_speed;
  2470. smaller_speed_factor = vmax_junction / previous_nominal_speed;
  2471. }
  2472. else
  2473. vmax_junction = previous_nominal_speed;
  2474. // Now limit the jerk in all axes.
  2475. TERN(HAS_LINEAR_E_JERK, LOOP_NUM_AXES, LOOP_LOGICAL_AXES)(axis) {
  2476. // Limit an axis. We have to differentiate: coasting, reversal of an axis, full stop.
  2477. float v_exit = previous_speed[axis] * smaller_speed_factor,
  2478. v_entry = current_speed[axis];
  2479. if (limited) {
  2480. v_exit *= v_factor;
  2481. v_entry *= v_factor;
  2482. }
  2483. // Calculate jerk depending on whether the axis is coasting in the same direction or reversing.
  2484. const float jerk = (v_exit > v_entry)
  2485. ? // coasting axis reversal
  2486. ( (v_entry > 0 || v_exit < 0) ? (v_exit - v_entry) : _MAX(v_exit, -v_entry) )
  2487. : // v_exit <= v_entry coasting axis reversal
  2488. ( (v_entry < 0 || v_exit > 0) ? (v_entry - v_exit) : _MAX(-v_exit, v_entry) );
  2489. const float maxj = (max_jerk[axis] + (axis == X_AXIS || axis == Y_AXIS ? extra_xyjerk : 0.0f));
  2490. if (jerk > maxj) {
  2491. v_factor *= maxj / jerk;
  2492. ++limited;
  2493. }
  2494. }
  2495. if (limited) vmax_junction *= v_factor;
  2496. // Now the transition velocity is known, which maximizes the shared exit / entry velocity while
  2497. // respecting the jerk factors, it may be possible, that applying separate safe exit / entry velocities will achieve faster prints.
  2498. const float vmax_junction_threshold = vmax_junction * 0.99f;
  2499. if (previous_safe_speed > vmax_junction_threshold && safe_speed > vmax_junction_threshold)
  2500. vmax_junction = safe_speed;
  2501. }
  2502. else
  2503. vmax_junction = safe_speed;
  2504. previous_safe_speed = safe_speed;
  2505. #if HAS_JUNCTION_DEVIATION
  2506. NOMORE(vmax_junction_sqr, sq(vmax_junction)); // Throttle down to max speed
  2507. #else
  2508. vmax_junction_sqr = sq(vmax_junction); // Go up or down to the new speed
  2509. #endif
  2510. #endif // Classic Jerk Limiting
  2511. // Max entry speed of this block equals the max exit speed of the previous block.
  2512. block->max_entry_speed_sqr = vmax_junction_sqr;
  2513. // Initialize block entry speed. Compute based on deceleration to user-defined MINIMUM_PLANNER_SPEED.
  2514. const float v_allowable_sqr = max_allowable_speed_sqr(-block->acceleration, sq(float(MINIMUM_PLANNER_SPEED)), block->millimeters);
  2515. // Start with the minimum allowed speed
  2516. block->entry_speed_sqr = sq(float(MINIMUM_PLANNER_SPEED));
  2517. // Initialize planner efficiency flags
  2518. // Set flag if block will always reach maximum junction speed regardless of entry/exit speeds.
  2519. // If a block can de/ac-celerate from nominal speed to zero within the length of the block, then
  2520. // the current block and next block junction speeds are guaranteed to always be at their maximum
  2521. // junction speeds in deceleration and acceleration, respectively. This is due to how the current
  2522. // block nominal speed limits both the current and next maximum junction speeds. Hence, in both
  2523. // the reverse and forward planners, the corresponding block junction speed will always be at the
  2524. // the maximum junction speed and may always be ignored for any speed reduction checks.
  2525. block->flag.set_nominal(block->nominal_speed_sqr <= v_allowable_sqr);
  2526. // Update previous path unit_vector and nominal speed
  2527. previous_speed = current_speed;
  2528. previous_nominal_speed_sqr = block->nominal_speed_sqr;
  2529. position = target; // Update the position
  2530. #if ENABLED(POWER_LOSS_RECOVERY)
  2531. block->sdpos = recovery.command_sdpos();
  2532. block->start_position = position_float.asLogical();
  2533. #endif
  2534. TERN_(HAS_POSITION_FLOAT, position_float = target_float);
  2535. TERN_(GRADIENT_MIX, mixer.gradient_control(target_float.z));
  2536. return true; // Movement was accepted
  2537. } // _populate_block()
  2538. /**
  2539. * Planner::buffer_sync_block
  2540. * Add a block to the buffer that just updates the position
  2541. * @param sync_flag BLOCK_FLAG_SYNC_FANS & BLOCK_FLAG_LASER_PWR
  2542. * Supports LASER_SYNCHRONOUS_M106_M107 and LASER_POWER_SYNC power sync block buffer queueing.
  2543. */
  2544. void Planner::buffer_sync_block(const BlockFlagBit sync_flag/*=BLOCK_BIT_SYNC_POSITION*/) {
  2545. // Wait for the next available block
  2546. uint8_t next_buffer_head;
  2547. block_t * const block = get_next_free_block(next_buffer_head);
  2548. // Clear block
  2549. memset(block, 0, sizeof(block_t));
  2550. block->flag.apply(sync_flag);
  2551. block->position = position;
  2552. #if ENABLED(BACKLASH_COMPENSATION)
  2553. LOOP_NUM_AXES(axis) block->position[axis] += backlash.get_applied_steps((AxisEnum)axis);
  2554. #endif
  2555. #if BOTH(HAS_FAN, LASER_SYNCHRONOUS_M106_M107)
  2556. FANS_LOOP(i) block->fan_speed[i] = thermalManager.fan_speed[i];
  2557. #endif
  2558. /**
  2559. * M3-based power setting can be processed inline with a laser power sync block.
  2560. * During active moves cutter.power is processed immediately, otherwise on the next move.
  2561. */
  2562. TERN_(LASER_POWER_SYNC, block->laser.power = cutter.power);
  2563. // If this is the first added movement, reload the delay, otherwise, cancel it.
  2564. if (block_buffer_head == block_buffer_tail) {
  2565. // If it was the first queued block, restart the 1st block delivery delay, to
  2566. // give the planner an opportunity to queue more movements and plan them
  2567. // As there are no queued movements, the Stepper ISR will not touch this
  2568. // variable, so there is no risk setting this here (but it MUST be done
  2569. // before the following line!!)
  2570. delay_before_delivering = BLOCK_DELAY_FOR_1ST_MOVE;
  2571. }
  2572. block_buffer_head = next_buffer_head;
  2573. stepper.wake_up();
  2574. } // buffer_sync_block()
  2575. /**
  2576. * Planner::buffer_segment
  2577. *
  2578. * Add a new linear movement to the buffer in axis units.
  2579. *
  2580. * Leveling and kinematics should be applied ahead of calling this.
  2581. *
  2582. * a,b,c,e - target positions in mm and/or degrees
  2583. * fr_mm_s - (target) speed of the move
  2584. * extruder - target extruder
  2585. * millimeters - the length of the movement, if known
  2586. *
  2587. * Return 'false' if no segment was queued due to cleaning, cold extrusion, full queue, etc.
  2588. */
  2589. bool Planner::buffer_segment(const abce_pos_t &abce
  2590. OPTARG(HAS_DIST_MM_ARG, const xyze_float_t &cart_dist_mm)
  2591. , const_feedRate_t fr_mm_s, const uint8_t extruder/*=active_extruder*/, const_float_t millimeters/*=0.0*/
  2592. ) {
  2593. // If we are cleaning, do not accept queuing of movements
  2594. if (cleaning_buffer_counter) return false;
  2595. // When changing extruders recalculate steps corresponding to the E position
  2596. #if ENABLED(DISTINCT_E_FACTORS)
  2597. if (last_extruder != extruder && settings.axis_steps_per_mm[E_AXIS_N(extruder)] != settings.axis_steps_per_mm[E_AXIS_N(last_extruder)]) {
  2598. position.e = LROUND(position.e * settings.axis_steps_per_mm[E_AXIS_N(extruder)] * mm_per_step[E_AXIS_N(last_extruder)]);
  2599. last_extruder = extruder;
  2600. }
  2601. #endif
  2602. // The target position of the tool in absolute steps
  2603. // Calculate target position in absolute steps
  2604. const abce_long_t target = {
  2605. LOGICAL_AXIS_LIST(
  2606. int32_t(LROUND(abce.e * settings.axis_steps_per_mm[E_AXIS_N(extruder)])),
  2607. int32_t(LROUND(abce.a * settings.axis_steps_per_mm[A_AXIS])),
  2608. int32_t(LROUND(abce.b * settings.axis_steps_per_mm[B_AXIS])),
  2609. int32_t(LROUND(abce.c * settings.axis_steps_per_mm[C_AXIS])),
  2610. int32_t(LROUND(abce.i * settings.axis_steps_per_mm[I_AXIS])),
  2611. int32_t(LROUND(abce.j * settings.axis_steps_per_mm[J_AXIS])),
  2612. int32_t(LROUND(abce.k * settings.axis_steps_per_mm[K_AXIS])),
  2613. int32_t(LROUND(abce.u * settings.axis_steps_per_mm[U_AXIS])),
  2614. int32_t(LROUND(abce.v * settings.axis_steps_per_mm[V_AXIS])),
  2615. int32_t(LROUND(abce.w * settings.axis_steps_per_mm[W_AXIS]))
  2616. )
  2617. };
  2618. #if HAS_POSITION_FLOAT
  2619. const xyze_pos_t target_float = abce;
  2620. #endif
  2621. #if HAS_EXTRUDERS
  2622. // DRYRUN prevents E moves from taking place
  2623. if (DEBUGGING(DRYRUN) || TERN0(CANCEL_OBJECTS, cancelable.skipping)) {
  2624. position.e = target.e;
  2625. TERN_(HAS_POSITION_FLOAT, position_float.e = abce.e);
  2626. }
  2627. #endif
  2628. /* <-- add a slash to enable
  2629. SERIAL_ECHOPGM(" buffer_segment FR:", fr_mm_s);
  2630. #if IS_KINEMATIC
  2631. SERIAL_ECHOPGM(" A:", abce.a, " (", position.a, "->", target.a, ") B:", abce.b);
  2632. #else
  2633. SERIAL_ECHOPGM_P(SP_X_LBL, abce.a);
  2634. SERIAL_ECHOPGM(" (", position.x, "->", target.x);
  2635. SERIAL_CHAR(')');
  2636. SERIAL_ECHOPGM_P(SP_Y_LBL, abce.b);
  2637. #endif
  2638. SERIAL_ECHOPGM(" (", position.y, "->", target.y);
  2639. #if HAS_Z_AXIS
  2640. #if ENABLED(DELTA)
  2641. SERIAL_ECHOPGM(") C:", abce.c);
  2642. #else
  2643. SERIAL_CHAR(')');
  2644. SERIAL_ECHOPGM_P(SP_Z_LBL, abce.c);
  2645. #endif
  2646. SERIAL_ECHOPGM(" (", position.z, "->", target.z);
  2647. SERIAL_CHAR(')');
  2648. #endif
  2649. #if HAS_I_AXIS
  2650. SERIAL_ECHOPGM_P(SP_I_LBL, abce.i);
  2651. SERIAL_ECHOPGM(" (", position.i, "->", target.i);
  2652. SERIAL_CHAR(')');
  2653. #endif
  2654. #if HAS_J_AXIS
  2655. SERIAL_ECHOPGM_P(SP_J_LBL, abce.j);
  2656. SERIAL_ECHOPGM(" (", position.j, "->", target.j);
  2657. SERIAL_CHAR(')');
  2658. #endif
  2659. #if HAS_K_AXIS
  2660. SERIAL_ECHOPGM_P(SP_K_LBL, abce.k);
  2661. SERIAL_ECHOPGM(" (", position.k, "->", target.k);
  2662. SERIAL_CHAR(')');
  2663. #endif
  2664. #if HAS_U_AXIS
  2665. SERIAL_ECHOPGM_P(SP_U_LBL, abce.u);
  2666. SERIAL_ECHOPGM(" (", position.u, "->", target.u);
  2667. SERIAL_CHAR(')');
  2668. #endif
  2669. #if HAS_V_AXIS
  2670. SERIAL_ECHOPGM_P(SP_V_LBL, abce.v);
  2671. SERIAL_ECHOPGM(" (", position.v, "->", target.v);
  2672. SERIAL_CHAR(')');
  2673. #endif
  2674. #if HAS_W_AXIS
  2675. SERIAL_ECHOPGM_P(SP_W_LBL, abce.w);
  2676. SERIAL_ECHOPGM(" (", position.w, "->", target.w);
  2677. SERIAL_CHAR(')');
  2678. #endif
  2679. #if HAS_EXTRUDERS
  2680. SERIAL_ECHOPGM_P(SP_E_LBL, abce.e);
  2681. SERIAL_ECHOLNPGM(" (", position.e, "->", target.e, ")");
  2682. #else
  2683. SERIAL_EOL();
  2684. #endif
  2685. //*/
  2686. // Queue the movement. Return 'false' if the move was not queued.
  2687. if (!_buffer_steps(target
  2688. OPTARG(HAS_POSITION_FLOAT, target_float)
  2689. OPTARG(HAS_DIST_MM_ARG, cart_dist_mm)
  2690. , fr_mm_s, extruder, millimeters)
  2691. ) return false;
  2692. stepper.wake_up();
  2693. return true;
  2694. } // buffer_segment()
  2695. /**
  2696. * Add a new linear movement to the buffer.
  2697. * The target is cartesian. It's translated to
  2698. * delta/scara if needed.
  2699. *
  2700. * cart - target position in mm or degrees
  2701. * fr_mm_s - (target) speed of the move (mm/s)
  2702. * extruder - target extruder
  2703. * millimeters - the length of the movement, if known
  2704. * inv_duration - the reciprocal if the duration of the movement, if known (kinematic only if feeedrate scaling is enabled)
  2705. */
  2706. bool Planner::buffer_line(const xyze_pos_t &cart, const_feedRate_t fr_mm_s, const uint8_t extruder/*=active_extruder*/, const float millimeters/*=0.0*/
  2707. OPTARG(SCARA_FEEDRATE_SCALING, const_float_t inv_duration/*=0.0*/)
  2708. ) {
  2709. xyze_pos_t machine = cart;
  2710. TERN_(HAS_POSITION_MODIFIERS, apply_modifiers(machine));
  2711. #if IS_KINEMATIC
  2712. #if HAS_JUNCTION_DEVIATION
  2713. const xyze_pos_t cart_dist_mm = LOGICAL_AXIS_ARRAY(
  2714. cart.e - position_cart.e,
  2715. cart.x - position_cart.x, cart.y - position_cart.y, cart.z - position_cart.z,
  2716. cart.i - position_cart.i, cart.j - position_cart.j, cart.k - position_cart.k,
  2717. cart.u - position_cart.u, cart.v - position_cart.v, cart.w - position_cart.w
  2718. );
  2719. #else
  2720. const xyz_pos_t cart_dist_mm = NUM_AXIS_ARRAY(
  2721. cart.x - position_cart.x, cart.y - position_cart.y, cart.z - position_cart.z,
  2722. cart.i - position_cart.i, cart.j - position_cart.j, cart.k - position_cart.k,
  2723. cart.u - position_cart.u, cart.v - position_cart.v, cart.w - position_cart.w
  2724. );
  2725. #endif
  2726. const float mm = millimeters ?: (cart_dist_mm.x || cart_dist_mm.y) ? cart_dist_mm.magnitude() : TERN0(HAS_Z_AXIS, ABS(cart_dist_mm.z));
  2727. // Cartesian XYZ to kinematic ABC, stored in global 'delta'
  2728. inverse_kinematics(machine);
  2729. #if ENABLED(SCARA_FEEDRATE_SCALING)
  2730. // For SCARA scale the feedrate from mm/s to degrees/s
  2731. // i.e., Complete the angular vector in the given time.
  2732. const float duration_recip = inv_duration ?: fr_mm_s / mm;
  2733. const xyz_pos_t diff = delta - position_float;
  2734. const feedRate_t feedrate = diff.magnitude() * duration_recip;
  2735. #else
  2736. const feedRate_t feedrate = fr_mm_s;
  2737. #endif
  2738. TERN_(HAS_EXTRUDERS, delta.e = machine.e);
  2739. if (buffer_segment(delta OPTARG(HAS_DIST_MM_ARG, cart_dist_mm), feedrate, extruder, mm)) {
  2740. position_cart = cart;
  2741. return true;
  2742. }
  2743. return false;
  2744. #else
  2745. return buffer_segment(machine, fr_mm_s, extruder, millimeters);
  2746. #endif
  2747. } // buffer_line()
  2748. #if ENABLED(DIRECT_STEPPING)
  2749. void Planner::buffer_page(const page_idx_t page_idx, const uint8_t extruder, const uint16_t num_steps) {
  2750. if (!last_page_step_rate) {
  2751. kill(GET_TEXT_F(MSG_BAD_PAGE_SPEED));
  2752. return;
  2753. }
  2754. uint8_t next_buffer_head;
  2755. block_t * const block = get_next_free_block(next_buffer_head);
  2756. block->flag.reset(BLOCK_BIT_PAGE);
  2757. #if HAS_FAN
  2758. FANS_LOOP(i) block->fan_speed[i] = thermalManager.fan_speed[i];
  2759. #endif
  2760. E_TERN_(block->extruder = extruder);
  2761. block->page_idx = page_idx;
  2762. block->step_event_count = num_steps;
  2763. block->initial_rate = block->final_rate = block->nominal_rate = last_page_step_rate; // steps/s
  2764. block->accelerate_until = 0;
  2765. block->decelerate_after = block->step_event_count;
  2766. // Will be set to last direction later if directional format.
  2767. block->direction_bits = 0;
  2768. #define PAGE_UPDATE_DIR(AXIS) \
  2769. if (!last_page_dir[_AXIS(AXIS)]) SBI(block->direction_bits, _AXIS(AXIS));
  2770. if (!DirectStepping::Config::DIRECTIONAL) {
  2771. PAGE_UPDATE_DIR(X);
  2772. PAGE_UPDATE_DIR(Y);
  2773. PAGE_UPDATE_DIR(Z);
  2774. PAGE_UPDATE_DIR(E);
  2775. }
  2776. // If this is the first added movement, reload the delay, otherwise, cancel it.
  2777. if (block_buffer_head == block_buffer_tail) {
  2778. // If it was the first queued block, restart the 1st block delivery delay, to
  2779. // give the planner an opportunity to queue more movements and plan them
  2780. // As there are no queued movements, the Stepper ISR will not touch this
  2781. // variable, so there is no risk setting this here (but it MUST be done
  2782. // before the following line!!)
  2783. delay_before_delivering = BLOCK_DELAY_FOR_1ST_MOVE;
  2784. }
  2785. // Move buffer head
  2786. block_buffer_head = next_buffer_head;
  2787. stepper.enable_all_steppers();
  2788. stepper.wake_up();
  2789. }
  2790. #endif // DIRECT_STEPPING
  2791. /**
  2792. * Directly set the planner ABCE position (and stepper positions)
  2793. * converting mm (or angles for SCARA) into steps.
  2794. *
  2795. * The provided ABCE position is in machine units.
  2796. */
  2797. void Planner::set_machine_position_mm(const abce_pos_t &abce) {
  2798. TERN_(DISTINCT_E_FACTORS, last_extruder = active_extruder);
  2799. TERN_(HAS_POSITION_FLOAT, position_float = abce);
  2800. position.set(
  2801. LOGICAL_AXIS_LIST(
  2802. LROUND(abce.e * settings.axis_steps_per_mm[E_AXIS_N(active_extruder)]),
  2803. LROUND(abce.a * settings.axis_steps_per_mm[A_AXIS]),
  2804. LROUND(abce.b * settings.axis_steps_per_mm[B_AXIS]),
  2805. LROUND(abce.c * settings.axis_steps_per_mm[C_AXIS]),
  2806. LROUND(abce.i * settings.axis_steps_per_mm[I_AXIS]),
  2807. LROUND(abce.j * settings.axis_steps_per_mm[J_AXIS]),
  2808. LROUND(abce.k * settings.axis_steps_per_mm[K_AXIS]),
  2809. LROUND(abce.u * settings.axis_steps_per_mm[U_AXIS]),
  2810. LROUND(abce.v * settings.axis_steps_per_mm[V_AXIS]),
  2811. LROUND(abce.w * settings.axis_steps_per_mm[W_AXIS])
  2812. )
  2813. );
  2814. if (has_blocks_queued()) {
  2815. //previous_nominal_speed_sqr = 0.0; // Reset planner junction speeds. Assume start from rest.
  2816. //previous_speed.reset();
  2817. buffer_sync_block(BLOCK_BIT_SYNC_POSITION);
  2818. }
  2819. else {
  2820. #if ENABLED(BACKLASH_COMPENSATION)
  2821. abce_long_t stepper_pos = position;
  2822. LOOP_NUM_AXES(axis) stepper_pos[axis] += backlash.get_applied_steps((AxisEnum)axis);
  2823. stepper.set_position(stepper_pos);
  2824. #else
  2825. stepper.set_position(position);
  2826. #endif
  2827. }
  2828. }
  2829. void Planner::set_position_mm(const xyze_pos_t &xyze) {
  2830. xyze_pos_t machine = xyze;
  2831. TERN_(HAS_POSITION_MODIFIERS, apply_modifiers(machine, true));
  2832. #if IS_KINEMATIC
  2833. position_cart = xyze;
  2834. inverse_kinematics(machine);
  2835. TERN_(HAS_EXTRUDERS, delta.e = machine.e);
  2836. set_machine_position_mm(delta);
  2837. #else
  2838. set_machine_position_mm(machine);
  2839. #endif
  2840. }
  2841. #if HAS_EXTRUDERS
  2842. /**
  2843. * Setters for planner position (also setting stepper position).
  2844. */
  2845. void Planner::set_e_position_mm(const_float_t e) {
  2846. const uint8_t axis_index = E_AXIS_N(active_extruder);
  2847. TERN_(DISTINCT_E_FACTORS, last_extruder = active_extruder);
  2848. const float e_new = DIFF_TERN(FWRETRACT, e, fwretract.current_retract[active_extruder]);
  2849. position.e = LROUND(settings.axis_steps_per_mm[axis_index] * e_new);
  2850. TERN_(HAS_POSITION_FLOAT, position_float.e = e_new);
  2851. TERN_(IS_KINEMATIC, TERN_(HAS_EXTRUDERS, position_cart.e = e));
  2852. if (has_blocks_queued())
  2853. buffer_sync_block(BLOCK_BIT_SYNC_POSITION);
  2854. else
  2855. stepper.set_axis_position(E_AXIS, position.e);
  2856. }
  2857. #endif
  2858. // Recalculate the steps/s^2 acceleration rates, based on the mm/s^2
  2859. void Planner::refresh_acceleration_rates() {
  2860. uint32_t highest_rate = 1;
  2861. LOOP_DISTINCT_AXES(i) {
  2862. max_acceleration_steps_per_s2[i] = settings.max_acceleration_mm_per_s2[i] * settings.axis_steps_per_mm[i];
  2863. if (TERN1(DISTINCT_E_FACTORS, i < E_AXIS || i == E_AXIS_N(active_extruder)))
  2864. NOLESS(highest_rate, max_acceleration_steps_per_s2[i]);
  2865. }
  2866. acceleration_long_cutoff = 4294967295UL / highest_rate; // 0xFFFFFFFFUL
  2867. TERN_(HAS_LINEAR_E_JERK, recalculate_max_e_jerk());
  2868. }
  2869. /**
  2870. * Recalculate 'position' and 'mm_per_step'.
  2871. * Must be called whenever settings.axis_steps_per_mm changes!
  2872. */
  2873. void Planner::refresh_positioning() {
  2874. LOOP_DISTINCT_AXES(i) mm_per_step[i] = 1.0f / settings.axis_steps_per_mm[i];
  2875. set_position_mm(current_position);
  2876. refresh_acceleration_rates();
  2877. }
  2878. // Apply limits to a variable and give a warning if the value was out of range
  2879. inline void limit_and_warn(float &val, const AxisEnum axis, PGM_P const setting_name, const xyze_float_t &max_limit) {
  2880. const uint8_t lim_axis = TERN_(HAS_EXTRUDERS, axis > E_AXIS ? E_AXIS :) axis;
  2881. const float before = val;
  2882. LIMIT(val, 0.1, max_limit[lim_axis]);
  2883. if (before != val) {
  2884. SERIAL_CHAR(AXIS_CHAR(lim_axis));
  2885. SERIAL_ECHOPGM(" Max ");
  2886. SERIAL_ECHOPGM_P(setting_name);
  2887. SERIAL_ECHOLNPGM(" limited to ", val);
  2888. }
  2889. }
  2890. /**
  2891. * For the specified 'axis' set the Maximum Acceleration to the given value (mm/s^2)
  2892. * The value may be limited with warning feedback, if configured.
  2893. * Calls refresh_acceleration_rates to precalculate planner terms in steps.
  2894. *
  2895. * This hard limit is applied as a block is being added to the planner queue.
  2896. */
  2897. void Planner::set_max_acceleration(const AxisEnum axis, float inMaxAccelMMS2) {
  2898. #if ENABLED(LIMITED_MAX_ACCEL_EDITING)
  2899. #ifdef MAX_ACCEL_EDIT_VALUES
  2900. constexpr xyze_float_t max_accel_edit = MAX_ACCEL_EDIT_VALUES;
  2901. const xyze_float_t &max_acc_edit_scaled = max_accel_edit;
  2902. #else
  2903. constexpr xyze_float_t max_accel_edit = DEFAULT_MAX_ACCELERATION;
  2904. const xyze_float_t max_acc_edit_scaled = max_accel_edit * 2;
  2905. #endif
  2906. limit_and_warn(inMaxAccelMMS2, axis, PSTR("Acceleration"), max_acc_edit_scaled);
  2907. #endif
  2908. settings.max_acceleration_mm_per_s2[axis] = inMaxAccelMMS2;
  2909. // Update steps per s2 to agree with the units per s2 (since they are used in the planner)
  2910. refresh_acceleration_rates();
  2911. }
  2912. /**
  2913. * For the specified 'axis' set the Maximum Feedrate to the given value (mm/s)
  2914. * The value may be limited with warning feedback, if configured.
  2915. *
  2916. * This hard limit is applied as a block is being added to the planner queue.
  2917. */
  2918. void Planner::set_max_feedrate(const AxisEnum axis, float inMaxFeedrateMMS) {
  2919. #if ENABLED(LIMITED_MAX_FR_EDITING)
  2920. #ifdef MAX_FEEDRATE_EDIT_VALUES
  2921. constexpr xyze_float_t max_fr_edit = MAX_FEEDRATE_EDIT_VALUES;
  2922. const xyze_float_t &max_fr_edit_scaled = max_fr_edit;
  2923. #else
  2924. constexpr xyze_float_t max_fr_edit = DEFAULT_MAX_FEEDRATE;
  2925. const xyze_float_t max_fr_edit_scaled = max_fr_edit * 2;
  2926. #endif
  2927. limit_and_warn(inMaxFeedrateMMS, axis, PSTR("Feedrate"), max_fr_edit_scaled);
  2928. #endif
  2929. settings.max_feedrate_mm_s[axis] = inMaxFeedrateMMS;
  2930. }
  2931. #if HAS_CLASSIC_JERK
  2932. /**
  2933. * For the specified 'axis' set the Maximum Jerk (instant change) to the given value (mm/s)
  2934. * The value may be limited with warning feedback, if configured.
  2935. *
  2936. * This hard limit is applied (to the block start speed) as the block is being added to the planner queue.
  2937. */
  2938. void Planner::set_max_jerk(const AxisEnum axis, float inMaxJerkMMS) {
  2939. #if ENABLED(LIMITED_JERK_EDITING)
  2940. constexpr xyze_float_t max_jerk_edit =
  2941. #ifdef MAX_JERK_EDIT_VALUES
  2942. MAX_JERK_EDIT_VALUES
  2943. #else
  2944. { (DEFAULT_XJERK) * 2, (DEFAULT_YJERK) * 2,
  2945. (DEFAULT_ZJERK) * 2, (DEFAULT_EJERK) * 2 }
  2946. #endif
  2947. ;
  2948. limit_and_warn(inMaxJerkMMS, axis, PSTR("Jerk"), max_jerk_edit);
  2949. #endif
  2950. max_jerk[axis] = inMaxJerkMMS;
  2951. }
  2952. #endif
  2953. #if HAS_WIRED_LCD
  2954. uint16_t Planner::block_buffer_runtime() {
  2955. #ifdef __AVR__
  2956. // Protect the access to the variable. Only required for AVR, as
  2957. // any 32bit CPU offers atomic access to 32bit variables
  2958. const bool was_enabled = stepper.suspend();
  2959. #endif
  2960. uint32_t bbru = block_buffer_runtime_us;
  2961. #ifdef __AVR__
  2962. // Reenable Stepper ISR
  2963. if (was_enabled) stepper.wake_up();
  2964. #endif
  2965. // To translate µs to ms a division by 1000 would be required.
  2966. // We introduce 2.4% error here by dividing by 1024.
  2967. // Doesn't matter because block_buffer_runtime_us is already too small an estimation.
  2968. bbru >>= 10;
  2969. // limit to about a minute.
  2970. NOMORE(bbru, 0x0000FFFFUL);
  2971. return bbru;
  2972. }
  2973. void Planner::clear_block_buffer_runtime() {
  2974. #ifdef __AVR__
  2975. // Protect the access to the variable. Only required for AVR, as
  2976. // any 32bit CPU offers atomic access to 32bit variables
  2977. const bool was_enabled = stepper.suspend();
  2978. #endif
  2979. block_buffer_runtime_us = 0;
  2980. #ifdef __AVR__
  2981. // Reenable Stepper ISR
  2982. if (was_enabled) stepper.wake_up();
  2983. #endif
  2984. }
  2985. #endif