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

planner.cpp 111KB

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