My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

planner.cpp 132KB

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