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

planner.cpp 111KB

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