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

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