plcopen 0.22.0
载入中...
搜索中...
未找到
group_cartesian_impl.h
浏览该文件的文档.
1#pragma once
2
3// AxisGroup batch 3 Cartesian path/window implementation.
4// Included by group.h after AxisGroup is complete.
5
7{
8
9inline rt::Result<std::uint32_t> AxisGroup::submit_cartesian_window(GroupCommand command)
10{
11 if(command.command_id == 0) {
12 command.command_id = next_command_id_++;
13 }
14 if(command.coord_system != CoordSystem::mcs &&
15 command.coord_system != CoordSystem::pcs) {
17 }
18 if(command.relative || !queue_.empty() || joint_window_.active_) {
20 }
21 const bool is_pose = pose_frames_.pose_kinematics_ != nullptr;
22 if(!is_pose && pose_frames_.kinematics_ == nullptr) {
24 }
25 if(is_pose && !pose_window_enabled_) {
27 }
28 if(command.tool_number != active_tool_ ||
29 command.payload_number != active_payload_) {
30 command.buffer_mode = BufferMode::buffered;
31 command.transition_mode = TransitionMode::none;
32 command.transition_velocity = 0.0;
33 command.transition_parameter = 0.0;
34 const rt::ErrorCode prepared = prepare_cartesian_linear(command);
35 if(prepared != rt::ErrorCode::ok) {
37 }
38 const rt::ErrorCode queued = queue_.push_back(command);
41 }
42 last_blend_degraded_id_ = command.command_id;
44 }
45 const bool extend = cartesian_.window_active_;
46 if(!extend) {
47 // Conversion seed: an active, non-chain, non-arc, non-angle-driven
48 // Cartesian line matching the active plugin kind.
49 if(!active_ || status_ != GroupStatus::moving ||
50 active_kind_ != GroupPathKind::cartesian_linear ||
51 active_command_.dynamic_pcs ||
52 cartesian_.takeover_active_ ||
53 cartesian_.active_segment_.arc_path || cartesian_.active_segment_.chain ||
54 cartesian_.active_segment_.angle_driven ||
55 cartesian_.active_segment_.pose != is_pose || active_path_length_ <= 0.0) {
57 }
58 } else if(cartesian_.window_stopping_ || cartesian_.window_pose_ != is_pose) {
60 }
61
62 auto copy_rot = [](const double src[3][3], double dst[3][3]) {
63 for(int r = 0; r < 3; ++r) {
64 for(int c = 0; c < 3; ++c) {
65 dst[r][c] = src[r][c];
66 }
67 }
68 };
69 auto advance_rot = [](const double start_r[3][3], const double axis[3],
70 double angle, double out_r[3][3]) {
71 double delta_r[3][3] = {};
72 geom::rodrigues(axis, angle, delta_r);
73 geom::rotation_multiply(start_r, delta_r, out_r);
74 };
75
76 // Successor target in the plugin Cartesian / TCP domain.
77 geom::Vec3 target_point = cartesian_part(command.target);
78 geom::RigidTransform target_pose{};
79 if(is_pose) {
80 target_pose = geom::make_rpy_transform(
81 command.target.value[0], command.target.value[1],
82 command.target.value[2], command.target.value[3],
83 command.target.value[4], command.target.value[5]);
84 if(command.coord_system == CoordSystem::pcs) {
85 target_pose = geom::compose(pose_frames_.workpiece_frame_, target_pose);
86 }
87 target_point = target_pose.translation;
88 } else {
89 if(command.coord_system == CoordSystem::pcs) {
90 target_point = geom::transform_point(pose_frames_.workpiece_frame_, target_point);
91 }
92 target_point = target_point - pose_frames_.tool_offset_;
93 }
94
95 // Tail geometry: the line the corner attaches to.
96 geom::Vec3 tail_end{};
97 geom::Vec3 tail_dir{};
98 double tail_room = 0.0; // trimmable room on the tail line
99 std::size_t tail_index = 0;
100 double tail_end_rot[3][3] = {{1.0, 0.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 0.0, 1.0}};
101 double live_entry_v = 0.0;
102 double live_entry_a = 0.0;
103 double live_s = 0.0;
104
105 if(!extend) {
106 const otg::State1D live = otg::sample(
107 active_profile_, rt::CycleTick::from_cycles(active_tick_));
108 live_s = live.position < 0.0 ? 0.0 : live.position;
109 live_s = live_s > active_path_length_ ? active_path_length_ : live_s;
110 live_entry_v = live.velocity < 0.0 ? 0.0 : live.velocity;
111 live_entry_a = live.acceleration;
112 tail_end = geom::Vec3{cartesian_.active_segment_.start.x + cartesian_.active_segment_.delta.x,
113 cartesian_.active_segment_.start.y + cartesian_.active_segment_.delta.y,
114 cartesian_.active_segment_.start.z + cartesian_.active_segment_.delta.z};
115 const double len = geom::norm(cartesian_.active_segment_.delta);
116 if(len <= 1e-12) {
118 }
119 tail_dir = geom::Vec3{cartesian_.active_segment_.delta.x / len,
120 cartesian_.active_segment_.delta.y / len,
121 cartesian_.active_segment_.delta.z / len};
122 tail_room = active_path_length_ - live_s;
123 if(is_pose) {
124 advance_rot(cartesian_.active_segment_.rotation_start,
125 cartesian_.active_segment_.axis,
126 cartesian_.active_segment_.angle, tail_end_rot);
127 }
128 } else {
129 tail_index = cartesian_.window_.size() - 1;
130 const CartPiece &tail = cartesian_.window_[tail_index];
131 tail_end = geom::Vec3{tail.start.x + tail.dir.x * tail.length,
132 tail.start.y + tail.dir.y * tail.length,
133 tail.start.z + tail.dir.z * tail.length};
134 tail_dir = tail.dir;
135 if(is_pose) {
136 advance_rot(tail.rotation_start, tail.axis, tail.angle, tail_end_rot);
137 }
138 if(tail_index == cartesian_.piece_index_) {
139 const otg::State1D live = otg::sample(
140 cartesian_.window_[tail_index].profile,
141 rt::CycleTick::from_cycles(cartesian_.piece_tick_));
142 live_s = live.position < 0.0 ? 0.0 : live.position;
143 live_s = live_s > tail.length ? tail.length : live_s;
144 live_entry_v = live.velocity < 0.0 ? 0.0 : live.velocity;
145 live_entry_a = live.acceleration;
146 tail_room = tail.length - live_s;
147 } else if(tail_index > cartesian_.piece_index_) {
148 tail_room = tail.length;
149 } else {
151 }
152 }
153
154 if(is_pose && command.orientation_mode == OrientationMode::constant) {
155 copy_rot(tail_end_rot, target_pose.rotation);
156 }
157 double leg_axis[3] = {0.0, 0.0, 1.0};
158 double leg_angle = 0.0;
159 if(is_pose) {
160 geom::relative_axis_angle(tail_end_rot, target_pose.rotation,
161 leg_axis, leg_angle);
162 if(leg_angle >= 3.14159265358979323846 - 1e-6) {
164 }
165 }
166
167 const geom::Vec3 out_vec = target_point - tail_end;
168 const double len_b = geom::norm(out_vec);
169 bool degrade = false;
170 double trim = 0.0;
171 double corner_cap = 0.0;
172 geom::QuinticBlendSegment corner{};
173 bool passthrough = false;
174 if(len_b <= 1e-12) {
175 degrade = true;
176 } else {
177 const geom::Vec3 t1{out_vec.x / len_b, out_vec.y / len_b,
178 out_vec.z / len_b};
179 const double dot =
180 tail_dir.x * t1.x + tail_dir.y * t1.y + tail_dir.z * t1.z;
181 if(dot <= -0.999) {
182 degrade = true;
183 } else if(dot >= 1.0 - 1e-9) {
184 passthrough = true;
185 } else {
186 const geom::Vec3 diff{t1.x - tail_dir.x, t1.y - tail_dir.y,
187 t1.z - tail_dir.z};
188 const double turn = geom::norm(diff);
189 trim = command.transition_parameter * 96.0 / (23.0 * turn);
190 const double room = tail_room < len_b ? tail_room : len_b;
191 if(trim > 0.5 * room) {
192 trim = 0.5 * room;
193 }
194 if(trim <= 1e-9 || tail_room <= trim) {
195 degrade = true;
196 } else {
197 const geom::Vec3 entry{tail_end.x - tail_dir.x * trim,
198 tail_end.y - tail_dir.y * trim,
199 tail_end.z - tail_dir.z * trim};
200 const geom::Vec3 exit{tail_end.x + t1.x * trim,
201 tail_end.y + t1.y * trim,
202 tail_end.z + t1.z * trim};
203 const rt::Result<geom::QuinticBlendSegment> blend =
204 geom::make_quintic_blend(entry, tail_end, exit,
205 command.transition_parameter);
206 if(!blend) {
207 degrade = true;
208 } else {
209 corner = blend.value();
210 const double axis_accel =
211 command.acceleration < command.deceleration
212 ? command.acceleration
213 : command.deceleration;
214 corner_cap = corner.max_curvature > 1e-12
215 ? std::sqrt(axis_accel /
216 corner.max_curvature)
217 : command.velocity;
218 }
219 }
220 }
221 }
222
223 const std::size_t base_pieces = extend ? cartesian_.window_.size() : 1;
224 if(!degrade &&
225 base_pieces + (passthrough ? 1 : 2) > CartWindowPieces) {
228 }
229 if(!degrade && !passthrough && command.transition_velocity > 0.0 &&
230 command.transition_velocity < corner_cap) {
231 corner_cap = command.transition_velocity;
232 }
233
234 // Extending while riding a corner piece is a declared too-late degrade.
235 if(!degrade && extend && cartesian_.window_[cartesian_.piece_index_].corner) {
236 degrade = true;
237 }
238
239 if(!degrade) {
240 // Stage the candidate window into cartesian_.staging_window_ so any
241 // validation or rebuild failure leaves live state untouched (atomic).
242 CartStorage &staging = cartesian_.staging_window_;
243 staging.clear();
244 std::size_t stage_start_index = 0;
245 double stage_entry_v = 0.0;
246 double stage_entry_a = 0.0;
247 double stage_acc = 0.0;
248 double stage_dec = 0.0;
249 double stage_jerk = 0.0;
250 double entry_rot[3][3] = {{1.0, 0.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 0.0, 1.0}};
251
252 if(!extend) {
253 CartPiece first{};
254 first.pose = is_pose;
255 first.start = geom::Vec3{
256 cartesian_.active_segment_.start.x + tail_dir.x * live_s,
257 cartesian_.active_segment_.start.y + tail_dir.y * live_s,
258 cartesian_.active_segment_.start.z + tail_dir.z * live_s};
259 first.dir = tail_dir;
260 first.length = (active_path_length_ - live_s) - (passthrough ? 0.0 : trim);
261 first.cap = active_command_.velocity;
262 if(is_pose) {
263 const double f_live = live_s / active_path_length_;
264 const double f_end =
265 (active_path_length_ - (passthrough ? 0.0 : trim)) /
266 active_path_length_;
267 advance_rot(cartesian_.active_segment_.rotation_start,
268 cartesian_.active_segment_.axis,
269 cartesian_.active_segment_.angle * f_live,
270 first.rotation_start);
271 for(int d = 0; d < 3; ++d) {
272 first.axis[d] = cartesian_.active_segment_.axis[d];
273 }
274 first.angle = cartesian_.active_segment_.angle * (f_end - f_live);
275 advance_rot(first.rotation_start, first.axis, first.angle, entry_rot);
276 }
277 staging.push_back(first);
278 stage_start_index = 0;
279 stage_entry_v = live_entry_v;
280 stage_entry_a = live_entry_a;
281 stage_acc = active_command_.acceleration;
282 stage_dec = active_command_.deceleration;
283 stage_jerk = active_command_.jerk;
284 } else {
285 staging.copy_from(cartesian_.window_);
286 stage_start_index = cartesian_.piece_index_;
287 const std::size_t stage_tail_index = tail_index;
288 CartPiece &current = staging[stage_start_index];
289 const otg::State1D live = otg::sample(
290 current.profile, rt::CycleTick::from_cycles(cartesian_.piece_tick_));
291 double s_cur = live.position < 0.0 ? 0.0 : live.position;
292 s_cur = s_cur > current.length ? current.length : s_cur;
293 const double orig_cur_len = current.length;
294 current.start = geom::Vec3{current.start.x + current.dir.x * s_cur,
295 current.start.y + current.dir.y * s_cur,
296 current.start.z + current.dir.z * s_cur};
297 current.length -= s_cur;
298 if(is_pose && orig_cur_len > 1e-12) {
299 const double f_cur = s_cur / orig_cur_len;
300 double next_r[3][3] = {};
301 advance_rot(current.rotation_start, current.axis,
302 current.angle * f_cur, next_r);
303 copy_rot(next_r, current.rotation_start);
304 current.angle *= (1.0 - f_cur);
305 }
306 stage_entry_v = live.velocity < 0.0 ? 0.0 : live.velocity;
307 stage_entry_a = live.acceleration;
308 stage_acc = cartesian_.window_acceleration_;
309 stage_dec = cartesian_.window_deceleration_;
310 stage_jerk = cartesian_.window_jerk_;
311
312 CartPiece &tail_piece = staging[stage_tail_index];
313 const double pre_trim_len = tail_piece.length;
314 if(!passthrough) {
315 tail_piece.length -= trim;
316 if(is_pose && pre_trim_len > 1e-12) {
317 const double f_keep = tail_piece.length / pre_trim_len;
318 tail_piece.angle *= f_keep;
319 }
320 }
321 if(is_pose) {
322 advance_rot(tail_piece.rotation_start, tail_piece.axis,
323 tail_piece.angle, entry_rot);
324 }
325 }
326
327 // Build corner piece (if !passthrough) and new line piece.
328 CartPiece corner_piece{};
329 CartPiece line_piece{};
330 const geom::Vec3 t1{out_vec.x / len_b, out_vec.y / len_b,
331 out_vec.z / len_b};
332 if(!passthrough) {
333 corner_piece.corner = true;
334 corner_piece.pose = is_pose;
335 corner_piece.blend = corner;
336 corner_piece.length = corner.length;
337 corner_piece.cap = corner_cap;
338 if(is_pose) {
339 const double f_exit = trim / len_b;
340 double exit_rot[3][3] = {};
341 advance_rot(tail_end_rot, leg_axis, leg_angle * f_exit, exit_rot);
342 copy_rot(entry_rot, corner_piece.rotation_start);
343 geom::relative_axis_angle(entry_rot, exit_rot,
344 corner_piece.axis, corner_piece.angle);
345 if(corner_piece.angle >= 3.14159265358979323846 - 1e-6) {
348 }
349 line_piece.pose = true;
350 copy_rot(exit_rot, line_piece.rotation_start);
351 for(int d = 0; d < 3; ++d) {
352 line_piece.axis[d] = leg_axis[d];
353 }
354 line_piece.angle = leg_angle * (1.0 - f_exit);
355 }
356 } else if(is_pose) {
357 line_piece.pose = true;
358 copy_rot(tail_end_rot, line_piece.rotation_start);
359 for(int d = 0; d < 3; ++d) {
360 line_piece.axis[d] = leg_axis[d];
361 }
362 line_piece.angle = leg_angle;
363 }
364 line_piece.start = passthrough
365 ? tail_end
366 : geom::Vec3{tail_end.x + t1.x * trim,
367 tail_end.y + t1.y * trim,
368 tail_end.z + t1.z * trim};
369 line_piece.dir = t1;
370 line_piece.length = passthrough ? len_b : len_b - trim;
371 line_piece.cap = command.velocity;
372 if(passthrough && command.transition_velocity > 0.0 &&
373 command.transition_velocity < line_piece.cap) {
374 line_piece.cap = command.transition_velocity;
375 }
376
377 // Pre-validate the REAL trimmed corner piece (if present) and the REAL
378 // new line piece through IK, singularity margin, and member soft limits.
379 double chain[MaxAxes] = {};
380 if(!extend) {
381 for(std::size_t i = 0; i < axes_.size(); ++i) {
382 chain[i] = active_finish_[i];
383 }
384 } else {
385 for(std::size_t i = 0; i < axes_.size(); ++i) {
386 chain[i] = cart_tail_joints_[i];
387 }
388 }
389
390 auto solve_sample_ik = [&](const geom::RigidTransform &tcp,
391 const double *seed_in,
392 double *q_out) -> rt::ErrorCode {
393 if(is_pose) {
394 const geom::RigidTransform flange =
395 geom::compose(tcp, pose_frames_.pose_tool_inverse_);
396 kin::Pose6 pose{};
397 pose.position[0] = flange.translation.x;
398 pose.position[1] = flange.translation.y;
399 pose.position[2] = flange.translation.z;
400 copy_rot(flange.rotation, pose.rotation);
401 const rt::ErrorCode s = pose_frames_.pose_kinematics_->inverse(
402 pose, seed_in, pose_frames_.pose_max_joint_step_, q_out);
403 if(s != rt::ErrorCode::ok) {
404 return s;
405 }
406 if(pose_frames_.pose_kinematics_->singularity_margin(q_out) <
407 pose_frames_.pose_min_margin_) {
409 }
410 } else {
411 const rt::ErrorCode s = pose_frames_.kinematics_->inverse(
412 tcp.translation, seed_in, axes_.size(), q_out);
413 if(s != rt::ErrorCode::ok) {
414 return s;
415 }
416 if(pose_frames_.kinematics_->singularity_margin(q_out, axes_.size()) <
417 pose_frames_.kinematics_min_margin_) {
419 }
420 }
421 GroupPosition gp{};
422 gp.size = axes_.size();
423 for(std::size_t i = 0; i < axes_.size(); ++i) {
424 gp.value[i] = q_out[i];
425 }
426 return preflight_member_targets(gp);
427 };
428
429 // Walk seed safely back from tail_end to corner entry when !passthrough
430 // so large trims never trip pose_max_joint_step on corner sample 0.
431 if(!passthrough) {
432 constexpr int BackSteps = 8;
433 double q_back[MaxAxes] = {};
434 double entry_axis[3] = {0.0, 0.0, 1.0};
435 double entry_ang = 0.0;
436 if(is_pose) {
437 geom::relative_axis_angle(tail_end_rot, entry_rot,
438 entry_axis, entry_ang);
439 }
440 for(int k = 1; k <= BackSteps; ++k) {
441 const double frac =
442 static_cast<double>(k) / static_cast<double>(BackSteps);
443 geom::RigidTransform tcp{};
444 tcp.translation = geom::Vec3{tail_end.x - tail_dir.x * (trim * frac),
445 tail_end.y - tail_dir.y * (trim * frac),
446 tail_end.z - tail_dir.z * (trim * frac)};
447 if(is_pose) {
448 advance_rot(tail_end_rot, entry_axis, entry_ang * frac,
449 tcp.rotation);
450 }
451 const rt::ErrorCode solved = solve_sample_ik(tcp, chain, q_back);
452 if(solved != rt::ErrorCode::ok) {
454 }
455 for(std::size_t i = 0; i < axes_.size(); ++i) {
456 chain[i] = q_back[i];
457 }
458 }
459 }
460
461 auto prevalidate_piece = [&](CartPiece &piece) -> rt::ErrorCode {
462 constexpr int Samples = 32;
463 double q[MaxAxes] = {};
464 double worst_step = 0.0;
465 for(int k = 0; k <= Samples; ++k) {
466 const double s =
467 piece.length * static_cast<double>(k) / static_cast<double>(Samples);
468 geom::RigidTransform tcp{};
469 if(is_pose) {
470 cart_piece_pose(piece, s, tcp);
471 } else {
472 tcp.translation = cart_piece_point(piece, s);
473 }
474 const rt::ErrorCode solved = solve_sample_ik(tcp, chain, q);
475 if(solved != rt::ErrorCode::ok) {
476 return solved;
477 }
478 if(k > 0) {
479 for(std::size_t i = 0; i < axes_.size(); ++i) {
480 const double step = std::fabs(q[i] - chain[i]);
481 if(step > worst_step) {
482 worst_step = step;
483 }
484 }
485 }
486 for(std::size_t i = 0; i < axes_.size(); ++i) {
487 chain[i] = q[i];
488 }
489 }
490 if(is_pose && worst_step > 0.0 && piece.length > 0.0) {
491 const double per_unit =
492 worst_step / (piece.length / static_cast<double>(Samples));
493 const double allowed =
494 0.5 * pose_frames_.pose_max_joint_step_ / per_unit;
495 if(allowed < piece.cap) {
496 piece.cap = allowed;
497 }
498 }
499 return rt::ErrorCode::ok;
500 };
501
502 if(!passthrough) {
503 const rt::ErrorCode corner_ok = prevalidate_piece(corner_piece);
504 if(corner_ok != rt::ErrorCode::ok) {
505 return rt::Result<std::uint32_t>::failure(corner_ok);
506 }
507 staging.push_back(corner_piece);
508 }
509 const rt::ErrorCode line_ok = prevalidate_piece(line_piece);
510 if(line_ok != rt::ErrorCode::ok) {
512 }
513 staging.push_back(line_piece);
514
515 stage_acc = stage_acc < command.acceleration ? stage_acc : command.acceleration;
516 stage_dec = stage_dec < command.deceleration ? stage_dec : command.deceleration;
517 stage_jerk = stage_jerk < command.jerk ? stage_jerk : command.jerk;
518
519 if(!cart_window_rebuild_storage(staging, stage_start_index, stage_entry_v,
520 stage_entry_a, stage_acc, stage_dec,
521 stage_jerk)) {
522 // Atomic degradation: live window/active motion untouched; queue as BUFFERED.
523 staging.clear();
524 } else {
525 // Atomic commit: swap staged window into live window.
526 cartesian_.window_.swap(staging);
527 staging.clear();
528 if(!extend) {
529 for(std::size_t i = 0; i < axes_.size(); ++i) {
530 cartesian_.window_joints_[i] = cartesian_.joints_[i];
531 }
532 active_ = false;
533 cartesian_.window_active_ = true;
534 cartesian_.window_pose_ = is_pose;
535 cartesian_.piece_index_ = 0;
536 }
537 cartesian_.piece_tick_ = 0;
538 cartesian_.window_entry_velocity_ = stage_entry_v;
539 cartesian_.window_entry_acceleration_ = stage_entry_a;
540 cartesian_.window_acceleration_ = stage_acc;
541 cartesian_.window_deceleration_ = stage_dec;
542 cartesian_.window_jerk_ = stage_jerk;
543 for(std::size_t i = 0; i < axes_.size(); ++i) {
544 cart_tail_joints_[i] = chain[i];
545 }
546 cartesian_.window_last_id_ = command.command_id;
547 status_ = GroupStatus::moving;
549 }
550 }
551
552 // Reported degradation: plain buffered Cartesian segment behind the
553 // window (or behind the active segment). Record degradation only after
554 // both preparation and queue commit succeed.
555 command.buffer_mode = BufferMode::buffered;
556 command.transition_mode = TransitionMode::none;
557 command.transition_velocity = 0.0;
558 command.transition_parameter = 0.0;
559 const rt::ErrorCode prepared = prepare_cartesian_linear(command);
560 if(prepared != rt::ErrorCode::ok) {
561 return rt::Result<std::uint32_t>::failure(prepared);
562 }
563 const rt::ErrorCode queued = queue_.push_back(command);
566 }
567 last_blend_degraded_id_ = command.command_id;
569}
570
571inline bool AxisGroup::verify_profile_monotonic(const otg::Profile1D &p, double length)
572{
573 if(!std::isfinite(length) || length < 0.0) {
574 return false;
575 }
576 auto state_ok = [&](double pos, double vel) -> bool {
577 return std::isfinite(pos) && std::isfinite(vel) &&
578 vel >= -1e-9 && pos >= -1e-7 && pos <= length + 1e-7;
579 };
580 auto insert_sorted_unique = [](double *arr, int &cnt, int cap, double val) {
581 for(int i = 0; i < cnt; ++i) {
582 if(std::fabs(arr[i] - val) <= 1e-14) {
583 return;
584 }
585 }
586 if(cnt >= cap) {
587 return;
588 }
589 int pos = cnt;
590 while(pos > 0 && arr[pos - 1] > val) {
591 arr[pos] = arr[pos - 1];
592 --pos;
593 }
594 arr[pos] = val;
595 ++cnt;
596 };
597 for(std::size_t idx = 0; idx < p.segment_count(); ++idx) {
598 const otg::Segment1D &seg = p.segment(idx);
599 if(seg.duration_cycles < 0 || !otg::is_finite(seg.start) ||
600 !otg::is_finite(seg.finish) || !std::isfinite(seg.c0) ||
601 !std::isfinite(seg.c1) || !std::isfinite(seg.c2) ||
602 !std::isfinite(seg.c3) || !std::isfinite(seg.c4) ||
603 !std::isfinite(seg.c5)) {
604 return false;
605 }
606 if(!state_ok(seg.start.position, seg.start.velocity) ||
607 !state_ok(seg.finish.position, seg.finish.velocity)) {
608 return false;
609 }
610 if(seg.duration_cycles == 0) {
611 continue;
612 }
613 const double dur_d = static_cast<double>(seg.duration_cycles);
614 // Normalized u = x / dur_d in [0, 1]:
615 // p(u) = d0 + d1*u + d2*u^2 + d3*u^3 + d4*u^4 + d5*u^5
616 // v(u) = v0 + v1*u + v2*u^2 + v3*u^3 + v4*u^4
617 // a_u(u) = v'(u) = v1 + 2*v2*u + 3*v3*u^2 + 4*v4*u^3
618 // j_u(u) = v''(u) = 2*v2 + 6*v3*u + 12*v4*u^2
619 const double d0 = seg.c0;
620 const double d1 = seg.c1 * dur_d;
621 const double d2 = (seg.c2 * dur_d) * dur_d;
622 const double d3 = ((seg.c3 * dur_d) * dur_d) * dur_d;
623 const double d4 = (((seg.c4 * dur_d) * dur_d) * dur_d) * dur_d;
624 const double d5 = ((((seg.c5 * dur_d) * dur_d) * dur_d) * dur_d) * dur_d;
625 const double v0 = seg.c1;
626 const double v1 = 2.0 * (seg.c2 * dur_d);
627 const double v2 = 3.0 * ((seg.c3 * dur_d) * dur_d);
628 const double v3 = 4.0 * (((seg.c4 * dur_d) * dur_d) * dur_d);
629 const double v4 = 5.0 * ((((seg.c5 * dur_d) * dur_d) * dur_d) * dur_d);
630 if(!std::isfinite(d1) || !std::isfinite(d2) || !std::isfinite(d3) ||
631 !std::isfinite(d4) || !std::isfinite(d5) || !std::isfinite(v1) ||
632 !std::isfinite(v2) || !std::isfinite(v3) || !std::isfinite(v4)) {
633 return false;
634 }
635 auto eval_p_u = [&](double u) -> double {
636 return d0 + u * (d1 + u * (d2 + u * (d3 + u * (d4 + u * d5))));
637 };
638 auto eval_v_u = [&](double u) -> double {
639 return v0 + u * (v1 + u * (v2 + u * (v3 + u * v4)));
640 };
641 auto eval_a_u = [&](double u) -> double {
642 return v1 + u * (2.0 * v2 + u * (3.0 * v3 + u * (4.0 * v4)));
643 };
644 auto check_u = [&](double u) -> bool {
645 if(!std::isfinite(u) || u <= 0.0 || u >= 1.0) {
646 return true;
647 }
648 if(!state_ok(eval_p_u(u), eval_v_u(u))) {
649 return false;
650 }
651 const double x = u * dur_d;
652 const double xf = std::floor(x);
653 if(xf > 0.0 && xf < dur_d) {
654 const double uf = xf / dur_d;
655 if(!state_ok(eval_p_u(uf), eval_v_u(uf))) return false;
656 }
657 const double xc = std::ceil(x);
658 if(xc > 0.0 && xc < dur_d) {
659 const double uc = xc / dur_d;
660 if(!state_ok(eval_p_u(uc), eval_v_u(uc))) return false;
661 }
662 return true;
663 };
664
665 // Step 1: partition [0, 1] at all roots (and double-root vertex) of j_u(u) = 0
666 // so a_u(u) is monotonic on every subinterval.
667 double a_breaks[4] = {0.0, 1.0, 0.0, 0.0};
668 int a_cnt = 2;
669 const double qa = 12.0 * v4;
670 const double qb = 6.0 * v3;
671 const double qc = 2.0 * v2;
672 double j_scale = std::fabs(qa);
673 if(std::fabs(qb) > j_scale) j_scale = std::fabs(qb);
674 if(std::fabs(qc) > j_scale) j_scale = std::fabs(qc);
675 if(j_scale > 0.0) {
676 if(std::fabs(qa) > 1.0e-15 * j_scale) {
677 const double disc = qb * qb - 4.0 * qa * qc;
678 if(std::isfinite(disc) && disc >= 0.0) {
679 const double sdisc = std::sqrt(disc);
680 const double q_tmp = -0.5 * (qb + (qb >= 0.0 ? sdisc : -sdisc));
681 const double r1 = q_tmp / qa;
682 const double r2 = q_tmp != 0.0 ? (qc / q_tmp) : 0.0;
683 if(std::isfinite(r1) && r1 > 0.0 && r1 < 1.0) {
684 insert_sorted_unique(a_breaks, a_cnt, 4, r1);
685 }
686 if(std::isfinite(r2) && r2 > 0.0 && r2 < 1.0) {
687 insert_sorted_unique(a_breaks, a_cnt, 4, r2);
688 }
689 } else {
690 // Guard against slightly negative discriminant from rounding at a double root.
691 const double rv = -qb / (2.0 * qa);
692 if(std::isfinite(rv) && rv > 0.0 && rv < 1.0) {
693 insert_sorted_unique(a_breaks, a_cnt, 4, rv);
694 }
695 }
696 } else if(std::fabs(qb) > 1.0e-15 * j_scale) {
697 const double r1 = -qc / qb;
698 if(std::isfinite(r1) && r1 > 0.0 && r1 < 1.0) {
699 insert_sorted_unique(a_breaks, a_cnt, 4, r1);
700 }
701 }
702 }
703
704 // Step 2: collect EVERY interior a_break (capturing multiple/tangential
705 // roots of a_u(u) = 0 that coincide with j_u(u) = 0!) PLUS all strict
706 // sign-change roots of a_u(u) = 0 so v(u) is monotonic on every subinterval.
707 double v_breaks[8] = {0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
708 int v_cnt = 2;
709 for(int k = 1; k + 1 < a_cnt; ++k) {
710 insert_sorted_unique(v_breaks, v_cnt, 8, a_breaks[k]);
711 }
712 for(int k = 0; k + 1 < a_cnt; ++k) {
713 double lo = a_breaks[k];
714 double hi = a_breaks[k + 1];
715 const double alo = eval_a_u(lo);
716 const double ahi = eval_a_u(hi);
717 if(!std::isfinite(alo) || !std::isfinite(ahi)) {
718 return false;
719 }
720 if((alo < 0.0 && ahi > 0.0) || (alo > 0.0 && ahi < 0.0)) {
721 double fl = alo;
722 for(int it = 0; it < 56; ++it) {
723 const double mid = 0.5 * (lo + hi);
724 const double fm = eval_a_u(mid);
725 if(!std::isfinite(fm)) return false;
726 if((fl < 0.0 && fm <= 0.0) || (fl > 0.0 && fm >= 0.0)) {
727 lo = mid;
728 fl = fm;
729 } else {
730 hi = mid;
731 }
732 }
733 insert_sorted_unique(v_breaks, v_cnt, 8, 0.5 * (lo + hi));
734 }
735 }
736
737 // Step 3: verify every velocity-partition point AND every sign-change
738 // root of v(u) = 0 (all interior extrema of p(u) in [0, 1]).
739 for(int k = 1; k + 1 < v_cnt; ++k) {
740 if(!check_u(v_breaks[k])) return false;
741 }
742 for(int k = 0; k + 1 < v_cnt; ++k) {
743 double lo = v_breaks[k];
744 double hi = v_breaks[k + 1];
745 const double vlo = eval_v_u(lo);
746 const double vhi = eval_v_u(hi);
747 if(!std::isfinite(vlo) || !std::isfinite(vhi)) {
748 return false;
749 }
750 if((vlo < 0.0 && vhi > 0.0) || (vlo > 0.0 && vhi < 0.0)) {
751 double fl = vlo;
752 for(int it = 0; it < 56; ++it) {
753 const double mid = 0.5 * (lo + hi);
754 const double fm = eval_v_u(mid);
755 if(!std::isfinite(fm)) return false;
756 if((fl < 0.0 && fm <= 0.0) || (fl > 0.0 && fm >= 0.0)) {
757 lo = mid;
758 fl = fm;
759 } else {
760 hi = mid;
761 }
762 }
763 if(!check_u(0.5 * (lo + hi))) return false;
764 }
765 }
766 }
767 return true;
768}
769
770// Bidirectional node scan and per-line profile planning over every
771// piece from start_index onward inside an isolated staging buffer.
772inline bool AxisGroup::cart_window_rebuild_storage(CartStorage &storage,
773 std::size_t start_index,
774 double entry_velocity,
775 double entry_acceleration,
776 double acc,
777 double dec,
778 double jerk) const
779{
780 const std::size_t count = storage.size();
781 if(start_index >= count) {
782 return false;
783 }
784
785 // Forward pass: reachable node velocities.
786 double v = entry_velocity;
787 for(std::size_t i = start_index; i < count; ++i) {
788 CartPiece &piece = storage[i];
789 if(piece.corner) {
790 v = v < piece.cap ? v : piece.cap;
791 piece.v_in = v;
792 piece.v_out = v;
793 continue;
794 }
795 piece.v_in = v;
796 double reach = plan::jerk_reachable_speed(v, piece.length, acc, jerk);
797 reach = reach < piece.cap ? reach : piece.cap;
798 if(pose_frames_.cartesian_velocity_limit_ > 0.0 &&
799 reach > pose_frames_.cartesian_velocity_limit_) {
800 reach = pose_frames_.cartesian_velocity_limit_;
801 }
802 piece.v_out = reach;
803 v = reach;
804 }
805 // Backward pass: terminal rest.
806 v = 0.0;
807 for(std::size_t r = count; r > start_index; --r) {
808 CartPiece &piece = storage[r - 1];
809 if(piece.corner) {
810 v = v < piece.cap ? v : piece.cap;
811 piece.v_out = piece.v_out < v ? piece.v_out : v;
812 piece.v_in = piece.v_out;
813 v = piece.v_in;
814 continue;
815 }
816 piece.v_out = piece.v_out < v ? piece.v_out : v;
817 double reach =
818 plan::jerk_reachable_speed(piece.v_out, piece.length, dec, jerk);
819 piece.v_in = piece.v_in < reach ? piece.v_in : reach;
820 v = piece.v_in;
821 }
822 constexpr double MaxWindowCycles = 1.0e15;
823
824 for(std::size_t i = start_index; i < count; ++i) {
825 CartPiece &piece = storage[i];
826 if(piece.corner) {
827 if(piece.length <= 0.0) {
828 piece.duration = 0;
829 continue;
830 }
831 if(!std::isfinite(piece.v_in) || piece.v_in <= 0.0) {
832 return false;
833 }
834 const double raw_cycles = piece.length / piece.v_in;
835 if(!std::isfinite(raw_cycles) || raw_cycles < 0.0 ||
836 raw_cycles > MaxWindowCycles) {
837 return false;
838 }
839 const std::int64_t ceiled =
840 static_cast<std::int64_t>(std::ceil(raw_cycles));
841 piece.duration = ceiled < 1 ? 1 : ceiled;
842 continue;
843 }
844 const bool live_entry = i == start_index;
845 const double entry_v = live_entry ? entry_velocity : piece.v_in;
846 const double entry_a = live_entry ? entry_acceleration : 0.0;
847 double cap = piece.cap;
848 if(pose_frames_.cartesian_velocity_limit_ > 0.0 &&
849 cap > pose_frames_.cartesian_velocity_limit_) {
850 cap = pose_frames_.cartesian_velocity_limit_;
851 }
852 // Spec §2 #9 live-entry overspeed guard: when live entry speed
853 // (including mandatory coast from positive entry acceleration:
854 // v_entry + a_entry^2 / (2*jerk)) exceeds piece cap or exit target,
855 // require the final adopted profile (after any fixed-time refinement)
856 // to pass verify_profile_monotonic without reversing or overshooting
857 // piece.length. Non-overspeed pieces keep legacy KB-049/KB-073/KB-086
858 // admission behavior.
859 const double v_coast =
860 entry_a > 0.0 ? entry_v + (entry_a * entry_a) / (2.0 * jerk) : entry_v;
861 const bool entry_overspeed = live_entry &&
862 (v_coast > cap + 1e-12 ||
863 v_coast > piece.v_out + 1e-12);
864 if(live_entry && entry_v > cap) {
865 cap = entry_v;
866 }
867 const otg::Limits1D lim{cap, acc, dec, jerk};
868 const rt::Result<otg::Profile1D> profile = otg::plan_time_optimal(
869 {0.0, entry_v, entry_a}, {piece.length, piece.v_out, 0.0},
870 lim);
871 if(!profile) {
872 return false;
873 }
874 piece.profile = profile.value();
875 piece.duration = piece.profile.duration_cycles();
876 const bool initial_ok =
877 !entry_overspeed || verify_profile_monotonic(piece.profile, piece.length);
878 const double avg_v = entry_v > piece.v_out
879 ? entry_v : (piece.v_out > 1e-12 ? piece.v_out : entry_v);
880 if(avg_v > 1e-12) {
881 const double raw_ideal = std::ceil(piece.length / avg_v);
882 if(std::isfinite(raw_ideal) && raw_ideal >= 1.0 &&
883 raw_ideal <= MaxWindowCycles) {
884 const std::int64_t ideal = static_cast<std::int64_t>(raw_ideal);
885 if(piece.duration > ideal + 4 || !initial_ok) {
886 for(std::int64_t t = ideal; t <= ideal + 4; ++t) {
887 const rt::Result<otg::Profile1D> ft =
889 {0.0, entry_v, entry_a},
890 {piece.length, piece.v_out, 0.0}, lim, t);
891 if(ft && (!entry_overspeed ||
892 verify_profile_monotonic(ft.value(), piece.length))) {
893 piece.profile = ft.value();
894 piece.duration = ft.value().duration_cycles();
895 break;
896 }
897 }
898 }
899 }
900 }
901 if(entry_overspeed && !verify_profile_monotonic(piece.profile, piece.length)) {
902 return false;
903 }
904 }
905 return true;
906}
907
908inline geom::Vec3 AxisGroup::cart_piece_point(const CartPiece &piece, double s) const
909{
910 if(piece.corner) {
911 const double u = geom::quintic_parameter_at_length(piece.blend, s);
912 return geom::quintic_point(piece.blend, u);
913 }
914 const double clamped = s < 0.0 ? 0.0 : (s > piece.length ? piece.length : s);
915 return geom::Vec3{piece.start.x + piece.dir.x * clamped,
916 piece.start.y + piece.dir.y * clamped,
917 piece.start.z + piece.dir.z * clamped};
918}
919
920inline void AxisGroup::cart_piece_pose(const CartPiece &piece, double s,
921 geom::RigidTransform &tcp) const
922{
923 tcp.translation = cart_piece_point(piece, s);
924 const double clamped = s < 0.0 ? 0.0 : (s > piece.length ? piece.length : s);
925 const double frac = piece.length > 1e-15 ? clamped / piece.length : 1.0;
926 double rel[3][3] = {};
927 geom::rodrigues(piece.axis, piece.angle * frac, rel);
928 geom::rotation_multiply(piece.rotation_start, rel, tcp.rotation);
929}
930
931inline bool AxisGroup::cart_window_emit(geom::Vec3 point)
932{
933 double q[MaxAxes] = {};
934 rt::ErrorCode solved =
935 pose_frames_.kinematics_->inverse(point, cartesian_.window_joints_, axes_.size(), q);
936 if(solved == rt::ErrorCode::ok &&
937 pose_frames_.kinematics_->singularity_margin(q, axes_.size()) <
938 pose_frames_.kinematics_min_margin_) {
940 }
941 if(solved != rt::ErrorCode::ok) {
942 cartesian_.last_error_ = solved;
943 abort_motion();
944 set_group_error(solved);
945 return false;
946 }
947 for(std::size_t i = 0; i < axes_.size(); ++i) {
948 axes_[i]->set_synchronized_position(q[i]);
949 cartesian_.window_joints_[i] = q[i];
950 }
951 return true;
952}
953
954inline bool AxisGroup::cart_window_emit_pose(const geom::RigidTransform &tcp)
955{
956 double q[MaxAxes] = {};
957 const geom::RigidTransform flange =
958 geom::compose(tcp, pose_frames_.active_pose_tool_inverse_);
959 kin::Pose6 pose{};
960 pose.position[0] = flange.translation.x;
961 pose.position[1] = flange.translation.y;
962 pose.position[2] = flange.translation.z;
963 for(int r = 0; r < 3; ++r) {
964 for(int c = 0; c < 3; ++c) {
965 pose.rotation[r][c] = flange.rotation[r][c];
966 }
967 }
968 rt::ErrorCode solved = pose_frames_.pose_kinematics_->inverse(
969 pose, cartesian_.window_joints_, pose_frames_.pose_max_joint_step_, q);
970 if(solved == rt::ErrorCode::ok &&
971 pose_frames_.pose_kinematics_->singularity_margin(q) <
972 pose_frames_.pose_min_margin_) {
974 }
975 if(solved != rt::ErrorCode::ok) {
976 cartesian_.last_error_ = solved;
977 abort_motion();
978 set_group_error(solved);
979 return false;
980 }
981 for(std::size_t i = 0; i < axes_.size(); ++i) {
982 axes_[i]->set_synchronized_position(q[i]);
983 cartesian_.window_joints_[i] = q[i];
984 }
985 return true;
986}
987
988inline void AxisGroup::cart_window_cycle()
989{
990 if(cartesian_.window_stopping_) {
991 ++cartesian_.halt_tick_;
992 const otg::State1D state = otg::sample(
993 cartesian_.halt_profile_, rt::CycleTick::from_cycles(cartesian_.halt_tick_));
994 if(cartesian_.window_pose_) {
995 geom::RigidTransform tcp{};
996 cart_window_pose_at(cartesian_.halt_origin_ + state.position, tcp);
997 if(!cart_window_emit_pose(tcp)) {
998 return;
999 }
1000 } else {
1001 const geom::Vec3 point =
1002 cart_window_point_at(cartesian_.halt_origin_ + state.position);
1003 if(!cart_window_emit(point)) {
1004 return;
1005 }
1006 }
1007 if(cartesian_.halt_tick_ >= cartesian_.halt_duration_) {
1008 cart_window_reset();
1009 clear_axes_synchronized();
1010 status_ = GroupStatus::standby;
1011 start_next_queued();
1012 }
1013 return;
1014 }
1015
1016 ++cartesian_.piece_tick_;
1017 CartPiece &piece = cartesian_.window_[cartesian_.piece_index_];
1018 double s = 0.0;
1019 if(piece.corner) {
1020 s = piece.v_in * static_cast<double>(cartesian_.piece_tick_);
1021 s = s > piece.length ? piece.length : s;
1022 } else {
1023 const otg::State1D state = otg::sample(
1024 piece.profile, rt::CycleTick::from_cycles(cartesian_.piece_tick_));
1025 s = state.position;
1026 }
1027 if(cartesian_.window_pose_) {
1028 geom::RigidTransform tcp{};
1029 cart_piece_pose(piece, s, tcp);
1030 if(!cart_window_emit_pose(tcp)) {
1031 return;
1032 }
1033 } else {
1034 if(!cart_window_emit(cart_piece_point(piece, s))) {
1035 return;
1036 }
1037 }
1038 if(cartesian_.piece_tick_ >= piece.duration) {
1039 if(cartesian_.piece_index_ + 1 < cartesian_.window_.size()) {
1040 ++cartesian_.piece_index_;
1041 cartesian_.piece_tick_ = 0;
1042 // Entry state for the freshly entered piece.
1043 const CartPiece &next = cartesian_.window_[cartesian_.piece_index_];
1044 cartesian_.window_entry_velocity_ = next.v_in;
1045 cartesian_.window_entry_acceleration_ = 0.0;
1046 } else {
1047 cart_window_reset();
1048 clear_axes_synchronized();
1049 status_ = GroupStatus::standby;
1050 start_next_queued();
1051 }
1052 }
1053}
1054
1055// Composite arc-length lookup from the live point onward (halt walker).
1056inline geom::Vec3 AxisGroup::cart_window_point_at(double composite) const
1057{
1058 double remaining = composite;
1059 for(std::size_t i = cartesian_.piece_index_; i < cartesian_.window_.size(); ++i) {
1060 const CartPiece &piece = cartesian_.window_[i];
1061 double offset = 0.0;
1062 if(i == cartesian_.piece_index_) {
1063 offset = cartesian_.halt_piece_offset_;
1064 }
1065 const double available = piece.length - offset;
1066 if(remaining <= available) {
1067 return cart_piece_point(piece, offset + remaining);
1068 }
1069 remaining -= available;
1070 }
1071 const CartPiece &last = cartesian_.window_[cartesian_.window_.size() - 1];
1072 return cart_piece_point(last, last.length);
1073}
1074
1075inline void AxisGroup::cart_window_pose_at(double composite,
1076 geom::RigidTransform &tcp) const
1077{
1078 double remaining = composite;
1079 for(std::size_t i = cartesian_.piece_index_; i < cartesian_.window_.size(); ++i) {
1080 const CartPiece &piece = cartesian_.window_[i];
1081 double offset = 0.0;
1082 if(i == cartesian_.piece_index_) {
1083 offset = cartesian_.halt_piece_offset_;
1084 }
1085 const double available = piece.length - offset;
1086 if(remaining <= available) {
1087 cart_piece_pose(piece, offset + remaining, tcp);
1088 return;
1089 }
1090 remaining -= available;
1091 }
1092 const CartPiece &last = cartesian_.window_[cartesian_.window_.size() - 1];
1093 cart_piece_pose(last, last.length, tcp);
1094}
1095
1096inline rt::ErrorCode AxisGroup::cart_window_stop(double deceleration, double jerk)
1097{
1098 if(!std::isfinite(deceleration) || deceleration <= 0.0 ||
1099 !std::isfinite(jerk) || jerk <= 0.0) {
1101 }
1102 CartPiece &piece = cartesian_.window_[cartesian_.piece_index_];
1103 otg::State1D state{};
1104 if(piece.corner) {
1105 double s = piece.v_in * static_cast<double>(cartesian_.piece_tick_);
1106 s = s > piece.length ? piece.length : s;
1107 state = {s, piece.v_in, 0.0};
1108 } else {
1109 state = otg::sample(piece.profile,
1110 rt::CycleTick::from_cycles(cartesian_.piece_tick_));
1111 }
1112 double remaining = piece.length - state.position;
1113 for(std::size_t i = cartesian_.piece_index_ + 1; i < cartesian_.window_.size(); ++i) {
1114 remaining += cartesian_.window_[i].length;
1115 }
1116 const otg::Limits1D halt_limits{state.velocity > 1e-12 ? state.velocity
1117 : 1e-12,
1118 deceleration, deceleration, jerk};
1119 double target = state.velocity * state.velocity / (2.0 * deceleration) +
1120 state.velocity * (deceleration / jerk);
1121 if(target > remaining) {
1122 target = remaining;
1123 }
1124 rt::Result<otg::Profile1D> halt =
1126 for(int attempt = 0; attempt < 8; ++attempt) {
1127 halt = otg::plan_time_optimal({0.0, state.velocity, state.acceleration},
1128 {target, 0.0, 0.0}, halt_limits);
1129 if(halt || target >= remaining) {
1130 break;
1131 }
1132 target = target * 1.5 < remaining ? target * 1.5 : remaining;
1133 }
1134 if(!halt) {
1135 if(std::fabs(state.velocity) <= 1e-12 &&
1136 std::fabs(state.acceleration) <= 1e-12) {
1137 cart_window_reset();
1138 clear_axes_synchronized();
1139 queue_.clear();
1140 status_ = GroupStatus::standby;
1141 return rt::ErrorCode::ok;
1142 }
1143 // Cannot form a feasible braking trajectory within the remaining path
1144 // under the requested deceleration/jerk: leave active motion untouched.
1146 }
1147 cartesian_.halt_profile_ = halt.value();
1148 cartesian_.halt_duration_ = cartesian_.halt_profile_.duration_cycles();
1149 cartesian_.halt_tick_ = 0;
1150 cartesian_.halt_origin_ = 0.0;
1151 cartesian_.halt_piece_offset_ = state.position;
1152 cartesian_.window_stopping_ = true;
1153 queue_.clear();
1154 status_ = GroupStatus::stopping;
1155 return rt::ErrorCode::ok;
1156}
1157
1158inline void AxisGroup::cart_window_reset()
1159{
1160 cartesian_.window_.clear();
1161 cartesian_.staging_window_.clear();
1162 cartesian_.window_active_ = false;
1163 cartesian_.window_stopping_ = false;
1164 cartesian_.window_pose_ = false;
1165 cartesian_.piece_index_ = 0;
1166 cartesian_.piece_tick_ = 0;
1167 cartesian_.halt_tick_ = 0;
1168 cartesian_.halt_duration_ = 0;
1169 cartesian_.halt_origin_ = 0.0;
1170 cartesian_.halt_piece_offset_ = 0.0;
1171}
1172
1173// Cartesian v2-C (approved addendum): fuse the active Cartesian line,
1174// a Cartesian-space quintic corner inside the tolerance band, and the
1175// successor line into one chain driven by one profile planned from the
1176// live path state. The chain velocity carries the corner curvature cap;
1177// orientation rides a single geodesic over the whole chain (declared).
1178// Reflex corners, too-late submissions, and chains that do not beat the
1179// full-stop baseline degrade to BUFFERED and are reported.
1180inline rt::Result<std::uint32_t> AxisGroup::submit_cartesian_blend(GroupCommand command)
1181{
1182 if(command.command_id == 0) {
1183 command.command_id = next_command_id_++;
1184 }
1185 if(command.coord_system != CoordSystem::mcs &&
1186 command.coord_system != CoordSystem::pcs) {
1188 }
1189 if(command.relative ||
1190 (pose_frames_.kinematics_ == nullptr && pose_frames_.pose_kinematics_ == nullptr)) {
1192 }
1193 // Mixed-mode blending, arc/rotation-driven actives, committed
1194 // chains, windows, and non-empty queues are all outside the v1
1195 // fusion shape.
1196 if(!active_ || status_ != GroupStatus::moving ||
1197 active_kind_ != GroupPathKind::cartesian_linear ||
1198 active_command_.dynamic_pcs ||
1199 cartesian_.takeover_active_ ||
1200 cartesian_.active_segment_.arc_path || cartesian_.active_segment_.angle_driven ||
1201 cartesian_.active_segment_.chain || joint_window_.active_ || !queue_.empty() ||
1202 active_path_length_ <= 0.0) {
1204 }
1205
1206 // Successor target in the Cartesian (TCP) domain.
1207 geom::Vec3 target_point = cartesian_part(command.target);
1208 geom::RigidTransform target_pose{};
1209 if(pose_frames_.pose_kinematics_ != nullptr) {
1210 target_pose = geom::make_rpy_transform(
1211 command.target.value[0], command.target.value[1],
1212 command.target.value[2], command.target.value[3],
1213 command.target.value[4], command.target.value[5]);
1214 if(command.coord_system == CoordSystem::pcs) {
1215 target_pose = geom::compose(pose_frames_.workpiece_frame_, target_pose);
1216 }
1217 target_point = target_pose.translation;
1218 } else {
1219 if(command.coord_system == CoordSystem::pcs) {
1220 target_point = geom::transform_point(pose_frames_.workpiece_frame_, target_point);
1221 }
1222 target_point = target_point - pose_frames_.tool_offset_;
1223 }
1224
1225 // Live path state and geometry.
1226 const otg::State1D live =
1227 otg::sample(active_profile_, rt::CycleTick::from_cycles(active_tick_));
1228 const double s_live = live.position < 0.0
1229 ? 0.0
1230 : (live.position > active_path_length_
1231 ? active_path_length_
1232 : live.position);
1233 const double remaining = active_path_length_ - s_live;
1234 const geom::Vec3 live_point =
1235 cartesian_point_at(cartesian_.active_segment_, s_live / active_path_length_);
1236 const geom::Vec3 corner_point = geom::Vec3{
1237 cartesian_.active_segment_.start.x + cartesian_.active_segment_.delta.x,
1238 cartesian_.active_segment_.start.y + cartesian_.active_segment_.delta.y,
1239 cartesian_.active_segment_.start.z + cartesian_.active_segment_.delta.z};
1240 const double active_len = geom::norm(cartesian_.active_segment_.delta);
1241 if(active_len <= 1e-12) {
1243 }
1244 const geom::Vec3 t0{cartesian_.active_segment_.delta.x / active_len,
1245 cartesian_.active_segment_.delta.y / active_len,
1246 cartesian_.active_segment_.delta.z / active_len};
1247 const geom::Vec3 out_vec = target_point - corner_point;
1248 const double len_b = geom::norm(out_vec);
1249 const double dot = len_b > 1e-12
1250 ? (t0.x * out_vec.x + t0.y * out_vec.y +
1251 t0.z * out_vec.z) /
1252 len_b
1253 : -1.0;
1254
1255 bool degrade = false;
1256 double trim = 0.0;
1257 bool passthrough = false;
1258 if(len_b <= 1e-12 || dot <= -0.999) {
1259 degrade = true;
1260 } else if(dot >= 1.0 - 1e-9) {
1261 passthrough = true;
1262 } else {
1263 const geom::Vec3 t1{out_vec.x / len_b, out_vec.y / len_b,
1264 out_vec.z / len_b};
1265 const double turn = geom::norm(t1 - t0);
1266 trim = command.transition_parameter * 96.0 / (23.0 * turn);
1267 const double room = remaining < len_b ? remaining : len_b;
1268 if(trim > 0.5 * room) {
1269 trim = 0.5 * room;
1270 }
1271 if(trim <= 1e-9 || remaining <= trim) {
1272 degrade = true;
1273 }
1274 }
1275
1276 CartesianSegment segment{};
1277 rt::Result<otg::Profile1D> chain_profile =
1279 if(!degrade) {
1280 const geom::Vec3 t1{out_vec.x / len_b, out_vec.y / len_b,
1281 out_vec.z / len_b};
1282 segment.pose = cartesian_.active_segment_.pose;
1283 segment.chain = true;
1284 segment.start = live_point;
1285 segment.dir1 = t0;
1286 if(passthrough) {
1287 segment.line1 = remaining;
1288 segment.exit_point = corner_point;
1289 } else {
1290 const geom::Vec3 entry{corner_point.x - t0.x * trim,
1291 corner_point.y - t0.y * trim,
1292 corner_point.z - t0.z * trim};
1293 const geom::Vec3 exit{corner_point.x + t1.x * trim,
1294 corner_point.y + t1.y * trim,
1295 corner_point.z + t1.z * trim};
1296 const rt::Result<geom::QuinticBlendSegment> blend =
1297 geom::make_quintic_blend(entry, corner_point, exit,
1298 command.transition_parameter);
1299 if(!blend) {
1300 degrade = true;
1301 } else {
1302 segment.corner = blend.value();
1303 segment.line1 = remaining - trim;
1304 segment.exit_point = exit;
1305 }
1306 }
1307 segment.dir2 = t1;
1308 segment.line2 = len_b - trim;
1309 segment.delta = target_point - live_point;
1310 segment.length = segment.line1 + segment.corner.length + segment.line2;
1311
1312 if(!degrade && segment.pose) {
1313 const geom::RigidTransform live_tcp = pose_start_tcp(cartesian_.joints_);
1314 if(command.orientation_mode == OrientationMode::constant) {
1315 for(int i = 0; i < 3; ++i) {
1316 for(int j = 0; j < 3; ++j) {
1317 target_pose.rotation[i][j] = live_tcp.rotation[i][j];
1318 }
1319 }
1320 }
1321 for(int i = 0; i < 3; ++i) {
1322 for(int j = 0; j < 3; ++j) {
1323 segment.rotation_start[i][j] = live_tcp.rotation[i][j];
1324 }
1325 }
1326 geom::relative_axis_angle(live_tcp.rotation, target_pose.rotation,
1327 segment.axis, segment.angle);
1328 if(segment.angle >= 3.14159265358979323846 - 1e-6) {
1331 }
1332 }
1333 }
1334
1335 if(!degrade) {
1336 // Chain envelope: both commands and the corner curvature cap.
1337 GroupCommand fused = command;
1338 fused.velocity = fused.velocity < active_command_.velocity
1339 ? fused.velocity
1340 : active_command_.velocity;
1341 fused.acceleration = fused.acceleration < active_command_.acceleration
1342 ? fused.acceleration
1343 : active_command_.acceleration;
1344 fused.deceleration = fused.deceleration < active_command_.deceleration
1345 ? fused.deceleration
1346 : active_command_.deceleration;
1347 fused.jerk =
1348 fused.jerk < active_command_.jerk ? fused.jerk : active_command_.jerk;
1349 if(command.transition_velocity > 0.0 &&
1350 command.transition_velocity < fused.velocity) {
1351 // This planner has one profile for the fused chain, so the
1352 // explicit junction cap conservatively bounds that profile.
1353 fused.velocity = command.transition_velocity;
1354 }
1355 if(segment.corner.max_curvature > 1e-12) {
1356 const double axis_accel =
1357 fused.acceleration < fused.deceleration ? fused.acceleration
1358 : fused.deceleration;
1359 const double cap = std::sqrt(axis_accel / segment.corner.max_curvature);
1360 if(cap < fused.velocity) {
1361 fused.velocity = cap;
1362 }
1363 }
1364 double chain_seed[MaxAxes] = {};
1365 for(std::size_t i = 0; i < axes_.size(); ++i) {
1366 chain_seed[i] = cartesian_.joints_[i];
1367 }
1368 const rt::ErrorCode validated =
1369 prevalidate_cartesian(fused, segment, chain_seed);
1370 if(validated != rt::ErrorCode::ok) {
1371 return rt::Result<std::uint32_t>::failure(validated);
1372 }
1373 chain_profile = otg::plan_time_optimal(
1374 {0.0, live.velocity, live.acceleration},
1375 {fused.cart.length, 0.0, 0.0},
1376 {fused.velocity, fused.acceleration, fused.deceleration, fused.jerk});
1377 if(!chain_profile) {
1378 degrade = true;
1379 } else {
1380 // Constructive gate: the fused chain must beat the full-stop
1381 // baseline (finish the active segment, then run the successor
1382 // from rest).
1383 const rt::Result<otg::Profile1D> tail = otg::plan_time_optimal(
1384 {0.0, 0.0, 0.0}, {len_b, 0.0, 0.0},
1385 {command.velocity, command.acceleration, command.deceleration,
1386 command.jerk});
1387 if(tail) {
1388 const std::int64_t baseline = (active_duration_ - active_tick_) +
1389 tail.value().duration_cycles();
1390 if(chain_profile.value().duration_cycles() >= baseline) {
1391 degrade = true;
1392 }
1393 } else {
1394 degrade = true;
1395 }
1396 }
1397 if(!degrade) {
1398 active_command_ = fused;
1399 cartesian_.active_segment_ = fused.cart;
1400 active_kind_ = GroupPathKind::cartesian_linear;
1401 active_arc_ = geom::ArcSegment{};
1402 active_path_length_ = fused.cart.length;
1403 active_profile_ = chain_profile.value();
1404 active_tick_ = 0;
1405 active_duration_ = active_profile_.duration_cycles();
1406 for(std::size_t i = 0; i < axes_.size(); ++i) {
1407 active_start_[i] = axes_[i]->snapshot().command_position;
1408 active_finish_[i] = fused.target.value[i];
1409 }
1411 }
1412 }
1413
1414 // Reported degradation to a plain buffered Cartesian segment. Record
1415 // degradation only after both preparation and queue commit succeed.
1416 command.buffer_mode = BufferMode::buffered;
1417 command.transition_mode = TransitionMode::none;
1418 command.transition_velocity = 0.0;
1419 command.transition_parameter = 0.0;
1420 const rt::ErrorCode prepared = prepare_cartesian_linear(command);
1421 if(prepared != rt::ErrorCode::ok) {
1422 return rt::Result<std::uint32_t>::failure(prepared);
1423 }
1424 const rt::ErrorCode queued = queue_.push_back(command);
1425 if(queued != rt::ErrorCode::ok) {
1427 }
1428 last_blend_degraded_id_ = command.command_id;
1430}
1431
1432inline rt::ErrorCode AxisGroup::prepare_cartesian_linear(GroupCommand &command)
1433{
1434 const rt::ErrorCode guarded = cartesian_guards(command);
1435 if(guarded != rt::ErrorCode::ok) {
1436 return guarded;
1437 }
1438 double chain[MaxAxes] = {};
1439 segment_start_joints(command, chain);
1440
1441 CartesianSegment segment{};
1442 if(pose_frames_.pose_kinematics_ != nullptr) {
1443 segment.pose = true;
1444 const geom::RigidTransform requested = geom::make_rpy_transform(
1445 command.target.value[0], command.target.value[1],
1446 command.target.value[2], command.target.value[3],
1447 command.target.value[4], command.target.value[5]);
1448 const geom::RigidTransform start = pose_start_tcp(chain);
1449 geom::RigidTransform target = requested;
1450 if(command.relative) {
1451 geom::Vec3 displacement = requested.translation;
1452 if(command.coord_system == CoordSystem::pcs) {
1453 displacement = geom::transform_rotate(pose_frames_.workpiece_frame_, displacement);
1454 }
1455 target.translation = start.translation + displacement;
1456 if(command.orientation_mode == OrientationMode::constant) {
1457 for(int i = 0; i < 3; ++i) {
1458 for(int j = 0; j < 3; ++j) {
1459 target.rotation[i][j] = start.rotation[i][j];
1460 }
1461 }
1462 } else {
1463 geom::rotation_multiply(start.rotation, requested.rotation,
1464 target.rotation);
1465 }
1466 } else {
1467 if(command.coord_system == CoordSystem::pcs) {
1468 target = geom::compose(pose_frames_.workpiece_frame_, target);
1469 }
1470 if(command.orientation_mode == OrientationMode::constant) {
1471 for(int i = 0; i < 3; ++i) {
1472 for(int j = 0; j < 3; ++j) {
1473 target.rotation[i][j] = start.rotation[i][j];
1474 }
1475 }
1476 }
1477 }
1478 segment.start = start.translation;
1479 segment.delta = target.translation - start.translation;
1480 for(int i = 0; i < 3; ++i) {
1481 for(int j = 0; j < 3; ++j) {
1482 segment.rotation_start[i][j] = start.rotation[i][j];
1483 }
1484 }
1485 geom::relative_axis_angle(start.rotation, target.rotation, segment.axis,
1486 segment.angle);
1487 if(segment.angle >= 3.14159265358979323846 - 1e-6) {
1489 }
1490 segment.length = geom::norm(segment.delta);
1491 if(segment.length < 1e-12 && segment.angle > 0.0) {
1492 segment.angle_driven = true;
1493 segment.length = segment.angle;
1494 }
1495 } else {
1496 geom::Vec3 point = cartesian_part(command.target);
1497 geom::Vec3 start{};
1498 const rt::ErrorCode forwarded =
1499 pose_frames_.kinematics_->forward(chain, axes_.size(), start);
1500 if(forwarded != rt::ErrorCode::ok) {
1501 return forwarded;
1502 }
1503 if(command.relative) {
1504 if(command.coord_system == CoordSystem::pcs) {
1505 point = geom::transform_rotate(pose_frames_.workpiece_frame_, point);
1506 }
1507 point = start + point;
1508 } else {
1509 if(command.coord_system == CoordSystem::pcs) {
1510 point = geom::transform_point(pose_frames_.workpiece_frame_, point);
1511 }
1512 point = point - pose_frames_.tool_offset_;
1513 }
1514 segment.start = start;
1515 segment.delta = point - start;
1516 segment.length = geom::norm(segment.delta);
1517 }
1518 command.relative = false;
1519 return prevalidate_cartesian(command, segment, chain);
1520}
1521
1522// Cartesian v2-B / Y5: BORDER / CENTER / RADIUS arcs in either xy_helical
1523// (KB-047 default: XY circle + linear Z) or spatial_3d (true arbitrary 3D
1524// plane oriented by circ_plane_normal). Pose groups ride the start-to-target
1525// geodesic along the arc fraction; aux orientation slots are ignored.
1526inline rt::ErrorCode AxisGroup::prepare_cartesian_circular(GroupCommand &command)
1527{
1528 const rt::ErrorCode guarded = cartesian_guards(command);
1529 if(guarded != rt::ErrorCode::ok) {
1530 return guarded;
1531 }
1532 const bool spatial = command.circ_plane_mode == CircPlaneMode::spatial_3d;
1533 if(spatial && pose_frames_.pose_kinematics_ == nullptr &&
1534 (pose_frames_.kinematics_ == nullptr ||
1535 pose_frames_.kinematics_->cartesian_count() != 3)) {
1537 }
1538 const bool pcs = command.coord_system == CoordSystem::pcs;
1539 double chain[MaxAxes] = {};
1540 segment_start_joints(command, chain);
1541
1542 CartesianSegment segment{};
1543 geom::Vec3 start_point{};
1544 geom::Vec3 aux_point =
1545 command.circ_mode == CircMode::radius ? geom::Vec3{} : cartesian_part(command.aux);
1546 geom::Vec3 target_point = cartesian_part(command.target);
1547 if(pose_frames_.pose_kinematics_ != nullptr) {
1548 segment.pose = true;
1549 const geom::RigidTransform requested = geom::make_rpy_transform(
1550 command.target.value[0], command.target.value[1],
1551 command.target.value[2], command.target.value[3],
1552 command.target.value[4], command.target.value[5]);
1553 const geom::RigidTransform start = pose_start_tcp(chain);
1554 start_point = start.translation;
1555 geom::RigidTransform target = requested;
1556 if(command.relative) {
1557 geom::Vec3 target_delta = requested.translation;
1558 if(pcs) {
1559 target_delta = geom::transform_rotate(pose_frames_.workpiece_frame_, target_delta);
1560 if(command.circ_mode != CircMode::radius) {
1561 aux_point = geom::transform_rotate(pose_frames_.workpiece_frame_, aux_point);
1562 }
1563 }
1564 target.translation = start.translation + target_delta;
1565 if(command.circ_mode != CircMode::radius) {
1566 aux_point = start.translation + aux_point;
1567 }
1568 if(command.orientation_mode == OrientationMode::constant) {
1569 for(int i = 0; i < 3; ++i) {
1570 for(int j = 0; j < 3; ++j) {
1571 target.rotation[i][j] = start.rotation[i][j];
1572 }
1573 }
1574 } else {
1575 geom::rotation_multiply(start.rotation, requested.rotation,
1576 target.rotation);
1577 }
1578 } else {
1579 if(pcs) {
1580 target = geom::compose(pose_frames_.workpiece_frame_, target);
1581 if(command.circ_mode != CircMode::radius) {
1582 aux_point = geom::transform_point(pose_frames_.workpiece_frame_, aux_point);
1583 }
1584 }
1585 if(command.orientation_mode == OrientationMode::constant) {
1586 for(int i = 0; i < 3; ++i) {
1587 for(int j = 0; j < 3; ++j) {
1588 target.rotation[i][j] = start.rotation[i][j];
1589 }
1590 }
1591 }
1592 }
1593 target_point = target.translation;
1594 for(int i = 0; i < 3; ++i) {
1595 for(int j = 0; j < 3; ++j) {
1596 segment.rotation_start[i][j] = start.rotation[i][j];
1597 }
1598 }
1599 geom::relative_axis_angle(start.rotation, target.rotation, segment.axis,
1600 segment.angle);
1601 if(segment.angle >= 3.14159265358979323846 - 1e-6) {
1603 }
1604 } else {
1605 geom::Vec3 start{};
1606 const rt::ErrorCode forwarded =
1607 pose_frames_.kinematics_->forward(chain, axes_.size(), start);
1608 if(forwarded != rt::ErrorCode::ok) {
1609 return forwarded;
1610 }
1611 start_point = start;
1612 if(command.relative) {
1613 if(pcs) {
1614 if(command.circ_mode != CircMode::radius) {
1615 aux_point = geom::transform_rotate(pose_frames_.workpiece_frame_, aux_point);
1616 }
1617 target_point = geom::transform_rotate(pose_frames_.workpiece_frame_, target_point);
1618 }
1619 if(command.circ_mode != CircMode::radius) {
1620 aux_point = start + aux_point;
1621 }
1622 target_point = start + target_point;
1623 } else {
1624 if(pcs) {
1625 if(command.circ_mode != CircMode::radius) {
1626 aux_point = geom::transform_point(pose_frames_.workpiece_frame_, aux_point);
1627 }
1628 target_point = geom::transform_point(pose_frames_.workpiece_frame_, target_point);
1629 }
1630 if(command.circ_mode != CircMode::radius) {
1631 aux_point = aux_point - pose_frames_.tool_offset_;
1632 }
1633 target_point = target_point - pose_frames_.tool_offset_;
1634 }
1635 }
1636
1637 const bool ccw = command.path_choice == CircPathChoice::counter_clockwise;
1638 rt::Result<geom::ArcSegment> arc =
1640 if(spatial) {
1641 // Free-vector transform: rotate plane normal by PCS only, never translate.
1642 const geom::Vec3 normal_mcs =
1643 pcs ? geom::transform_rotate(pose_frames_.workpiece_frame_,
1644 command.circ_plane_normal)
1645 : command.circ_plane_normal;
1646 if(command.circ_mode == CircMode::border) {
1648 target_point, normal_mcs, ccw);
1649 } else if(command.circ_mode == CircMode::center) {
1651 target_point, normal_mcs, ccw);
1652 } else {
1654 command.circ_radius, normal_mcs, ccw);
1655 }
1656 if(!arc) {
1657 return arc.error();
1658 }
1659 } else {
1660 const geom::Vec3 plane_start{start_point.x, start_point.y, 0.0};
1661 const geom::Vec3 plane_finish{target_point.x, target_point.y, 0.0};
1662 if(command.circ_mode == CircMode::border) {
1663 const geom::Vec3 plane_aux{aux_point.x, aux_point.y, 0.0};
1664 constexpr double PointTolerance = 1e-12;
1665 if(geom::norm(plane_aux - plane_start) <= PointTolerance ||
1666 geom::norm(plane_finish - plane_aux) <= PointTolerance ||
1667 geom::norm(plane_finish - plane_start) <= PointTolerance) {
1669 }
1670 arc = geom::make_arc(plane_start, plane_aux, plane_finish);
1671 if(!arc) {
1673 }
1674 if(arc.value().radius > geom::norm(plane_finish - plane_start) * 1e6) {
1676 }
1677 const CircPathChoice derived = arc.value().sweep >= 0.0
1680 if(derived != command.path_choice) {
1682 }
1683 if(command.tolerance > 0.0) {
1684 const double via_sweep = geom::normalize_sweep(
1685 geom::angle_of(plane_aux, arc.value().center) -
1686 arc.value().start_angle,
1687 arc.value().sweep);
1688 const double fraction = via_sweep / arc.value().sweep;
1689 const double expected_z = start_point.z +
1690 (target_point.z - start_point.z) * fraction;
1691 if(std::fabs(aux_point.z - expected_z) > command.tolerance) {
1693 }
1694 }
1695 } else if(command.circ_mode == CircMode::center) {
1696 const geom::Vec3 plane_center{aux_point.x, aux_point.y, 0.0};
1697 arc = geom::make_arc_center_xy(plane_start, plane_center, plane_finish, ccw);
1698 if(!arc) {
1699 return arc.error();
1700 }
1701 } else {
1702 arc = geom::make_arc_radius_xy(plane_start, plane_finish,
1703 command.circ_radius, ccw);
1704 if(!arc) {
1705 return arc.error();
1706 }
1707 }
1708 }
1709
1710 segment.arc_path = true;
1711 segment.arc = arc.value();
1712 segment.start = start_point;
1713 segment.delta = target_point - start_point;
1714 segment.length = arc.value().length;
1715 command.relative = false;
1716 return prevalidate_cartesian(command, segment, chain);
1717}
1718
1719inline rt::ErrorCode AxisGroup::cartesian_guards(const GroupCommand &command) const
1720{
1721 if(command.coord_system != CoordSystem::mcs &&
1722 command.coord_system != CoordSystem::pcs) {
1724 }
1725 if((command.relative &&
1726 command.orientation_mode == OrientationMode::joint_space) ||
1727 command.buffer_mode == BufferMode::blending_low ||
1728 command.buffer_mode == BufferMode::blending_high ||
1729 command.transition_mode != TransitionMode::none ||
1730 command.transition_parameter != 0.0) {
1732 }
1733 if(pose_frames_.kinematics_ == nullptr && pose_frames_.pose_kinematics_ == nullptr) {
1735 }
1736 return rt::ErrorCode::ok;
1737}
1738
1739inline void AxisGroup::segment_start_joints(const GroupCommand &command, double *chain) const
1740{
1741 const bool aborting = command.buffer_mode == BufferMode::aborting;
1742 for(std::size_t i = 0; i < axes_.size(); ++i) {
1743 chain[i] = aborting ? axes_[i]->snapshot().command_position
1744 : queued_finish(i);
1745 }
1746}
1747
1748inline geom::RigidTransform AxisGroup::pose_start_tcp(const double *chain) const
1749{
1750 kin::Pose6 flange{};
1751 pose_frames_.pose_kinematics_->forward(chain, flange);
1752 geom::RigidTransform start{};
1753 start.translation = geom::Vec3{flange.position[0], flange.position[1],
1754 flange.position[2]};
1755 for(int i = 0; i < 3; ++i) {
1756 for(int j = 0; j < 3; ++j) {
1757 start.rotation[i][j] = flange.rotation[i][j];
1758 }
1759 }
1760 return geom::compose(start, pose_frames_.pose_tool_);
1761}
1762
1763// Shared 33-sample pre-validation and command commit for every
1764// Cartesian segment shape.
1765inline rt::ErrorCode AxisGroup::prevalidate_cartesian(GroupCommand &command,
1766 CartesianSegment &segment,
1767 double *chain)
1768{
1769 constexpr int Samples = 32;
1770 double q[MaxAxes] = {};
1771 double worst_step = 0.0;
1772 segment.interior_soft_limits_ok = true;
1773 cartesian_.pending_takeover_grid_valid_ = false;
1774 const bool enforce_companion_soft_limits =
1775 pose_frames_.translation_path_differential_ != nullptr &&
1776 !segment.pose && !segment.arc_path && !segment.chain;
1777 const bool record_takeover_grid =
1778 command.buffer_mode == BufferMode::aborting &&
1779 !segment.pose && !segment.arc_path && !segment.chain &&
1780 axes_.size() >= 2 && axes_.size() <= 3;
1781
1782 for(int k = 0; k <= Samples; ++k) {
1783 const double fraction =
1784 static_cast<double>(k) / static_cast<double>(Samples);
1786 if(segment.pose) {
1787 geom::RigidTransform tcp{};
1788 cartesian_pose_at(segment, fraction, tcp);
1789 const geom::RigidTransform flange_target =
1790 geom::compose(tcp, pose_frames_.pose_tool_inverse_);
1791 kin::Pose6 pose{};
1792 pose.position[0] = flange_target.translation.x;
1793 pose.position[1] = flange_target.translation.y;
1794 pose.position[2] = flange_target.translation.z;
1795 for(int i = 0; i < 3; ++i) {
1796 for(int j = 0; j < 3; ++j) {
1797 pose.rotation[i][j] = flange_target.rotation[i][j];
1798 }
1799 }
1800 solved = pose_frames_.pose_kinematics_->inverse(pose, chain,
1801 pose_frames_.pose_max_joint_step_, q);
1802 if(solved == rt::ErrorCode::ok &&
1803 pose_frames_.pose_kinematics_->singularity_margin(q) < pose_frames_.pose_min_margin_) {
1805 }
1806 } else {
1807 const geom::Vec3 sample = cartesian_point_at(segment, fraction);
1808 solved = pose_frames_.kinematics_->inverse(sample, chain, axes_.size(), q);
1809 if(solved == rt::ErrorCode::ok &&
1810 pose_frames_.kinematics_->singularity_margin(q, axes_.size()) <
1811 pose_frames_.kinematics_min_margin_) {
1813 }
1814 }
1815 if(solved != rt::ErrorCode::ok) {
1816 return solved;
1817 }
1818 if(k > 0) {
1819 for(std::size_t i = 0; i < axes_.size(); ++i) {
1820 const double step = std::fabs(q[i] - chain[i]);
1821 if(step > worst_step) {
1822 worst_step = step;
1823 }
1824 }
1825 }
1826 for(std::size_t i = 0; i < axes_.size(); ++i) {
1828 axes_[i]->motion_limits(), q[i])) {
1829 segment.interior_soft_limits_ok = false;
1830 if(enforce_companion_soft_limits) {
1832 }
1833 }
1834 chain[i] = q[i];
1835 if(record_takeover_grid) {
1836 cartesian_.pending_takeover_grid_[static_cast<std::size_t>(k)][i] = q[i];
1837 }
1838 }
1839 }
1840 // Velocity budget (decision #6): the step gate doubles as the joint
1841 // velocity budget with a safety factor of two (pose pipeline).
1842 if(segment.pose && worst_step > 0.0 && segment.length > 0.0) {
1843 const double per_unit =
1844 worst_step / (segment.length / static_cast<double>(Samples));
1845 const double allowed = 0.5 * pose_frames_.pose_max_joint_step_ / per_unit;
1846 if(allowed < command.velocity) {
1847 command.velocity = allowed;
1848 }
1849 }
1850 for(std::size_t i = 0; i < axes_.size(); ++i) {
1851 command.target.value[i] = q[i];
1852 }
1853 command.target.size = axes_.size();
1854 if(pose_frames_.cartesian_velocity_limit_ > 0.0 &&
1855 pose_frames_.cartesian_velocity_limit_ < command.velocity) {
1856 command.velocity = pose_frames_.cartesian_velocity_limit_;
1857 }
1858 command.coord_system = CoordSystem::acs;
1860 command.cart = segment;
1861 const rt::ErrorCode pf = preflight_member_targets(command.target);
1862 if(pf == rt::ErrorCode::ok && record_takeover_grid) {
1863 cartesian_.pending_takeover_grid_valid_ = true;
1864 }
1865 return pf;
1866}
1867
1868inline geom::Vec3 AxisGroup::cartesian_point_at(const CartesianSegment &segment,
1869 double fraction) const
1870{
1871 if(segment.chain) {
1872 const double s = fraction * segment.length;
1873 if(s <= segment.line1) {
1874 return geom::Vec3{segment.start.x + segment.dir1.x * s,
1875 segment.start.y + segment.dir1.y * s,
1876 segment.start.z + segment.dir1.z * s};
1877 }
1878 const double in_corner = s - segment.line1;
1879 if(in_corner <= segment.corner.length) {
1880 const double u =
1881 geom::quintic_parameter_at_length(segment.corner, in_corner);
1882 return geom::quintic_point(segment.corner, u);
1883 }
1884 const double tail = s - segment.line1 - segment.corner.length;
1885 return geom::Vec3{segment.exit_point.x + segment.dir2.x * tail,
1886 segment.exit_point.y + segment.dir2.y * tail,
1887 segment.exit_point.z + segment.dir2.z * tail};
1888 }
1889 if(segment.arc_path) {
1890 geom::Vec3 point =
1891 geom::sample(segment.arc, fraction * segment.arc.length);
1892 if(!segment.arc.spatial) {
1893 point.z = segment.start.z + segment.delta.z * fraction;
1894 }
1895 return point;
1896 }
1897 return geom::Vec3{segment.start.x + segment.delta.x * fraction,
1898 segment.start.y + segment.delta.y * fraction,
1899 segment.start.z + segment.delta.z * fraction};
1900}
1901
1902inline void AxisGroup::cartesian_pose_at(const CartesianSegment &segment,
1903 double fraction,
1904 geom::RigidTransform &tcp) const
1905{
1906 tcp.translation = cartesian_point_at(segment, fraction);
1907 double relative[3][3];
1908 geom::rodrigues(segment.axis, segment.angle * fraction, relative);
1909 geom::rotation_multiply(segment.rotation_start, relative, tcp.rotation);
1910}
1911
1912// Cycle-path Cartesian sampling (approved matrix decisions #3/#4/#7):
1913// one analytic inverse per cycle, seeded by the previous cycle's
1914// joints. A failure between the pre-validation samples is the declared
1915// group errorstop — members keep the last good setpoint, nothing
1916// extrapolates, nothing flips branches.
1917inline bool AxisGroup::cartesian_cycle(double ratio)
1918{
1919 double q[MaxAxes] = {};
1921 if(cartesian_.active_segment_.pose) {
1922 geom::RigidTransform tcp{};
1923 cartesian_pose_at(cartesian_.active_segment_, ratio, tcp);
1924 const geom::RigidTransform flange_target =
1925 geom::compose(tcp, pose_frames_.active_pose_tool_inverse_);
1926 kin::Pose6 pose{};
1927 pose.position[0] = flange_target.translation.x;
1928 pose.position[1] = flange_target.translation.y;
1929 pose.position[2] = flange_target.translation.z;
1930 for(int i = 0; i < 3; ++i) {
1931 for(int j = 0; j < 3; ++j) {
1932 pose.rotation[i][j] = flange_target.rotation[i][j];
1933 }
1934 }
1935 solved = pose_frames_.pose_kinematics_->inverse(pose, cartesian_.joints_,
1936 pose_frames_.pose_max_joint_step_, q);
1937 if(solved == rt::ErrorCode::ok &&
1938 pose_frames_.pose_kinematics_->singularity_margin(q) < pose_frames_.pose_min_margin_) {
1940 }
1941 } else {
1942 const geom::Vec3 point = cartesian_point_at(cartesian_.active_segment_, ratio);
1943 solved = pose_frames_.kinematics_->inverse(point, cartesian_.joints_, axes_.size(), q);
1944 if(solved == rt::ErrorCode::ok &&
1945 pose_frames_.kinematics_->singularity_margin(q, axes_.size()) <
1946 pose_frames_.kinematics_min_margin_) {
1948 }
1949 }
1950 if(solved != rt::ErrorCode::ok) {
1951 cartesian_.last_error_ = solved;
1952 abort_motion();
1953 set_group_error(solved);
1954 return false;
1955 }
1956 if(cartesian_.takeover_active_) {
1957 // Math-Max Step 5 (D10): keep strictly 1 inverse() per cycle and keep
1958 // cartesian_.joints_ strictly equal to pure q_base (never polluted by
1959 // residual offsets). Residual offsets add O(N) on member setpoints.
1960 for(std::size_t i = 0; i < axes_.size(); ++i) {
1961 const double offset =
1962 (i < 3 && cartesian_.takeover_residuals_[i].segment_count() > 0)
1963 ? otg::sample(cartesian_.takeover_residuals_[i],
1964 rt::CycleTick::from_cycles(active_tick_))
1965 .position
1966 : 0.0;
1967 axes_[i]->set_synchronized_position(q[i] + offset);
1968 cartesian_.joints_[i] = q[i];
1969 }
1970 if(!cartesian_.takeover_stopping_ &&
1971 active_tick_ >= cartesian_.takeover_residual_duration_) {
1972 cartesian_.takeover_active_ = false;
1973 cartesian_.takeover_tcp_tube_ = 0.0;
1974 }
1975 return true;
1976 }
1977 for(std::size_t i = 0; i < axes_.size(); ++i) {
1978 axes_[i]->set_synchronized_position(q[i]);
1979 cartesian_.joints_[i] = q[i];
1980 }
1981 return true;
1982}
1983
1984// Math-Max Step 5 (KB-109, R2-F1/F2/F3): Stage and verify the Cartesian LINE
1985// aborting takeover plan (or certified/replay-verified safe rest-start fallback)
1986// BEFORE abort_motion() so unprovable or out-of-bounds commands fail closed
1987// atomically without disturbing the active motion.
1988inline rt::ErrorCode AxisGroup::stage_cartesian_takeover(const GroupCommand &command)
1989{
1990 cartesian_.clear_staged_takeover();
1991 const double longest = command.cart.length;
1992 if(!command.cart.interior_soft_limits_ok) {
1994 }
1995 if(pose_frames_.kinematics_ == nullptr ||
1996 pose_frames_.pose_kinematics_ != nullptr ||
1997 pose_frames_.translation_path_differential_ == nullptr ||
1998 axes_.size() < 2 || axes_.size() > 3 ||
2001 }
2002
2003 CartesianTakeoverInput input{};
2004 input.kinematics = pose_frames_.kinematics_;
2005 input.differential = pose_frames_.translation_path_differential_;
2006 input.min_singularity_margin = pose_frames_.kinematics_min_margin_;
2007 input.joint_count = axes_.size();
2008 input.start_point = command.cart.start;
2009 input.unit_direction = {
2010 command.cart.delta.x / longest,
2011 command.cart.delta.y / longest,
2012 command.cart.delta.z / longest,
2013 };
2014 input.path_length = longest;
2015 input.has_path_delta = true;
2016 input.path_delta = command.cart.delta;
2017 if(cartesian_.pending_takeover_grid_valid_) {
2018 input.has_prevalidated_grid = true;
2019 input.prevalidated_grid = cartesian_.pending_takeover_grid_;
2020 }
2021 input.has_continuous_seed = !connector_.captured_from_output_history();
2022 for(std::size_t i = 0; i < axes_.size(); ++i) {
2023 input.start_joints[i] = axes_[i]->snapshot().command_position;
2024 input.captured_velocity[i] = connector_.captured_output_velocity()[i];
2025 input.captured_acceleration[i] = connector_.captured_output_acceleration()[i];
2026 input.continuous_velocity[i] = connector_.captured_analytic_velocity()[i];
2027 input.continuous_acceleration[i] = connector_.captured_analytic_acceleration()[i];
2028 input.member_limits[i] = axes_[i]->motion_limits();
2029 }
2030 input.base_command_limits = {
2031 command.velocity, command.acceleration, command.deceleration, command.jerk};
2032 input.max_tcp_tube = pose_frames_.cartesian_takeover_tcp_tube_limit_;
2033
2034 CartesianTakeoverPlan plan{};
2035 CartesianTakeoverCallCounts calls{};
2036 otg::Limits1D safe_limits{};
2037 bool safe_limits_proven = false;
2039 input, plan, calls, &safe_limits, &safe_limits_proven);
2040 if(plan_rc == rt::ErrorCode::ok) {
2041 cartesian_.staged_takeover_valid_ = true;
2042 cartesian_.staged_takeover_is_connector_ = true;
2043 cartesian_.staged_takeover_has_safe_envelope_ = safe_limits_proven;
2044 cartesian_.staged_base_profile_ = plan.base_profile;
2045 cartesian_.staged_base_duration_ = plan.base_duration;
2046 cartesian_.staged_residuals_ = plan.residual_profiles;
2047 cartesian_.staged_residual_duration_ = plan.residual_duration;
2048 cartesian_.staged_tcp_tube_ = plan.tcp_tube;
2049 if(safe_limits_proven) {
2050 cartesian_.staged_safe_limits_ = safe_limits;
2051 }
2052 return rt::ErrorCode::ok;
2053 }
2054
2055 if(safe_limits_proven) {
2056 const rt::Result<otg::Profile1D> rest =
2058 if(!rest) {
2060 }
2061 cartesian_.staged_takeover_valid_ = true;
2062 cartesian_.staged_takeover_is_connector_ = false;
2063 cartesian_.staged_takeover_has_safe_envelope_ = true;
2064 cartesian_.staged_base_profile_ = rest.value();
2065 cartesian_.staged_base_duration_ = rest.value().duration_cycles();
2066 cartesian_.staged_safe_limits_ = safe_limits;
2067 return rt::ErrorCode::ok;
2068 }
2069
2070 // Uncertified plugin or failed differential: allow rest-start fallback ONLY
2071 // when the entire rest profile fits within MaxReplayCycles and passes full
2072 // tick-by-tick IK/soft-limit/margin/member-v-a-j replay within D07 budget.
2073 const rt::Result<otg::Profile1D> short_rest =
2074 CartesianTakeoverPlanner::plan_rest_base_profile(longest, input.base_command_limits);
2075 constexpr std::size_t kMaxInvBudget =
2077 static_cast<std::size_t>(CartesianTakeoverPlanner::MaxReplayCycles);
2078 if(short_rest &&
2080 input, short_rest.value(), calls, kMaxInvBudget)) {
2081 cartesian_.staged_takeover_valid_ = true;
2082 cartesian_.staged_takeover_is_connector_ = false;
2083 cartesian_.staged_takeover_has_safe_envelope_ = false;
2084 cartesian_.staged_base_profile_ = short_rest.value();
2085 cartesian_.staged_base_duration_ = short_rest.value().duration_cycles();
2086 return rt::ErrorCode::ok;
2087 }
2088
2089 return plan_rc != rt::ErrorCode::ok ? plan_rc : rt::ErrorCode::infeasible;
2090}
2091
2092// Math-Max Step 5 (D11): dedicated replay-verified controlled stop while a
2093// Cartesian takeover connector is active.
2094inline rt::ErrorCode AxisGroup::plan_cartesian_connector_stop(double deceleration,
2095 double jerk)
2096{
2097 if(!cartesian_.takeover_active_ || !active_ ||
2098 active_kind_ != GroupPathKind::cartesian_linear ||
2099 cartesian_.active_segment_.pose ||
2100 cartesian_.active_segment_.arc_path ||
2101 cartesian_.active_segment_.chain ||
2102 pose_frames_.kinematics_ == nullptr ||
2103 active_path_length_ <= CartesianTakeoverPlanner::StateZeroTolerance ||
2104 axes_.size() < 2 || axes_.size() > 3) {
2106 }
2107
2108 const otg::State1D live_base =
2109 otg::sample(active_profile_, rt::CycleTick::from_cycles(active_tick_));
2110 std::array<double, MaxAxes> out_v{};
2111 std::array<double, MaxAxes> out_a{};
2112 current_member_output_state(out_v, out_a);
2113
2114 CartesianTakeoverStopInput stop_in{};
2115 stop_in.kinematics = pose_frames_.kinematics_;
2116 stop_in.min_singularity_margin = pose_frames_.kinematics_min_margin_;
2117 stop_in.joint_count = axes_.size();
2118 stop_in.start_point = cartesian_.active_segment_.start;
2119 stop_in.unit_direction = {
2120 cartesian_.active_segment_.delta.x / active_path_length_,
2121 cartesian_.active_segment_.delta.y / active_path_length_,
2122 cartesian_.active_segment_.delta.z / active_path_length_,
2123 };
2124 stop_in.path_length = active_path_length_;
2125 stop_in.has_path_delta = true;
2126 stop_in.path_delta = cartesian_.active_segment_.delta;
2127 stop_in.live_base_state = live_base;
2128 for(std::size_t i = 0; i < axes_.size(); ++i) {
2129 stop_in.live_base_joints[i] = cartesian_.joints_[i];
2130 stop_in.live_output_joints[i] = axes_[i]->snapshot().command_position;
2131 stop_in.captured_velocity[i] = out_v[i];
2132 stop_in.captured_acceleration[i] = out_a[i];
2133 if(cartesian_.takeover_residuals_[i].segment_count() > 0) {
2134 stop_in.live_residuals[i] = otg::sample(
2135 cartesian_.takeover_residuals_[i],
2136 rt::CycleTick::from_cycles(active_tick_));
2137 } else {
2138 stop_in.live_residuals[i] = otg::State1D{};
2139 }
2140 stop_in.member_limits[i] = axes_[i]->motion_limits();
2141 }
2142 stop_in.base_stop_limits = {
2143 std::max(active_command_.velocity, std::fabs(live_base.velocity)),
2144 active_command_.acceleration,
2145 deceleration,
2146 jerk,
2147 };
2148 stop_in.max_tcp_tube = pose_frames_.cartesian_takeover_tcp_tube_limit_;
2149
2150 CartesianTakeoverStopPlan stop_plan{};
2151 const rt::ErrorCode rc = CartesianTakeoverPlanner::plan_stop(stop_in, stop_plan);
2152 if(rc != rt::ErrorCode::ok) {
2153 return rc;
2154 }
2155
2156 active_profile_ = stop_plan.base_profile;
2157 active_tick_ = 0;
2158 active_duration_ = stop_plan.duration;
2159 override_paused_ = false;
2160 cartesian_.takeover_residuals_ = stop_plan.residual_profiles;
2161 cartesian_.takeover_residual_duration_ = stop_plan.duration;
2162 cartesian_.takeover_tcp_tube_ = stop_plan.tcp_tube;
2163 cartesian_.takeover_active_ = true;
2164 cartesian_.takeover_stopping_ = true;
2165 status_ = GroupStatus::stopping;
2166 return rt::ErrorCode::ok;
2167}
2168
2169} // namespace plcopen::core::axis
rt::Result< std::uint32_t > halt(double deceleration=1.0, double jerk=1.0, BufferMode buffer_mode=BufferMode::aborting)
static constexpr std::size_t MaxAxes
static bool verify_profile_monotonic(const otg::Profile1D &p, double length)
static bool inside_soft_limits(const MotionLimits &m, double pos)
static rt::Result< otg::Profile1D > plan_rest_base_profile(double path_length, const otg::Limits1D &limits)
static rt::ErrorCode plan_stop(const CartesianTakeoverStopInput &in, CartesianTakeoverStopPlan &plan_out)
static bool verify_rest_start_replay(const CartesianTakeoverInput &in, const otg::Profile1D &rest_profile, CartesianTakeoverCallCounts &calls, std::size_t max_inv_budget)
static rt::ErrorCode plan(const CartesianTakeoverInput &in, CartesianTakeoverPlan &best_out, CartesianTakeoverCallCounts &calls, otg::Limits1D *safe_base_limits_out=nullptr, bool *safe_base_limits_proven_out=nullptr)
static constexpr CycleTick from_cycles(std::int64_t cycles)
定义 cycle.h:42
static constexpr Result success(const T &value)
定义 error.h:24
static constexpr Result failure(ErrorCode error)
定义 error.h:29
Vec3 transform_rotate(const RigidTransform &transform, Vec3 v)
定义 frame.h:99
rt::Result< ArcSegment > make_arc_center_xy(Vec3 start, Vec3 center, Vec3 finish, bool counter_clockwise)
void rotation_multiply(const double a[3][3], const double b[3][3], double out[3][3])
Vec3 transform_point(const RigidTransform &transform, Vec3 p)
Vec3 sample(LineSegment line, double arclength)
rt::Result< ArcSegment > make_spatial_arc_center(Vec3 start, Vec3 center, Vec3 finish, Vec3 plane_normal, bool counter_clockwise)
double norm(Vec3 value)
double quintic_parameter_at_length(const QuinticBlendSegment &blend, double arclength)
double dot(Vec3 lhs, Vec3 rhs)
void rodrigues(const double axis[3], double angle, double out[3][3])
rt::Result< ArcSegment > make_arc_radius_xy(Vec3 start, Vec3 finish, double signed_radius, bool counter_clockwise)
rt::Result< ArcSegment > make_arc(Vec3 start, Vec3 via, Vec3 finish)
rt::Result< ArcSegment > make_spatial_arc_border(Vec3 start, Vec3 via, Vec3 finish, Vec3 ref_normal, bool counter_clockwise)
double angle_of(Vec3 point, Vec3 center)
RigidTransform make_rpy_transform(double x, double y, double z, double roll, double pitch, double yaw)
定义 frame.h:71
Vec3 quintic_point(const QuinticBlendSegment &blend, double u)
double normalize_sweep(double sweep, double orientation)
void relative_axis_angle(const double a[3][3], const double b[3][3], double axis[3], double &angle)
RigidTransform compose(const RigidTransform &a, const RigidTransform &b)
rt::Result< QuinticBlendSegment > make_quintic_blend(Vec3 start, Vec3 corner, Vec3 finish, double tolerance)
rt::Result< ArcSegment > make_spatial_arc_radius(Vec3 start, Vec3 finish, double signed_radius, Vec3 plane_normal, bool counter_clockwise)
rt::Result< Profile1D > plan(State1D from, Target1D to, Limits1D limits)
rt::Result< Profile1D > plan_time_optimal(State1D from, Target1D to, Limits1D limits)
rt::Result< Profile1D > solve_fixed_time(State1D from, Target1D to, Limits1D limits, std::int64_t total_cycles)
bool is_finite(State1D state)
State1D sample(const Profile1D &profile, rt::CycleTick tick)
double jerk_reachable_speed(double entry, double distance, double bound, double jerk)
定义 path.h:20
std::string trim(std::string_view text)
定义 l2b.h:100