planner.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  1. /*
  2. planner.c - buffers movement commands and manages the acceleration profile plan
  3. Part of Grbl
  4. Copyright (c) 2009-2011 Simen Svale Skogsrud
  5. Grbl is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 3 of the License, or
  8. (at your option) any later version.
  9. Grbl is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with Grbl. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. /* The ring buffer implementation gleaned from the wiring_serial library by David A. Mellis. */
  17. /*
  18. Reasoning behind the mathematics in this module (in the key of 'Mathematica'):
  19. s == speed, a == acceleration, t == time, d == distance
  20. Basic definitions:
  21. Speed[s_, a_, t_] := s + (a*t)
  22. Travel[s_, a_, t_] := Integrate[Speed[s, a, t], t]
  23. Distance to reach a specific speed with a constant acceleration:
  24. Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, d, t]
  25. d -> (m^2 - s^2)/(2 a) --> estimate_acceleration_distance()
  26. Speed after a given distance of travel with constant acceleration:
  27. Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, m, t]
  28. m -> Sqrt[2 a d + s^2]
  29. DestinationSpeed[s_, a_, d_] := Sqrt[2 a d + s^2]
  30. When to start braking (di) to reach a specified destionation speed (s2) after accelerating
  31. from initial speed s1 without ever stopping at a plateau:
  32. Solve[{DestinationSpeed[s1, a, di] == DestinationSpeed[s2, a, d - di]}, di]
  33. di -> (2 a d - s1^2 + s2^2)/(4 a) --> intersection_distance()
  34. IntersectionDistance[s1_, s2_, a_, d_] := (2 a d - s1^2 + s2^2)/(4 a)
  35. */
  36. #include "Marlin.h"
  37. #include "planner.h"
  38. #include "stepper.h"
  39. #include "temperature.h"
  40. #include "ultralcd.h"
  41. #include "language.h"
  42. #ifdef MESH_BED_LEVELING
  43. #include "mesh_bed_leveling.h"
  44. #include "mesh_bed_calibration.h"
  45. #endif
  46. //===========================================================================
  47. //=============================public variables ============================
  48. //===========================================================================
  49. unsigned long minsegmenttime;
  50. float max_feedrate[NUM_AXIS]; // set the max speeds
  51. float axis_steps_per_unit[NUM_AXIS];
  52. unsigned long max_acceleration_units_per_sq_second[NUM_AXIS]; // Use M201 to override by software
  53. float minimumfeedrate;
  54. float acceleration; // Normal acceleration mm/s^2 THIS IS THE DEFAULT ACCELERATION for all moves. M204 SXXXX
  55. float retract_acceleration; // mm/s^2 filament pull-pack and push-forward while standing still in the other axis M204 TXXXX
  56. // Jerk is a maximum immediate velocity change.
  57. float max_jerk[NUM_AXIS];
  58. float mintravelfeedrate;
  59. unsigned long axis_steps_per_sqr_second[NUM_AXIS];
  60. #ifdef ENABLE_AUTO_BED_LEVELING
  61. // this holds the required transform to compensate for bed level
  62. matrix_3x3 plan_bed_level_matrix = {
  63. 1.0, 0.0, 0.0,
  64. 0.0, 1.0, 0.0,
  65. 0.0, 0.0, 1.0,
  66. };
  67. #endif // #ifdef ENABLE_AUTO_BED_LEVELING
  68. // The current position of the tool in absolute steps
  69. long position[NUM_AXIS]; //rescaled from extern when axis_steps_per_unit are changed by gcode
  70. static float previous_speed[NUM_AXIS]; // Speed of previous path line segment
  71. static float previous_nominal_speed; // Nominal speed of previous path line segment
  72. static float previous_safe_speed; // Exit speed limited by a jerk to full halt of a previous last segment.
  73. #ifdef AUTOTEMP
  74. float autotemp_max=250;
  75. float autotemp_min=210;
  76. float autotemp_factor=0.1;
  77. bool autotemp_enabled=false;
  78. #endif
  79. unsigned char g_uc_extruder_last_move[3] = {0,0,0};
  80. //===========================================================================
  81. //=================semi-private variables, used in inline functions =====
  82. //===========================================================================
  83. block_t block_buffer[BLOCK_BUFFER_SIZE]; // A ring buffer for motion instfructions
  84. volatile unsigned char block_buffer_head; // Index of the next block to be pushed
  85. volatile unsigned char block_buffer_tail; // Index of the block to process now
  86. //===========================================================================
  87. //=============================private variables ============================
  88. //===========================================================================
  89. #ifdef PREVENT_DANGEROUS_EXTRUDE
  90. float extrude_min_temp=EXTRUDE_MINTEMP;
  91. #endif
  92. #ifdef FILAMENT_SENSOR
  93. static char meas_sample; //temporary variable to hold filament measurement sample
  94. #endif
  95. // Returns the index of the next block in the ring buffer
  96. // NOTE: Removed modulo (%) operator, which uses an expensive divide and multiplication.
  97. static inline int8_t next_block_index(int8_t block_index) {
  98. if (++ block_index == BLOCK_BUFFER_SIZE)
  99. block_index = 0;
  100. return block_index;
  101. }
  102. // Returns the index of the previous block in the ring buffer
  103. static inline int8_t prev_block_index(int8_t block_index) {
  104. if (block_index == 0)
  105. block_index = BLOCK_BUFFER_SIZE;
  106. -- block_index;
  107. return block_index;
  108. }
  109. //===========================================================================
  110. //=============================functions ============================
  111. //===========================================================================
  112. // Calculates the distance (not time) it takes to accelerate from initial_rate to target_rate using the
  113. // given acceleration:
  114. FORCE_INLINE float estimate_acceleration_distance(float initial_rate, float target_rate, float acceleration)
  115. {
  116. if (acceleration!=0) {
  117. return((target_rate*target_rate-initial_rate*initial_rate)/
  118. (2.0*acceleration));
  119. }
  120. else {
  121. return 0.0; // acceleration was 0, set acceleration distance to 0
  122. }
  123. }
  124. // This function gives you the point at which you must start braking (at the rate of -acceleration) if
  125. // you started at speed initial_rate and accelerated until this point and want to end at the final_rate after
  126. // a total travel of distance. This can be used to compute the intersection point between acceleration and
  127. // deceleration in the cases where the trapezoid has no plateau (i.e. never reaches maximum speed)
  128. FORCE_INLINE float intersection_distance(float initial_rate, float final_rate, float acceleration, float distance)
  129. {
  130. if (acceleration!=0) {
  131. return((2.0*acceleration*distance-initial_rate*initial_rate+final_rate*final_rate)/
  132. (4.0*acceleration) );
  133. }
  134. else {
  135. return 0.0; // acceleration was 0, set intersection distance to 0
  136. }
  137. }
  138. // Calculates trapezoid parameters so that the entry- and exit-speed is compensated by the provided factors.
  139. void calculate_trapezoid_for_block(block_t *block, float entry_factor, float exit_factor) {
  140. unsigned long initial_rate = ceil(block->nominal_rate*entry_factor); // (step/min)
  141. unsigned long final_rate = ceil(block->nominal_rate*exit_factor); // (step/min)
  142. // Limit minimal step rate (Otherwise the timer will overflow.)
  143. if(initial_rate <120) {
  144. initial_rate=120;
  145. }
  146. if(final_rate < 120) {
  147. final_rate=120;
  148. }
  149. long acceleration = block->acceleration_st;
  150. int32_t accelerate_steps =
  151. ceil(estimate_acceleration_distance(initial_rate, block->nominal_rate, acceleration));
  152. int32_t decelerate_steps =
  153. floor(estimate_acceleration_distance(block->nominal_rate, final_rate, -acceleration));
  154. // Calculate the size of Plateau of Nominal Rate.
  155. int32_t plateau_steps = block->step_event_count-accelerate_steps-decelerate_steps;
  156. // Is the Plateau of Nominal Rate smaller than nothing? That means no cruising, and we will
  157. // have to use intersection_distance() to calculate when to abort acceleration and start braking
  158. // in order to reach the final_rate exactly at the end of this block.
  159. if (plateau_steps < 0) {
  160. accelerate_steps = ceil(intersection_distance(initial_rate, final_rate, acceleration, block->step_event_count));
  161. accelerate_steps = max(accelerate_steps,0); // Check limits due to numerical round-off
  162. accelerate_steps = min((uint32_t)accelerate_steps,block->step_event_count);//(We can cast here to unsigned, because the above line ensures that we are above zero)
  163. plateau_steps = 0;
  164. }
  165. #ifdef ADVANCE
  166. volatile long initial_advance = block->advance*entry_factor*entry_factor;
  167. volatile long final_advance = block->advance*exit_factor*exit_factor;
  168. #endif // ADVANCE
  169. // block->accelerate_until = accelerate_steps;
  170. // block->decelerate_after = accelerate_steps+plateau_steps;
  171. CRITICAL_SECTION_START; // Fill variables used by the stepper in a critical section
  172. if (! block->busy) { // Don't update variables if block is busy.
  173. block->accelerate_until = accelerate_steps;
  174. block->decelerate_after = accelerate_steps+plateau_steps;
  175. block->initial_rate = initial_rate;
  176. block->final_rate = final_rate;
  177. #ifdef ADVANCE
  178. block->initial_advance = initial_advance;
  179. block->final_advance = final_advance;
  180. #endif //ADVANCE
  181. }
  182. CRITICAL_SECTION_END;
  183. }
  184. // Calculates the maximum allowable entry speed, when you must be able to reach target_velocity using the
  185. // decceleration within the allotted distance.
  186. FORCE_INLINE float max_allowable_entry_speed(float decceleration, float target_velocity, float distance)
  187. {
  188. // assert(decceleration < 0);
  189. return sqrt(target_velocity*target_velocity-2*decceleration*distance);
  190. }
  191. // Recalculates the motion plan according to the following algorithm:
  192. //
  193. // 1. Go over every block in reverse order and calculate a junction speed reduction (i.e. block_t.entry_factor)
  194. // so that:
  195. // a. The junction jerk is within the set limit
  196. // b. No speed reduction within one block requires faster deceleration than the one, true constant
  197. // acceleration.
  198. // 2. Go over every block in chronological order and dial down junction speed reduction values if
  199. // a. The speed increase within one block would require faster accelleration than the one, true
  200. // constant acceleration.
  201. //
  202. // When these stages are complete all blocks have an entry_factor that will allow all speed changes to
  203. // be performed using only the one, true constant acceleration, and where no junction jerk is jerkier than
  204. // the set limit. Finally it will:
  205. //
  206. // 3. Recalculate trapezoids for all blocks.
  207. void planner_recalculate(const float &safe_final_speed)
  208. {
  209. // Reverse pass
  210. // Make a local copy of block_buffer_tail, because the interrupt can alter it
  211. // by consuming the blocks, therefore shortening the queue.
  212. unsigned char tail = block_buffer_tail;
  213. uint8_t block_index;
  214. block_t *prev, *current, *next;
  215. // SERIAL_ECHOLNPGM("planner_recalculate - 1");
  216. // At least three blocks are in the queue?
  217. unsigned char n_blocks = (block_buffer_head + BLOCK_BUFFER_SIZE - tail) & (BLOCK_BUFFER_SIZE - 1);
  218. if (n_blocks >= 3) {
  219. // Initialize the last tripple of blocks.
  220. block_index = prev_block_index(block_buffer_head);
  221. next = block_buffer + block_index;
  222. current = block_buffer + (block_index = prev_block_index(block_index));
  223. // No need to recalculate the last block, it has already been set by the plan_buffer_line() function.
  224. // Vojtech thinks, that one shall not touch the entry speed of the very first block as well, because
  225. // 1) it may already be running at the stepper interrupt,
  226. // 2) there is no way to limit it when going in the forward direction.
  227. while (block_index != tail) {
  228. if (current->flag & BLOCK_FLAG_START_FROM_FULL_HALT) {
  229. // Don't modify the entry velocity of the starting block.
  230. // Also don't modify the trapezoids before this block, they are finalized already, prepared
  231. // for the stepper interrupt routine to use them.
  232. tail = block_index;
  233. // Update the number of blocks to process.
  234. n_blocks = (block_buffer_head + BLOCK_BUFFER_SIZE - tail) & (BLOCK_BUFFER_SIZE - 1);
  235. // SERIAL_ECHOLNPGM("START");
  236. break;
  237. }
  238. // If entry speed is already at the maximum entry speed, no need to recheck. Block is cruising.
  239. // If not, block in state of acceleration or deceleration. Reset entry speed to maximum and
  240. // check for maximum allowable speed reductions to ensure maximum possible planned speed.
  241. if (current->entry_speed != current->max_entry_speed) {
  242. // assert(current->entry_speed < current->max_entry_speed);
  243. // Entry speed could be increased up to the max_entry_speed, limited by the length of the current
  244. // segment and the maximum acceleration allowed for this segment.
  245. // If nominal length true, max junction speed is guaranteed to be reached even if decelerating to a jerk-from-zero velocity.
  246. // Only compute for max allowable speed if block is decelerating and nominal length is false.
  247. current->entry_speed = ((current->flag & BLOCK_FLAG_NOMINAL_LENGTH) || current->max_entry_speed <= next->entry_speed) ?
  248. current->max_entry_speed :
  249. min(current->max_entry_speed, max_allowable_entry_speed(-current->acceleration,next->entry_speed,current->millimeters));
  250. current->flag |= BLOCK_FLAG_RECALCULATE;
  251. }
  252. next = current;
  253. current = block_buffer + (block_index = prev_block_index(block_index));
  254. }
  255. }
  256. // SERIAL_ECHOLNPGM("planner_recalculate - 2");
  257. // Forward pass and recalculate the trapezoids.
  258. if (n_blocks >= 2) {
  259. // Better to limit the velocities using the already processed block, if it is available, so rather use the saved tail.
  260. block_index = tail;
  261. prev = block_buffer + block_index;
  262. current = block_buffer + (block_index = next_block_index(block_index));
  263. do {
  264. // If the previous block is an acceleration block, but it is not long enough to complete the
  265. // full speed change within the block, we need to adjust the entry speed accordingly. Entry
  266. // speeds have already been reset, maximized, and reverse planned by reverse planner.
  267. // If nominal length is true, max junction speed is guaranteed to be reached. No need to recheck.
  268. if (! (prev->flag & BLOCK_FLAG_NOMINAL_LENGTH) && prev->entry_speed < current->entry_speed) {
  269. float entry_speed = min(current->entry_speed, max_allowable_entry_speed(-prev->acceleration,prev->entry_speed,prev->millimeters));
  270. // Check for junction speed change
  271. if (current->entry_speed != entry_speed) {
  272. current->entry_speed = entry_speed;
  273. current->flag |= BLOCK_FLAG_RECALCULATE;
  274. }
  275. }
  276. // Recalculate if current block entry or exit junction speed has changed.
  277. if ((prev->flag | current->flag) & BLOCK_FLAG_RECALCULATE) {
  278. // NOTE: Entry and exit factors always > 0 by all previous logic operations.
  279. calculate_trapezoid_for_block(prev, prev->entry_speed/prev->nominal_speed, current->entry_speed/prev->nominal_speed);
  280. // Reset current only to ensure next trapezoid is computed.
  281. prev->flag &= ~BLOCK_FLAG_RECALCULATE;
  282. }
  283. prev = current;
  284. current = block_buffer + (block_index = next_block_index(block_index));
  285. } while (block_index != block_buffer_head);
  286. }
  287. // SERIAL_ECHOLNPGM("planner_recalculate - 3");
  288. // Last/newest block in buffer. Exit speed is set with safe_final_speed. Always recalculated.
  289. current = block_buffer + prev_block_index(block_buffer_head);
  290. calculate_trapezoid_for_block(current, current->entry_speed/current->nominal_speed, safe_final_speed/current->nominal_speed);
  291. current->flag &= ~BLOCK_FLAG_RECALCULATE;
  292. // SERIAL_ECHOLNPGM("planner_recalculate - 4");
  293. }
  294. void plan_init() {
  295. block_buffer_head = 0;
  296. block_buffer_tail = 0;
  297. memset(position, 0, sizeof(position)); // clear position
  298. previous_speed[0] = 0.0;
  299. previous_speed[1] = 0.0;
  300. previous_speed[2] = 0.0;
  301. previous_speed[3] = 0.0;
  302. previous_nominal_speed = 0.0;
  303. }
  304. #ifdef AUTOTEMP
  305. void getHighESpeed()
  306. {
  307. static float oldt=0;
  308. if(!autotemp_enabled){
  309. return;
  310. }
  311. if(degTargetHotend0()+2<autotemp_min) { //probably temperature set to zero.
  312. return; //do nothing
  313. }
  314. float high=0.0;
  315. uint8_t block_index = block_buffer_tail;
  316. while(block_index != block_buffer_head) {
  317. if((block_buffer[block_index].steps_x != 0) ||
  318. (block_buffer[block_index].steps_y != 0) ||
  319. (block_buffer[block_index].steps_z != 0)) {
  320. float se=(float(block_buffer[block_index].steps_e)/float(block_buffer[block_index].step_event_count))*block_buffer[block_index].nominal_speed;
  321. //se; mm/sec;
  322. if(se>high)
  323. {
  324. high=se;
  325. }
  326. }
  327. block_index = (block_index+1) & (BLOCK_BUFFER_SIZE - 1);
  328. }
  329. float g=autotemp_min+high*autotemp_factor;
  330. float t=g;
  331. if(t<autotemp_min)
  332. t=autotemp_min;
  333. if(t>autotemp_max)
  334. t=autotemp_max;
  335. if(oldt>t)
  336. {
  337. t=AUTOTEMP_OLDWEIGHT*oldt+(1-AUTOTEMP_OLDWEIGHT)*t;
  338. }
  339. oldt=t;
  340. setTargetHotend0(t);
  341. }
  342. #endif
  343. void check_axes_activity()
  344. {
  345. unsigned char x_active = 0;
  346. unsigned char y_active = 0;
  347. unsigned char z_active = 0;
  348. unsigned char e_active = 0;
  349. unsigned char tail_fan_speed = fanSpeed;
  350. block_t *block;
  351. if(block_buffer_tail != block_buffer_head)
  352. {
  353. uint8_t block_index = block_buffer_tail;
  354. tail_fan_speed = block_buffer[block_index].fan_speed;
  355. while(block_index != block_buffer_head)
  356. {
  357. block = &block_buffer[block_index];
  358. if(block->steps_x != 0) x_active++;
  359. if(block->steps_y != 0) y_active++;
  360. if(block->steps_z != 0) z_active++;
  361. if(block->steps_e != 0) e_active++;
  362. block_index = (block_index+1) & (BLOCK_BUFFER_SIZE - 1);
  363. }
  364. }
  365. if((DISABLE_X) && (x_active == 0)) disable_x();
  366. if((DISABLE_Y) && (y_active == 0)) disable_y();
  367. if((DISABLE_Z) && (z_active == 0)) disable_z();
  368. if((DISABLE_E) && (e_active == 0))
  369. {
  370. disable_e0();
  371. disable_e1();
  372. disable_e2();
  373. }
  374. #if defined(FAN_PIN) && FAN_PIN > -1
  375. #ifdef FAN_KICKSTART_TIME
  376. static unsigned long fan_kick_end;
  377. if (tail_fan_speed) {
  378. if (fan_kick_end == 0) {
  379. // Just starting up fan - run at full power.
  380. fan_kick_end = millis() + FAN_KICKSTART_TIME;
  381. tail_fan_speed = 255;
  382. } else if (fan_kick_end > millis())
  383. // Fan still spinning up.
  384. tail_fan_speed = 255;
  385. } else {
  386. fan_kick_end = 0;
  387. }
  388. #endif//FAN_KICKSTART_TIME
  389. #ifdef FAN_SOFT_PWM
  390. fanSpeedSoftPwm = tail_fan_speed;
  391. #else
  392. analogWrite(FAN_PIN,tail_fan_speed);
  393. #endif//!FAN_SOFT_PWM
  394. #endif//FAN_PIN > -1
  395. #ifdef AUTOTEMP
  396. getHighESpeed();
  397. #endif
  398. }
  399. bool waiting_inside_plan_buffer_line_print_aborted = false;
  400. /*
  401. void planner_abort_soft()
  402. {
  403. // Empty the queue.
  404. while (blocks_queued()) plan_discard_current_block();
  405. // Relay to planner wait routine, that the current line shall be canceled.
  406. waiting_inside_plan_buffer_line_print_aborted = true;
  407. //current_position[i]
  408. }
  409. */
  410. void planner_abort_hard()
  411. {
  412. // Abort the stepper routine and flush the planner queue.
  413. quickStop();
  414. // Now the front-end (the Marlin_main.cpp with its current_position) is out of sync.
  415. // First update the planner's current position in the physical motor steps.
  416. position[X_AXIS] = st_get_position(X_AXIS);
  417. position[Y_AXIS] = st_get_position(Y_AXIS);
  418. position[Z_AXIS] = st_get_position(Z_AXIS);
  419. position[E_AXIS] = st_get_position(E_AXIS);
  420. // Second update the current position of the front end.
  421. current_position[X_AXIS] = st_get_position_mm(X_AXIS);
  422. current_position[Y_AXIS] = st_get_position_mm(Y_AXIS);
  423. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  424. current_position[E_AXIS] = st_get_position_mm(E_AXIS);
  425. // Apply the mesh bed leveling correction to the Z axis.
  426. #ifdef MESH_BED_LEVELING
  427. if (mbl.active)
  428. current_position[Z_AXIS] -= mbl.get_z(current_position[X_AXIS], current_position[Y_AXIS]);
  429. #endif
  430. // Apply inverse world correction matrix.
  431. machine2world(current_position[X_AXIS], current_position[Y_AXIS]);
  432. memcpy(destination, current_position, sizeof(destination));
  433. // Resets planner junction speeds. Assumes start from rest.
  434. previous_nominal_speed = 0.0;
  435. previous_speed[0] = 0.0;
  436. previous_speed[1] = 0.0;
  437. previous_speed[2] = 0.0;
  438. previous_speed[3] = 0.0;
  439. // Relay to planner wait routine, that the current line shall be canceled.
  440. waiting_inside_plan_buffer_line_print_aborted = true;
  441. }
  442. float junction_deviation = 0.1;
  443. // Add a new linear movement to the buffer. steps_x, _y and _z is the absolute position in
  444. // mm. Microseconds specify how many microseconds the move should take to perform. To aid acceleration
  445. // calculation the caller must also provide the physical length of the line in millimeters.
  446. void plan_buffer_line(float x, float y, float z, const float &e, float feed_rate, const uint8_t &extruder)
  447. {
  448. // Calculate the buffer head after we push this byte
  449. int next_buffer_head = next_block_index(block_buffer_head);
  450. // If the buffer is full: good! That means we are well ahead of the robot.
  451. // Rest here until there is room in the buffer.
  452. if (block_buffer_tail == next_buffer_head) {
  453. waiting_inside_plan_buffer_line_print_aborted = false;
  454. do {
  455. manage_heater();
  456. // Vojtech: Don't disable motors inside the planner!
  457. manage_inactivity(false);
  458. lcd_update();
  459. } while (block_buffer_tail == next_buffer_head);
  460. if (waiting_inside_plan_buffer_line_print_aborted)
  461. // Inside the lcd_update() routine the print has been aborted.
  462. // Cancel the print, do not plan the current line this routine is waiting on.
  463. return;
  464. }
  465. #ifdef ENABLE_AUTO_BED_LEVELING
  466. apply_rotation_xyz(plan_bed_level_matrix, x, y, z);
  467. #endif // ENABLE_AUTO_BED_LEVELING
  468. // Apply the machine correction matrix.
  469. {
  470. #if 0
  471. SERIAL_ECHOPGM("Planner, current position - servos: ");
  472. MYSERIAL.print(st_get_position_mm(X_AXIS), 5);
  473. SERIAL_ECHOPGM(", ");
  474. MYSERIAL.print(st_get_position_mm(Y_AXIS), 5);
  475. SERIAL_ECHOPGM(", ");
  476. MYSERIAL.print(st_get_position_mm(Z_AXIS), 5);
  477. SERIAL_ECHOLNPGM("");
  478. SERIAL_ECHOPGM("Planner, target position, initial: ");
  479. MYSERIAL.print(x, 5);
  480. SERIAL_ECHOPGM(", ");
  481. MYSERIAL.print(y, 5);
  482. SERIAL_ECHOLNPGM("");
  483. SERIAL_ECHOPGM("Planner, world2machine: ");
  484. MYSERIAL.print(world2machine_rotation_and_skew[0][0], 5);
  485. SERIAL_ECHOPGM(", ");
  486. MYSERIAL.print(world2machine_rotation_and_skew[0][1], 5);
  487. SERIAL_ECHOPGM(", ");
  488. MYSERIAL.print(world2machine_rotation_and_skew[1][0], 5);
  489. SERIAL_ECHOPGM(", ");
  490. MYSERIAL.print(world2machine_rotation_and_skew[1][1], 5);
  491. SERIAL_ECHOLNPGM("");
  492. SERIAL_ECHOPGM("Planner, offset: ");
  493. MYSERIAL.print(world2machine_shift[0], 5);
  494. SERIAL_ECHOPGM(", ");
  495. MYSERIAL.print(world2machine_shift[1], 5);
  496. SERIAL_ECHOLNPGM("");
  497. #endif
  498. world2machine(x, y);
  499. #if 0
  500. SERIAL_ECHOPGM("Planner, target position, corrected: ");
  501. MYSERIAL.print(x, 5);
  502. SERIAL_ECHOPGM(", ");
  503. MYSERIAL.print(y, 5);
  504. SERIAL_ECHOLNPGM("");
  505. #endif
  506. }
  507. // The target position of the tool in absolute steps
  508. // Calculate target position in absolute steps
  509. //this should be done after the wait, because otherwise a M92 code within the gcode disrupts this calculation somehow
  510. long target[4];
  511. target[X_AXIS] = lround(x*axis_steps_per_unit[X_AXIS]);
  512. target[Y_AXIS] = lround(y*axis_steps_per_unit[Y_AXIS]);
  513. #ifdef MESH_BED_LEVELING
  514. if (mbl.active){
  515. target[Z_AXIS] = lround((z+mbl.get_z(x, y))*axis_steps_per_unit[Z_AXIS]);
  516. }else{
  517. target[Z_AXIS] = lround(z*axis_steps_per_unit[Z_AXIS]);
  518. }
  519. #else
  520. target[Z_AXIS] = lround(z*axis_steps_per_unit[Z_AXIS]);
  521. #endif // ENABLE_MESH_BED_LEVELING
  522. target[E_AXIS] = lround(e*axis_steps_per_unit[E_AXIS]);
  523. #ifdef PREVENT_DANGEROUS_EXTRUDE
  524. if(target[E_AXIS]!=position[E_AXIS])
  525. {
  526. if(degHotend(active_extruder)<extrude_min_temp)
  527. {
  528. position[E_AXIS]=target[E_AXIS]; //behave as if the move really took place, but ignore E part
  529. SERIAL_ECHO_START;
  530. SERIAL_ECHOLNRPGM(MSG_ERR_COLD_EXTRUDE_STOP);
  531. }
  532. #ifdef PREVENT_LENGTHY_EXTRUDE
  533. if(labs(target[E_AXIS]-position[E_AXIS])>axis_steps_per_unit[E_AXIS]*EXTRUDE_MAXLENGTH)
  534. {
  535. position[E_AXIS]=target[E_AXIS]; //behave as if the move really took place, but ignore E part
  536. SERIAL_ECHO_START;
  537. SERIAL_ECHOLNRPGM(MSG_ERR_LONG_EXTRUDE_STOP);
  538. }
  539. #endif
  540. }
  541. #endif
  542. // Prepare to set up new block
  543. block_t *block = &block_buffer[block_buffer_head];
  544. // Mark block as not busy (Not executed by the stepper interrupt, could be still tinkered with.)
  545. block->busy = false;
  546. // Number of steps for each axis
  547. #ifndef COREXY
  548. // default non-h-bot planning
  549. block->steps_x = labs(target[X_AXIS]-position[X_AXIS]);
  550. block->steps_y = labs(target[Y_AXIS]-position[Y_AXIS]);
  551. #else
  552. // corexy planning
  553. // these equations follow the form of the dA and dB equations on http://www.corexy.com/theory.html
  554. block->steps_x = labs((target[X_AXIS]-position[X_AXIS]) + (target[Y_AXIS]-position[Y_AXIS]));
  555. block->steps_y = labs((target[X_AXIS]-position[X_AXIS]) - (target[Y_AXIS]-position[Y_AXIS]));
  556. #endif
  557. block->steps_z = labs(target[Z_AXIS]-position[Z_AXIS]);
  558. block->steps_e = labs(target[E_AXIS]-position[E_AXIS]);
  559. block->steps_e *= volumetric_multiplier[active_extruder];
  560. block->steps_e *= extrudemultiply;
  561. block->steps_e /= 100;
  562. block->step_event_count = max(block->steps_x, max(block->steps_y, max(block->steps_z, block->steps_e)));
  563. // Bail if this is a zero-length block
  564. if (block->step_event_count <= dropsegments)
  565. {
  566. return;
  567. }
  568. block->fan_speed = fanSpeed;
  569. // Compute direction bits for this block
  570. block->direction_bits = 0;
  571. #ifndef COREXY
  572. if (target[X_AXIS] < position[X_AXIS])
  573. {
  574. block->direction_bits |= (1<<X_AXIS);
  575. }
  576. if (target[Y_AXIS] < position[Y_AXIS])
  577. {
  578. block->direction_bits |= (1<<Y_AXIS);
  579. }
  580. #else
  581. if ((target[X_AXIS]-position[X_AXIS]) + (target[Y_AXIS]-position[Y_AXIS]) < 0)
  582. {
  583. block->direction_bits |= (1<<X_AXIS);
  584. }
  585. if ((target[X_AXIS]-position[X_AXIS]) - (target[Y_AXIS]-position[Y_AXIS]) < 0)
  586. {
  587. block->direction_bits |= (1<<Y_AXIS);
  588. }
  589. #endif
  590. if (target[Z_AXIS] < position[Z_AXIS])
  591. {
  592. block->direction_bits |= (1<<Z_AXIS);
  593. }
  594. if (target[E_AXIS] < position[E_AXIS])
  595. {
  596. block->direction_bits |= (1<<E_AXIS);
  597. }
  598. block->active_extruder = extruder;
  599. //enable active axes
  600. #ifdef COREXY
  601. if((block->steps_x != 0) || (block->steps_y != 0))
  602. {
  603. enable_x();
  604. enable_y();
  605. }
  606. #else
  607. if(block->steps_x != 0) enable_x();
  608. if(block->steps_y != 0) enable_y();
  609. #endif
  610. #ifndef Z_LATE_ENABLE
  611. if(block->steps_z != 0) enable_z();
  612. #endif
  613. // Enable extruder(s)
  614. if(block->steps_e != 0)
  615. {
  616. if (DISABLE_INACTIVE_EXTRUDER) //enable only selected extruder
  617. {
  618. if(g_uc_extruder_last_move[0] > 0) g_uc_extruder_last_move[0]--;
  619. if(g_uc_extruder_last_move[1] > 0) g_uc_extruder_last_move[1]--;
  620. if(g_uc_extruder_last_move[2] > 0) g_uc_extruder_last_move[2]--;
  621. switch(extruder)
  622. {
  623. case 0:
  624. enable_e0();
  625. g_uc_extruder_last_move[0] = BLOCK_BUFFER_SIZE*2;
  626. if(g_uc_extruder_last_move[1] == 0) disable_e1();
  627. if(g_uc_extruder_last_move[2] == 0) disable_e2();
  628. break;
  629. case 1:
  630. enable_e1();
  631. g_uc_extruder_last_move[1] = BLOCK_BUFFER_SIZE*2;
  632. if(g_uc_extruder_last_move[0] == 0) disable_e0();
  633. if(g_uc_extruder_last_move[2] == 0) disable_e2();
  634. break;
  635. case 2:
  636. enable_e2();
  637. g_uc_extruder_last_move[2] = BLOCK_BUFFER_SIZE*2;
  638. if(g_uc_extruder_last_move[0] == 0) disable_e0();
  639. if(g_uc_extruder_last_move[1] == 0) disable_e1();
  640. break;
  641. }
  642. }
  643. else //enable all
  644. {
  645. enable_e0();
  646. enable_e1();
  647. enable_e2();
  648. }
  649. }
  650. if (block->steps_e == 0)
  651. {
  652. if(feed_rate<mintravelfeedrate) feed_rate=mintravelfeedrate;
  653. }
  654. else
  655. {
  656. if(feed_rate<minimumfeedrate) feed_rate=minimumfeedrate;
  657. }
  658. /* This part of the code calculates the total length of the movement.
  659. For cartesian bots, the X_AXIS is the real X movement and same for Y_AXIS.
  660. But for corexy bots, that is not true. The "X_AXIS" and "Y_AXIS" motors (that should be named to A_AXIS
  661. and B_AXIS) cannot be used for X and Y length, because A=X+Y and B=X-Y.
  662. So we need to create other 2 "AXIS", named X_HEAD and Y_HEAD, meaning the real displacement of the Head.
  663. Having the real displacement of the head, we can calculate the total movement length and apply the desired speed.
  664. */
  665. #ifndef COREXY
  666. float delta_mm[4];
  667. delta_mm[X_AXIS] = (target[X_AXIS]-position[X_AXIS])/axis_steps_per_unit[X_AXIS];
  668. delta_mm[Y_AXIS] = (target[Y_AXIS]-position[Y_AXIS])/axis_steps_per_unit[Y_AXIS];
  669. #else
  670. float delta_mm[6];
  671. delta_mm[X_HEAD] = (target[X_AXIS]-position[X_AXIS])/axis_steps_per_unit[X_AXIS];
  672. delta_mm[Y_HEAD] = (target[Y_AXIS]-position[Y_AXIS])/axis_steps_per_unit[Y_AXIS];
  673. delta_mm[X_AXIS] = ((target[X_AXIS]-position[X_AXIS]) + (target[Y_AXIS]-position[Y_AXIS]))/axis_steps_per_unit[X_AXIS];
  674. delta_mm[Y_AXIS] = ((target[X_AXIS]-position[X_AXIS]) - (target[Y_AXIS]-position[Y_AXIS]))/axis_steps_per_unit[Y_AXIS];
  675. #endif
  676. delta_mm[Z_AXIS] = (target[Z_AXIS]-position[Z_AXIS])/axis_steps_per_unit[Z_AXIS];
  677. delta_mm[E_AXIS] = ((target[E_AXIS]-position[E_AXIS])/axis_steps_per_unit[E_AXIS])*volumetric_multiplier[active_extruder]*extrudemultiply/100.0;
  678. if ( block->steps_x <=dropsegments && block->steps_y <=dropsegments && block->steps_z <=dropsegments )
  679. {
  680. block->millimeters = fabs(delta_mm[E_AXIS]);
  681. }
  682. else
  683. {
  684. #ifndef COREXY
  685. block->millimeters = sqrt(square(delta_mm[X_AXIS]) + square(delta_mm[Y_AXIS]) + square(delta_mm[Z_AXIS]));
  686. #else
  687. block->millimeters = sqrt(square(delta_mm[X_HEAD]) + square(delta_mm[Y_HEAD]) + square(delta_mm[Z_AXIS]));
  688. #endif
  689. }
  690. float inverse_millimeters = 1.0/block->millimeters; // Inverse millimeters to remove multiple divides
  691. // Calculate speed in mm/second for each axis. No divide by zero due to previous checks.
  692. float inverse_second = feed_rate * inverse_millimeters;
  693. int moves_queued = moves_planned();
  694. // slow down when de buffer starts to empty, rather than wait at the corner for a buffer refill
  695. #ifdef SLOWDOWN
  696. //FIXME Vojtech: Why moves_queued > 1? Why not >=1?
  697. // Can we somehow differentiate the filling of the buffer at the start of a g-code from a buffer draining situation?
  698. if (moves_queued > 1 && moves_queued < (BLOCK_BUFFER_SIZE >> 1)) {
  699. // segment time in micro seconds
  700. unsigned long segment_time = lround(1000000.0/inverse_second);
  701. if (segment_time < minsegmenttime)
  702. // buffer is draining, add extra time. The amount of time added increases if the buffer is still emptied more.
  703. inverse_second=1000000.0/(segment_time+lround(2*(minsegmenttime-segment_time)/moves_queued));
  704. }
  705. #endif // SLOWDOWN
  706. block->nominal_speed = block->millimeters * inverse_second; // (mm/sec) Always > 0
  707. block->nominal_rate = ceil(block->step_event_count * inverse_second); // (step/sec) Always > 0
  708. #ifdef FILAMENT_SENSOR
  709. //FMM update ring buffer used for delay with filament measurements
  710. if((extruder==FILAMENT_SENSOR_EXTRUDER_NUM) && (delay_index2 > -1)) //only for extruder with filament sensor and if ring buffer is initialized
  711. {
  712. delay_dist = delay_dist + delta_mm[E_AXIS]; //increment counter with next move in e axis
  713. while (delay_dist >= (10*(MAX_MEASUREMENT_DELAY+1))) //check if counter is over max buffer size in mm
  714. delay_dist = delay_dist - 10*(MAX_MEASUREMENT_DELAY+1); //loop around the buffer
  715. while (delay_dist<0)
  716. delay_dist = delay_dist + 10*(MAX_MEASUREMENT_DELAY+1); //loop around the buffer
  717. delay_index1=delay_dist/10.0; //calculate index
  718. //ensure the number is within range of the array after converting from floating point
  719. if(delay_index1<0)
  720. delay_index1=0;
  721. else if (delay_index1>MAX_MEASUREMENT_DELAY)
  722. delay_index1=MAX_MEASUREMENT_DELAY;
  723. if(delay_index1 != delay_index2) //moved index
  724. {
  725. meas_sample=widthFil_to_size_ratio()-100; //subtract off 100 to reduce magnitude - to store in a signed char
  726. }
  727. while( delay_index1 != delay_index2)
  728. {
  729. delay_index2 = delay_index2 + 1;
  730. if(delay_index2>MAX_MEASUREMENT_DELAY)
  731. delay_index2=delay_index2-(MAX_MEASUREMENT_DELAY+1); //loop around buffer when incrementing
  732. if(delay_index2<0)
  733. delay_index2=0;
  734. else if (delay_index2>MAX_MEASUREMENT_DELAY)
  735. delay_index2=MAX_MEASUREMENT_DELAY;
  736. measurement_delay[delay_index2]=meas_sample;
  737. }
  738. }
  739. #endif
  740. // Calculate and limit speed in mm/sec for each axis
  741. float current_speed[4];
  742. float speed_factor = 1.0; //factor <=1 do decrease speed
  743. for(int i=0; i < 4; i++)
  744. {
  745. current_speed[i] = delta_mm[i] * inverse_second;
  746. if(fabs(current_speed[i]) > max_feedrate[i])
  747. speed_factor = min(speed_factor, max_feedrate[i] / fabs(current_speed[i]));
  748. }
  749. // Correct the speed
  750. if( speed_factor < 1.0)
  751. {
  752. for(unsigned char i=0; i < 4; i++)
  753. {
  754. current_speed[i] *= speed_factor;
  755. }
  756. block->nominal_speed *= speed_factor;
  757. block->nominal_rate *= speed_factor;
  758. }
  759. // Compute and limit the acceleration rate for the trapezoid generator.
  760. float steps_per_mm = block->step_event_count/block->millimeters;
  761. if(block->steps_x == 0 && block->steps_y == 0 && block->steps_z == 0)
  762. {
  763. block->acceleration_st = ceil(retract_acceleration * steps_per_mm); // convert to: acceleration steps/sec^2
  764. }
  765. else
  766. {
  767. block->acceleration_st = ceil(acceleration * steps_per_mm); // convert to: acceleration steps/sec^2
  768. // Limit acceleration per axis
  769. //FIXME Vojtech: One shall rather limit a projection of the acceleration vector instead of using the limit.
  770. if(((float)block->acceleration_st * (float)block->steps_x / (float)block->step_event_count) > axis_steps_per_sqr_second[X_AXIS])
  771. block->acceleration_st = axis_steps_per_sqr_second[X_AXIS];
  772. if(((float)block->acceleration_st * (float)block->steps_y / (float)block->step_event_count) > axis_steps_per_sqr_second[Y_AXIS])
  773. block->acceleration_st = axis_steps_per_sqr_second[Y_AXIS];
  774. if(((float)block->acceleration_st * (float)block->steps_e / (float)block->step_event_count) > axis_steps_per_sqr_second[E_AXIS])
  775. block->acceleration_st = axis_steps_per_sqr_second[E_AXIS];
  776. if(((float)block->acceleration_st * (float)block->steps_z / (float)block->step_event_count ) > axis_steps_per_sqr_second[Z_AXIS])
  777. block->acceleration_st = axis_steps_per_sqr_second[Z_AXIS];
  778. }
  779. block->acceleration = block->acceleration_st / steps_per_mm;
  780. block->acceleration_rate = (long)((float)block->acceleration_st * (16777216.0 / (F_CPU / 8.0)));
  781. #if 0 // Use old jerk for now
  782. // Compute path unit vector
  783. double unit_vec[3];
  784. unit_vec[X_AXIS] = delta_mm[X_AXIS]*inverse_millimeters;
  785. unit_vec[Y_AXIS] = delta_mm[Y_AXIS]*inverse_millimeters;
  786. unit_vec[Z_AXIS] = delta_mm[Z_AXIS]*inverse_millimeters;
  787. // Compute maximum allowable entry speed at junction by centripetal acceleration approximation.
  788. // Let a circle be tangent to both previous and current path line segments, where the junction
  789. // deviation is defined as the distance from the junction to the closest edge of the circle,
  790. // colinear with the circle center. The circular segment joining the two paths represents the
  791. // path of centripetal acceleration. Solve for max velocity based on max acceleration about the
  792. // radius of the circle, defined indirectly by junction deviation. This may be also viewed as
  793. // path width or max_jerk in the previous grbl version. This approach does not actually deviate
  794. // from path, but used as a robust way to compute cornering speeds, as it takes into account the
  795. // nonlinearities of both the junction angle and junction velocity.
  796. double vmax_junction = MINIMUM_PLANNER_SPEED; // Set default max junction speed
  797. // Skip first block or when previous_nominal_speed is used as a flag for homing and offset cycles.
  798. if ((block_buffer_head != block_buffer_tail) && (previous_nominal_speed > 0.0)) {
  799. // Compute cosine of angle between previous and current path. (prev_unit_vec is negative)
  800. // NOTE: Max junction velocity is computed without sin() or acos() by trig half angle identity.
  801. double cos_theta = - previous_unit_vec[X_AXIS] * unit_vec[X_AXIS]
  802. - previous_unit_vec[Y_AXIS] * unit_vec[Y_AXIS]
  803. - previous_unit_vec[Z_AXIS] * unit_vec[Z_AXIS] ;
  804. // Skip and use default max junction speed for 0 degree acute junction.
  805. if (cos_theta < 0.95) {
  806. vmax_junction = min(previous_nominal_speed,block->nominal_speed);
  807. // Skip and avoid divide by zero for straight junctions at 180 degrees. Limit to min() of nominal speeds.
  808. if (cos_theta > -0.95) {
  809. // Compute maximum junction velocity based on maximum acceleration and junction deviation
  810. double sin_theta_d2 = sqrt(0.5*(1.0-cos_theta)); // Trig half angle identity. Always positive.
  811. vmax_junction = min(vmax_junction,
  812. sqrt(block->acceleration * junction_deviation * sin_theta_d2/(1.0-sin_theta_d2)) );
  813. }
  814. }
  815. }
  816. #endif
  817. // Start with a safe speed.
  818. // Safe speed is the speed, from which the machine may halt to stop immediately.
  819. float safe_speed = block->nominal_speed;
  820. bool limited = false;
  821. for (uint8_t axis = 0; axis < 4; ++ axis) {
  822. float jerk = fabs(current_speed[axis]);
  823. if (jerk > max_jerk[axis]) {
  824. // The actual jerk is lower, if it has been limited by the XY jerk.
  825. if (limited) {
  826. // Spare one division by a following gymnastics:
  827. // Instead of jerk *= safe_speed / block->nominal_speed,
  828. // multiply max_jerk[axis] by the divisor.
  829. jerk *= safe_speed;
  830. float mjerk = max_jerk[axis] * block->nominal_speed;
  831. if (jerk > mjerk) {
  832. safe_speed *= mjerk / jerk;
  833. limited = true;
  834. }
  835. } else {
  836. safe_speed = max_jerk[axis];
  837. limited = true;
  838. }
  839. }
  840. }
  841. // Reset the block flag.
  842. block->flag = 0;
  843. // Initial limit on the segment entry velocity.
  844. float vmax_junction;
  845. //FIXME Vojtech: Why only if at least two lines are planned in the queue?
  846. // Is it because we don't want to tinker with the first buffer line, which
  847. // is likely to be executed by the stepper interrupt routine soon?
  848. if (moves_queued > 1 && previous_nominal_speed > 0.0001f) {
  849. // Estimate a maximum velocity allowed at a joint of two successive segments.
  850. // If this maximum velocity allowed is lower than the minimum of the entry / exit safe velocities,
  851. // then the machine is not coasting anymore and the safe entry / exit velocities shall be used.
  852. // The junction velocity will be shared between successive segments. Limit the junction velocity to their minimum.
  853. bool prev_speed_larger = previous_nominal_speed > block->nominal_speed;
  854. float smaller_speed_factor = prev_speed_larger ? (block->nominal_speed / previous_nominal_speed) : (previous_nominal_speed / block->nominal_speed);
  855. // Pick the smaller of the nominal speeds. Higher speed shall not be achieved at the junction during coasting.
  856. vmax_junction = prev_speed_larger ? block->nominal_speed : previous_nominal_speed;
  857. // Factor to multiply the previous / current nominal velocities to get componentwise limited velocities.
  858. float v_factor = 1.f;
  859. limited = false;
  860. // Now limit the jerk in all axes.
  861. for (uint8_t axis = 0; axis < 4; ++ axis) {
  862. // Limit an axis. We have to differentiate coasting from the reversal of an axis movement, or a full stop.
  863. float v_exit = previous_speed[axis];
  864. float v_entry = current_speed [axis];
  865. if (prev_speed_larger)
  866. v_exit *= smaller_speed_factor;
  867. if (limited) {
  868. v_exit *= v_factor;
  869. v_entry *= v_factor;
  870. }
  871. // Calculate the jerk depending on whether the axis is coasting in the same direction or reversing a direction.
  872. float jerk =
  873. (v_exit > v_entry) ?
  874. ((v_entry > 0.f || v_exit < 0.f) ?
  875. // coasting
  876. (v_exit - v_entry) :
  877. // axis reversal
  878. max(v_exit, - v_entry)) :
  879. // v_exit <= v_entry
  880. ((v_entry < 0.f || v_exit > 0.f) ?
  881. // coasting
  882. (v_entry - v_exit) :
  883. // axis reversal
  884. max(- v_exit, v_entry));
  885. if (jerk > max_jerk[axis]) {
  886. v_factor *= max_jerk[axis] / jerk;
  887. limited = true;
  888. }
  889. }
  890. if (limited)
  891. vmax_junction *= v_factor;
  892. // Now the transition velocity is known, which maximizes the shared exit / entry velocity while
  893. // respecting the jerk factors, it may be possible, that applying separate safe exit / entry velocities will achieve faster prints.
  894. float vmax_junction_threshold = vmax_junction * 0.99f;
  895. if (previous_safe_speed > vmax_junction_threshold && safe_speed > vmax_junction_threshold) {
  896. // Not coasting. The machine will stop and start the movements anyway,
  897. // better to start the segment from start.
  898. block->flag |= BLOCK_FLAG_START_FROM_FULL_HALT;
  899. vmax_junction = safe_speed;
  900. }
  901. } else {
  902. block->flag |= BLOCK_FLAG_START_FROM_FULL_HALT;
  903. vmax_junction = safe_speed;
  904. }
  905. // Max entry speed of this block equals the max exit speed of the previous block.
  906. block->max_entry_speed = vmax_junction;
  907. // Initialize block entry speed. Compute based on deceleration to safe_speed.
  908. double v_allowable = max_allowable_entry_speed(-block->acceleration,safe_speed,block->millimeters);
  909. block->entry_speed = min(vmax_junction, v_allowable);
  910. // Initialize planner efficiency flags
  911. // Set flag if block will always reach maximum junction speed regardless of entry/exit speeds.
  912. // If a block can de/ac-celerate from nominal speed to zero within the length of the block, then
  913. // the current block and next block junction speeds are guaranteed to always be at their maximum
  914. // junction speeds in deceleration and acceleration, respectively. This is due to how the current
  915. // block nominal speed limits both the current and next maximum junction speeds. Hence, in both
  916. // the reverse and forward planners, the corresponding block junction speed will always be at the
  917. // the maximum junction speed and may always be ignored for any speed reduction checks.
  918. // Always calculate trapezoid for new block
  919. block->flag |= (block->nominal_speed <= v_allowable) ? (BLOCK_FLAG_NOMINAL_LENGTH | BLOCK_FLAG_RECALCULATE) : BLOCK_FLAG_RECALCULATE;
  920. // Update previous path unit_vector and nominal speed
  921. memcpy(previous_speed, current_speed, sizeof(previous_speed)); // previous_speed[] = current_speed[]
  922. previous_nominal_speed = block->nominal_speed;
  923. previous_safe_speed = safe_speed;
  924. #ifdef ADVANCE
  925. // Calculate advance rate
  926. if((block->steps_e == 0) || (block->steps_x == 0 && block->steps_y == 0 && block->steps_z == 0)) {
  927. block->advance_rate = 0;
  928. block->advance = 0;
  929. }
  930. else {
  931. long acc_dist = estimate_acceleration_distance(0, block->nominal_rate, block->acceleration_st);
  932. float advance = (STEPS_PER_CUBIC_MM_E * EXTRUDER_ADVANCE_K) *
  933. (current_speed[E_AXIS] * current_speed[E_AXIS] * EXTRUSION_AREA * EXTRUSION_AREA)*256;
  934. block->advance = advance;
  935. if(acc_dist == 0) {
  936. block->advance_rate = 0;
  937. }
  938. else {
  939. block->advance_rate = advance / (float)acc_dist;
  940. }
  941. }
  942. /*
  943. SERIAL_ECHO_START;
  944. SERIAL_ECHOPGM("advance :");
  945. SERIAL_ECHO(block->advance/256.0);
  946. SERIAL_ECHOPGM("advance rate :");
  947. SERIAL_ECHOLN(block->advance_rate/256.0);
  948. */
  949. #endif // ADVANCE
  950. calculate_trapezoid_for_block(block, block->entry_speed/block->nominal_speed, safe_speed/block->nominal_speed);
  951. // Move the buffer head. From now the block may be picked up by the stepper interrupt controller.
  952. block_buffer_head = next_buffer_head;
  953. // Update position
  954. memcpy(position, target, sizeof(target)); // position[] = target[]
  955. // Recalculate the trapezoids to maximize speed at the segment transitions while respecting
  956. // the machine limits (maximum acceleration and maximum jerk).
  957. // This runs asynchronously with the stepper interrupt controller, which may
  958. // interfere with the process.
  959. planner_recalculate(safe_speed);
  960. // SERIAL_ECHOPGM("Q");
  961. // SERIAL_ECHO(int(moves_planned()));
  962. // SERIAL_ECHOLNPGM("");
  963. st_wake_up();
  964. }
  965. #ifdef ENABLE_AUTO_BED_LEVELING
  966. vector_3 plan_get_position() {
  967. vector_3 position = vector_3(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS), st_get_position_mm(Z_AXIS));
  968. //position.debug("in plan_get position");
  969. //plan_bed_level_matrix.debug("in plan_get bed_level");
  970. matrix_3x3 inverse = matrix_3x3::transpose(plan_bed_level_matrix);
  971. //inverse.debug("in plan_get inverse");
  972. position.apply_rotation(inverse);
  973. //position.debug("after rotation");
  974. return position;
  975. }
  976. #endif // ENABLE_AUTO_BED_LEVELING
  977. void plan_set_position(float x, float y, float z, const float &e)
  978. {
  979. #ifdef ENABLE_AUTO_BED_LEVELING
  980. apply_rotation_xyz(plan_bed_level_matrix, x, y, z);
  981. #endif // ENABLE_AUTO_BED_LEVELING
  982. // Apply the machine correction matrix.
  983. {
  984. float tmpx = x;
  985. float tmpy = y;
  986. x = world2machine_rotation_and_skew[0][0] * tmpx + world2machine_rotation_and_skew[0][1] * tmpy + world2machine_shift[0];
  987. y = world2machine_rotation_and_skew[1][0] * tmpx + world2machine_rotation_and_skew[1][1] * tmpy + world2machine_shift[1];
  988. }
  989. position[X_AXIS] = lround(x*axis_steps_per_unit[X_AXIS]);
  990. position[Y_AXIS] = lround(y*axis_steps_per_unit[Y_AXIS]);
  991. #ifdef MESH_BED_LEVELING
  992. if (mbl.active){
  993. position[Z_AXIS] = lround((z+mbl.get_z(x, y))*axis_steps_per_unit[Z_AXIS]);
  994. }else{
  995. position[Z_AXIS] = lround(z*axis_steps_per_unit[Z_AXIS]);
  996. }
  997. #else
  998. position[Z_AXIS] = lround(z*axis_steps_per_unit[Z_AXIS]);
  999. #endif // ENABLE_MESH_BED_LEVELING
  1000. position[E_AXIS] = lround(e*axis_steps_per_unit[E_AXIS]);
  1001. st_set_position(position[X_AXIS], position[Y_AXIS], position[Z_AXIS], position[E_AXIS]);
  1002. previous_nominal_speed = 0.0; // Resets planner junction speeds. Assumes start from rest.
  1003. previous_speed[0] = 0.0;
  1004. previous_speed[1] = 0.0;
  1005. previous_speed[2] = 0.0;
  1006. previous_speed[3] = 0.0;
  1007. }
  1008. // Only useful in the bed leveling routine, when the mesh bed leveling is off.
  1009. void plan_set_z_position(const float &z)
  1010. {
  1011. position[Z_AXIS] = lround(z*axis_steps_per_unit[Z_AXIS]);
  1012. st_set_position(position[X_AXIS], position[Y_AXIS], position[Z_AXIS], position[E_AXIS]);
  1013. }
  1014. void plan_set_e_position(const float &e)
  1015. {
  1016. position[E_AXIS] = lround(e*axis_steps_per_unit[E_AXIS]);
  1017. st_set_e_position(position[E_AXIS]);
  1018. }
  1019. #ifdef PREVENT_DANGEROUS_EXTRUDE
  1020. void set_extrude_min_temp(float temp)
  1021. {
  1022. extrude_min_temp=temp;
  1023. }
  1024. #endif
  1025. // Calculate the steps/s^2 acceleration rates, based on the mm/s^s
  1026. void reset_acceleration_rates()
  1027. {
  1028. for(int8_t i=0; i < NUM_AXIS; i++)
  1029. {
  1030. axis_steps_per_sqr_second[i] = max_acceleration_units_per_sq_second[i] * axis_steps_per_unit[i];
  1031. }
  1032. }