rsbullet 0.3.11

Compiles bullet3 and exposes rust bindings to the C API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use std::{marker::PhantomData, sync::mpsc::Sender};

use anyhow::Result;
use futures::future::BoxFuture;
use robot_behavior::behavior::{Arm, ArmParam};
use robot_behavior::utils::path_generate;
use robot_behavior::{
    ArmImpedance, ArmPreplannedPath, ArmState, CartesianImpedanceHandle, Coord,
    JointImpedanceHandle, JointStateSync, LoadState, MotionType, Pose, RobotException, RobotFile,
    RobotResult, behavior::*,
};
use rsbullet_core::{
    BulletError, BulletResult, ControlModeArray, InverseKinematicsOptions, JointType,
    LoadModelFlags, PhysicsClient, UrdfOptions,
};

use crate::RsBullet;
use crate::types::{QueuedControl, RsBulletRobotState};

pub struct RsBulletRobot<R> {
    pub body_id: i32,
    pub joint_indices: Vec<i32>,
    pub joint_names: Vec<String>,
    pub(crate) command_sender: Sender<QueuedControl>,
    pub end_effector_link: i32,
    state_cache: Arc<Mutex<RsBulletRobotState>>,
    /// Control period for rate-limiting simulation. If the simulation step completes
    /// faster than this duration, the step callback will sleep for the remaining time.
    /// Typically set to match the desired control frequency (e.g., 1ms for 1kHz).
    pub control_period: Duration,
    _marker: PhantomData<R>,
}

impl<R> RsBulletRobot<R> {
    pub fn enqueue<CF>(&self, control: CF) -> anyhow::Result<()>
    where
        CF: FnMut(&mut PhysicsClient, Duration) -> BulletResult<bool> + Send + 'static,
    {
        self.command_sender
            .send(Box::new(control))
            .map_err(|_| anyhow::anyhow!("Failed to send control command: channel closed"))?;
        Ok(())
    }
}

pub struct RsBulletRobotBuilder<'a, R> {
    pub(crate) _marker: PhantomData<R>,
    pub(crate) rsbullet: &'a mut RsBullet,
    pub(crate) load_file: &'static str,
    pub(crate) base: Option<nalgebra::Isometry3<f64>>,
    pub(crate) base_fixed: bool,
    pub(crate) use_maximal_coordinates: Option<bool>,
    pub(crate) scaling: Option<f64>,
    pub(crate) flags: Option<LoadModelFlags>,
    pub(crate) end_effector_link: Option<i32>,
    pub(crate) end_effector_link_name: Option<String>,
}

impl<'a, R: RobotFile> RsBulletRobotBuilder<'a, R> {
    pub fn new(rsbullet: &'a mut RsBullet) -> Self {
        RsBulletRobotBuilder {
            _marker: PhantomData,
            rsbullet,
            load_file: R::URDF,
            base: None,
            base_fixed: false,
            scaling: None,
            flags: None,
            use_maximal_coordinates: None,
            end_effector_link: None,
            end_effector_link_name: None,
        }
    }
}

impl<R> RsBulletRobotBuilder<'_, R> {
    pub fn use_maximal_coordinates(mut self, use_maximal: bool) -> Self {
        self.use_maximal_coordinates = Some(use_maximal);
        self
    }
    pub fn flags(mut self, flags: LoadModelFlags) -> Self {
        self.flags = Some(flags);
        self
    }

    /// 显式指定末端 link 索引(Bullet joint index 语义)
    pub fn end_effector_link(mut self, link_index: i32) -> Self {
        self.end_effector_link = Some(link_index);
        self
    }

    /// 按 link 名称指定末端(优先于默认推断)
    pub fn end_effector_link_name(mut self, link_name: impl Into<String>) -> Self {
        self.end_effector_link_name = Some(link_name.into());
        self
    }
}

impl<'a, R> EntityBuilder<'a> for RsBulletRobotBuilder<'a, R> {
    type Entity = RsBulletRobot<R>;

    fn name(self, _: String) -> Self {
        self
    }

    fn base(mut self, base: impl Into<nalgebra::Isometry3<f64>>) -> Self {
        self.base = Some(base.into());
        self
    }
    fn base_fixed(mut self, base_fixed: bool) -> Self {
        self.base_fixed = base_fixed;
        self
    }
    fn scaling(mut self, scaling: f64) -> Self {
        self.scaling = Some(scaling);
        self
    }
    fn load(self) -> Result<RsBulletRobot<R>> {
        let body_id = self.rsbullet.client_mut().load_urdf(
            self.load_file,
            Some(UrdfOptions {
                base: self.base,
                use_fixed_base: self.base_fixed,
                global_scaling: self.scaling,
                flags: self.flags,
                use_maximal_coordinates: self.use_maximal_coordinates,
            }),
        )?;

        let joint_count = self.rsbullet.client_mut().get_num_joints(body_id);
        let mut joint_indices = Vec::new();
        let mut joint_names = Vec::new();
        for i in 0..joint_count {
            let info = self.rsbullet.client_mut().get_joint_info(body_id, i)?;
            if matches!(info.joint_type, JointType::Revolute | JointType::Prismatic) {
                joint_indices.push(i);
                joint_names.push(info.joint_name.clone());
            }
        }

        let end_effector_link = if let Some(idx) = self.end_effector_link {
            idx
        } else if let Some(name) = &self.end_effector_link_name {
            let mut selected = None;
            for i in 0..joint_count {
                let info = self.rsbullet.client_mut().get_joint_info(body_id, i)?;
                if info.link_name == *name {
                    selected = Some(i);
                    break;
                }
            }
            selected.unwrap_or_else(|| {
                if joint_count == 0 {
                    -1
                } else {
                    joint_count - 1
                }
            })
        } else {
            if joint_count == 0 {
                -1
            } else {
                joint_count - 1
            }
        };

        let joint_states = self
            .rsbullet
            .client_mut()
            .get_joint_states(body_id, &joint_indices)?;
        let link_state = if end_effector_link >= 0 {
            Some(self.rsbullet.client_mut().get_link_state(
                body_id,
                end_effector_link,
                true,
                true,
            )?)
        } else {
            None
        };
        let state_cache = Arc::new(Mutex::new(RsBulletRobotState { joint_states, link_state }));

        let cache_clone = state_cache.clone();
        let joint_indices_clone = joint_indices.clone();
        let end_effector_link_clone = end_effector_link;

        let sender = self.rsbullet.command_sender();

        let robot = RsBulletRobot::<R> {
            body_id,
            joint_indices,
            joint_names,
            command_sender: sender,
            end_effector_link,
            state_cache,
            control_period: Duration::from_secs_f64(1.0 / 240.0),
            _marker: PhantomData,
        };

        robot.enqueue(move |client, _| {
            let joint_states = client.get_joint_states(body_id, &joint_indices_clone)?;
            let link_state = if end_effector_link_clone >= 0 {
                Some(client.get_link_state(body_id, end_effector_link_clone, true, true)?)
            } else {
                None
            };
            let mut cache = cache_clone.lock().map_err(|_| BulletError::CommandFailed {
                message: "state cache poisoned",
                code: -1,
            })?;
            cache.joint_states = joint_states;
            cache.link_state = link_state;
            Ok(false)
        })?;

        Ok(robot)
    }
}

impl<R: JointStateSync> AttachFrom<R> for RsBulletRobot<R> {
    fn attach_from(self, from: &mut R) -> Result<()> {
        let handle = from.joint_state_handle();
        let body_id = self.body_id;
        let joint_names = self.joint_names.clone();
        let joint_indices = self.joint_indices.clone();

        self.enqueue(move |client, _| {
            let map = handle.lock().map_err(|_| BulletError::CommandFailed {
                message: "joint state handle poisoned",
                code: -1,
            })?;

            for (i, name) in joint_names.iter().enumerate() {
                if let Some(entry) = map.get(name) {
                    client.reset_joint_state(
                        body_id,
                        joint_indices[i],
                        entry.position,
                        entry.velocity,
                    )?;
                }
            }

            Ok(false) // keep running every step
        })?;

        Ok(())
    }
}

impl<const N: usize, R> Arm<N> for RsBulletRobot<R>
where
    R: ArmParam<N>,
{
    fn state(&mut self) -> RobotResult<ArmState<N>> {
        let cache = self
            .state_cache
            .lock()
            .map_err(|_| RobotException::NetworkError("state cache poisoned".to_string()))?;
        Ok(cache.clone().into())
    }

    fn set_load(&mut self, _load: LoadState) -> RobotResult<()> {
        Ok(())
    }

    fn set_coord(&mut self, _coord: Coord) -> RobotResult<()> {
        Ok(())
    }

    fn with_coord(&mut self, _coord: Coord) -> &mut Self {
        self
    }

    fn set_scale(&mut self, _scale: f64) -> RobotResult<()> {
        Ok(())
    }

    fn with_scale(&mut self, _scale: f64) -> &mut Self {
        self
    }

    fn with_velocity(&mut self, _joint_vel: &[f64; N]) -> &mut Self {
        self
    }

    fn with_acceleration(&mut self, _joint_acc: &[f64; N]) -> &mut Self {
        self
    }

    fn with_jerk(&mut self, _joint_jerk: &[f64; N]) -> &mut Self {
        self
    }

    fn with_cartesian_velocity(&mut self, _cartesian_vel: f64) -> &mut Self {
        self
    }

    fn with_cartesian_acceleration(&mut self, _cartesian_acc: f64) -> &mut Self {
        self
    }

    fn with_cartesian_jerk(&mut self, _cartesian_jerk: f64) -> &mut Self {
        self
    }

    fn with_rotation_velocity(&mut self, _rotation_vel: f64) -> &mut Self {
        self
    }

    fn with_rotation_acceleration(&mut self, _rotation_acc: f64) -> &mut Self {
        self
    }

    fn with_rotation_jerk(&mut self, _rotation_jerk: f64) -> &mut Self {
        self
    }
}

impl<const N: usize, R> ArmParam<N> for RsBulletRobot<R>
where
    R: ArmParam<N>,
{
    const CONTROL_PERIOD: f64 = R::CONTROL_PERIOD;
    const JOINT_DEFAULT: [f64; N] = R::JOINT_DEFAULT;
    const JOINT_MIN: [f64; N] = R::JOINT_MIN;
    const JOINT_MAX: [f64; N] = R::JOINT_MAX;
    const JOINT_VEL_BOUND: [f64; N] = R::JOINT_VEL_BOUND;
    const JOINT_ACC_BOUND: [f64; N] = R::JOINT_ACC_BOUND;
    const JOINT_JERK_BOUND: [f64; N] = R::JOINT_JERK_BOUND;
    const CARTESIAN_VEL_BOUND: f64 = R::CARTESIAN_VEL_BOUND;
    const CARTESIAN_ACC_BOUND: f64 = R::CARTESIAN_ACC_BOUND;
    const CARTESIAN_JERK_BOUND: f64 = R::CARTESIAN_JERK_BOUND;
    const ROTATION_VEL_BOUND: f64 = R::ROTATION_VEL_BOUND;
    const ROTATION_ACC_BOUND: f64 = R::ROTATION_ACC_BOUND;
    const ROTATION_JERK_BOUND: f64 = R::ROTATION_JERK_BOUND;
    const TORQUE_BOUND: [f64; N] = R::TORQUE_BOUND;
    const TORQUE_DOT_BOUND: [f64; N] = R::TORQUE_DOT_BOUND;
}

impl<const N: usize, R> ArmPreplannedMotion<N> for RsBulletRobot<R>
where
    R: ArmParam<N>,
{
    fn move_joint(&mut self, target: &[f64; N]) -> RobotResult<()> {
        self.move_joint_async(target)
    }

    fn move_joint_async(&mut self, target: &[f64; N]) -> RobotResult<()> {
        let body_id = self.body_id;
        let joint_indices = self.joint_indices.clone();

        let state = self.state()?;
        let (path_generate, t_max) = path_generate::joint_s_curve(
            &state.measured.joint.unwrap_or([0.; N]),
            target,
            &R::JOINT_VEL_BOUND,
            &R::JOINT_ACC_BOUND,
            &R::JOINT_JERK_BOUND,
        );

        let mut duration = Duration::from_secs(0);
        self.enqueue(move |client, dt| {
            duration += dt;
            let target = path_generate(duration);
            client.set_joint_motor_control_array(
                body_id,
                &joint_indices[0..N],
                ControlModeArray::Position(&target),
                None,
            )?;

            Ok(duration >= t_max)
        })
        .map_err(Into::into)
    }

    fn move_cartesian(&mut self, target: &Pose) -> RobotResult<()> {
        self.move_cartesian_async(target)
    }

    fn move_cartesian_async(&mut self, target: &Pose) -> RobotResult<()> {
        if self.end_effector_link < 0 {
            return Err(RobotException::UnprocessableInstructionError(
                "robot has no movable joints".to_string(),
            ));
        }

        let body_id = self.body_id;
        let joint_indices = self.joint_indices.clone();
        let end_effector_link = self.end_effector_link;

        let state = self.state()?;
        let (path_generate, t_max) = path_generate::cartesian_quat_simple_4th_curve(
            state.measured.pose_o_to_ee.unwrap_or_default().quat(),
            target.quat(),
            R::ROTATION_VEL_BOUND,
            R::ROTATION_ACC_BOUND,
        );

        let mut duration = Duration::from_secs(0);
        self.enqueue(move |client, dt| {
            duration += dt;

            let target_pose = path_generate(duration);

            let current_q: Vec<f64> = client
                .get_joint_states(body_id, &joint_indices)?
                .iter()
                .map(|s| s.position)
                .collect();
            let dof = client.compute_dof_count(body_id) as usize;
            let mut lower_full: Vec<f64> = R::JOINT_MIN.iter().copied().collect();
            let mut upper_full: Vec<f64> = R::JOINT_MAX.iter().copied().collect();
            let mut rest_full: Vec<f64> = R::JOINT_DEFAULT.iter().copied().collect();
            while lower_full.len() < dof {
                lower_full.push(0.0);
                upper_full.push(0.04);
                rest_full.push(0.02);
            }
            let joint_ranges: Vec<f64> = lower_full
                .iter()
                .zip(upper_full.iter())
                .map(|(l, u)| u - l)
                .collect();
            let mut seed = current_q;
            while seed.len() < dof {
                seed.push(0.02);
            }
            let ik_options = InverseKinematicsOptions {
                current_positions: Some(&seed),
                lower_limits: Some(&lower_full),
                upper_limits: Some(&upper_full),
                joint_ranges: Some(&joint_ranges),
                rest_poses: Some(&rest_full),
                max_iterations: Some(200),
                residual_threshold: Some(1e-4),
                ..Default::default()
            };

            let solution = client.calculate_inverse_kinematics(
                body_id,
                end_effector_link,
                target_pose,
                &ik_options,
            )?;

            if solution.len() < N {
                return Err(BulletError::CommandFailed {
                    message: "inverse kinematics returned insufficient joint values",
                    code: solution.len() as i32,
                });
            }

            client.set_joint_motor_control_array(
                body_id,
                &joint_indices[0..N],
                ControlModeArray::Position(&solution[..N]),
                None,
            )?;

            Ok(duration >= t_max)
        })
        .map_err(Into::into)
    }
}

impl<const N: usize, R> ArmPreplannedPath<N> for RsBulletRobot<R>
where
    R: ArmParam<N>,
{
    fn move_traj(&mut self, path: Vec<robot_behavior::MotionType<N>>) -> RobotResult<()> {
        self.move_traj_async(path)
    }
    fn move_traj_async(&mut self, path: Vec<robot_behavior::MotionType<N>>) -> RobotResult<()> {
        let body_id = self.body_id;
        let joint_indices = self.joint_indices.clone();
        let mut path = path.into_iter();

        self.enqueue(move |client, _| match path.next() {
            Some(MotionType::Joint(joint)) => {
                client.set_joint_motor_control_array(
                    body_id,
                    &joint_indices[0..N],
                    ControlModeArray::Position(&joint),
                    None,
                )?;
                Ok(false)
            }

            Some(MotionType::Cartesian(pose)) => {
                if joint_indices.len() < 2 {
                    return Err(BulletError::CommandFailed {
                        message: "robot has no movable joints",
                        code: -1,
                    });
                }

                let current_q: Vec<f64> = client
                    .get_joint_states(body_id, &joint_indices)?
                    .iter()
                    .map(|s| s.position)
                    .collect();
                let dof = client.compute_dof_count(body_id) as usize;
                let mut lower_full: Vec<f64> = R::JOINT_MIN.iter().copied().collect();
                let mut upper_full: Vec<f64> = R::JOINT_MAX.iter().copied().collect();
                let mut rest_full: Vec<f64> = R::JOINT_DEFAULT.iter().copied().collect();
                while lower_full.len() < dof {
                    lower_full.push(0.0);
                    upper_full.push(0.04);
                    rest_full.push(0.02);
                }
                let joint_ranges: Vec<f64> = lower_full
                    .iter()
                    .zip(upper_full.iter())
                    .map(|(l, u)| u - l)
                    .collect();
                let mut seed = current_q;
                while seed.len() < dof {
                    seed.push(0.02);
                }
                let ik_options = InverseKinematicsOptions {
                    current_positions: Some(&seed),
                    lower_limits: Some(&lower_full),
                    upper_limits: Some(&upper_full),
                    joint_ranges: Some(&joint_ranges),
                    rest_poses: Some(&rest_full),
                    max_iterations: Some(200),
                    residual_threshold: Some(1e-4),
                    ..Default::default()
                };

                let solution = client.calculate_inverse_kinematics(
                    body_id,
                    joint_indices.len() as i32 - 1,
                    pose.quat(),
                    &ik_options,
                )?;

                if solution.len() < N {
                    return Err(BulletError::CommandFailed {
                        message: "inverse kinematics returned insufficient joint values",
                        code: solution.len() as i32,
                    });
                }

                client.set_joint_motor_control_array(
                    body_id,
                    &joint_indices[0..N],
                    ControlModeArray::Position(&solution[..N]),
                    None,
                )?;

                Ok(false)
            }
            None => Ok(true),
            _ => Err(BulletError::CommandFailed {
                message: "unsupported motion type in preplanned path",
                code: -1,
            }),
        })
        .map_err(Into::into)
    }
}

// impl<R, const N: usize> ArmStreamingMotion<N> for RsBulletRobot<R>
// where
//     R: ArmParam<N>,
// {
//     type Handle = ;
//     fn control_with_target(&mut self) -> Arc<Mutex<Option<robot_behavior::ControlType<N>>>> {}
//     fn move_to_target(&mut self) -> Arc<Mutex<Option<robot_behavior::MotionType<N>>>> {}
//     fn end_streaming(&mut self) -> RobotResult<()> {}
//     fn start_streaming(&mut self) -> RobotResult<Self::Handle> {}
// }

impl<R, const N: usize> ArmRealtimeControl<N> for RsBulletRobot<R>
where
    R: ArmParam<N>,
{
    fn control_with_closure<FC>(&mut self, mut closure: FC) -> RobotResult<()>
    where
        FC: FnMut(ArmState<N>, Duration) -> (robot_behavior::ControlType<N>, bool) + Send + 'static,
    {
        let body_id = self.body_id;
        let joint_indices = self.joint_indices.clone();
        let cache_clone = self.state_cache.clone();
        let zero_velocity = vec![0.0; N];
        let zero_force = vec![0.0; N];
        let mut torque_mode_initialized = false;
        self.enqueue(move |client, dt| {
            let state = {
                let cache = cache_clone.lock().map_err(|_| {
                    RobotException::NetworkError("state cache poisoned".to_string())
                })?;
                cache.clone().into()
            };
            let (control, done) = closure(state, dt);

            match control {
                robot_behavior::ControlType::Torque(torque) => {
                    if !torque_mode_initialized {
                        client.set_joint_motor_control_array(
                            body_id,
                            &joint_indices[0..N],
                            ControlModeArray::Velocity(&zero_velocity),
                            Some(&zero_force),
                        )?;
                        torque_mode_initialized = true;
                    }
                    client.set_joint_motor_control_array(
                        body_id,
                        &joint_indices[0..N],
                        ControlModeArray::Torque(&torque),
                        None,
                    )?;
                }
                robot_behavior::ControlType::Zero => {
                    if !torque_mode_initialized {
                        client.set_joint_motor_control_array(
                            body_id,
                            &joint_indices[0..N],
                            ControlModeArray::Velocity(&zero_velocity),
                            Some(&zero_force),
                        )?;
                        torque_mode_initialized = true;
                    }
                    let zero_torque = vec![0.0; N];
                    client.set_joint_motor_control_array(
                        body_id,
                        &joint_indices[0..N],
                        ControlModeArray::Torque(&zero_torque),
                        None,
                    )?;
                }
            }

            Ok(done)
        })
        .map_err(Into::into)
    }
    fn move_with_closure<FM>(&mut self, mut closure: FM) -> RobotResult<()>
    where
        FM: FnMut(ArmState<N>, Duration) -> (robot_behavior::MotionType<N>, bool) + Send + 'static,
    {
        let body_id = self.body_id;
        let joint_indices = self.joint_indices.clone();
        let end_effector_link = self.end_effector_link;
        let cache_clone = self.state_cache.clone();
        self.enqueue(move |client, dt| {
            let state = {
                let cache = cache_clone.lock().map_err(|_| {
                    RobotException::NetworkError("state cache poisoned".to_string())
                })?;
                cache.clone().into()
            };
            let (motion, done) = closure(state, dt);

            match motion {
                robot_behavior::MotionType::Joint(target) => {
                    client.set_joint_motor_control_array(
                        body_id,
                        &joint_indices[0..N],
                        ControlModeArray::Position(&target),
                        None,
                    )?;
                }
                robot_behavior::MotionType::JointVel(vel) => {
                    client.set_joint_motor_control_array(
                        body_id,
                        &joint_indices[0..N],
                        ControlModeArray::Velocity(&vel),
                        None,
                    )?;
                }
                robot_behavior::MotionType::Cartesian(pose) => {
                    if end_effector_link < 0 {
                        return Err(BulletError::CommandFailed {
                            message: "robot has no end-effector link",
                            code: -1,
                        });
                    }

                    let current_q: Vec<f64> = client
                        .get_joint_states(body_id, &joint_indices)?
                        .iter()
                        .map(|s| s.position)
                        .collect();
                    let dof = client.compute_dof_count(body_id) as usize;
                    let mut lower_full: Vec<f64> = R::JOINT_MIN.iter().copied().collect();
                    let mut upper_full: Vec<f64> = R::JOINT_MAX.iter().copied().collect();
                    let mut rest_full: Vec<f64> = R::JOINT_DEFAULT.iter().copied().collect();
                    while lower_full.len() < dof {
                        lower_full.push(0.0);
                        upper_full.push(0.04);
                        rest_full.push(0.02);
                    }
                    let joint_ranges: Vec<f64> = lower_full
                        .iter()
                        .zip(upper_full.iter())
                        .map(|(l, u)| u - l)
                        .collect();
                    let mut seed = current_q;
                    while seed.len() < dof {
                        seed.push(0.02);
                    }
                    let ik_options = InverseKinematicsOptions {
                        current_positions: Some(&seed),
                        lower_limits: Some(&lower_full),
                        upper_limits: Some(&upper_full),
                        joint_ranges: Some(&joint_ranges),
                        rest_poses: Some(&rest_full),
                        max_iterations: Some(200),
                        residual_threshold: Some(1e-4),
                        ..Default::default()
                    };

                    let solution = client.calculate_inverse_kinematics(
                        body_id,
                        end_effector_link,
                        pose.quat(),
                        &ik_options,
                    )?;

                    if solution.len() < N {
                        return Err(BulletError::CommandFailed {
                            message: "inverse kinematics returned insufficient joint values",
                            code: solution.len() as i32,
                        });
                    }

                    client.set_joint_motor_control_array(
                        body_id,
                        &joint_indices[0..N],
                        ControlModeArray::Position(&solution[..N]),
                        None,
                    )?;
                }
                _ => {}
            }

            Ok(done)
        })
        .map_err(Into::into)
    }
}

impl<R, const N: usize> ArmImpedance<N> for RsBulletRobot<R>
where
    R: ArmParam<N>,
{
    fn joint_impedance_async(
        &mut self,
        stiffness: &[f64; N],
        damping: &[f64; N],
    ) -> RobotResult<JointImpedanceHandle<N>> {
        let handle = JointImpedanceHandle {
            stiffness: Arc::new(Mutex::new(*stiffness)),
            damping: Arc::new(Mutex::new(*damping)),
            target: Arc::new(Mutex::new(None)),
            is_finished: Arc::new(AtomicBool::new(false)),
        };

        let stiffness_clone = handle.stiffness.clone();
        let damping_clone = handle.damping.clone();
        let target_clone = handle.target.clone();
        let is_finished_clone = handle.is_finished.clone();

        let body_id = self.body_id;
        let joint_indices = self.joint_indices.clone();
        let cache_clone = self.state_cache.clone();
        let zero_velocity = vec![0.0; N];
        let zero_force = vec![0.0; N];
        let mut torque_mode_initialized = false;

        self.enqueue(move |client, _| {
            let state: ArmState<N> = {
                let cache = cache_clone.lock().map_err(|_| BulletError::CommandFailed {
                    message: "state cache poisoned",
                    code: -1,
                })?;
                cache.clone().into()
            };

            let q = state.measured.joint.unwrap_or([0.; N]);
            let dq = state.measured.joint_vel.unwrap_or([0.; N]);
            let target = {
                let t = target_clone.lock().unwrap();
                t.unwrap_or(q)
            };
            let stiffness = *stiffness_clone.lock().unwrap();
            let damping = *damping_clone.lock().unwrap();

            // PD control: τ = K * (q_d - q) - D * dq
            let mut torque = [0.0; N];
            for i in 0..N {
                torque[i] = stiffness[i] * (target[i] - q[i]) - damping[i] * dq[i];
            }

            // 扭矩限幅,避免仿真发散。
            for i in 0..N {
                let tau = torque[i];
                let limit = R::TORQUE_BOUND[i].abs();
                torque[i] = tau.clamp(-limit, limit);
            }

            if !torque_mode_initialized {
                client.set_joint_motor_control_array(
                    body_id,
                    &joint_indices[0..N],
                    ControlModeArray::Velocity(&zero_velocity),
                    Some(&zero_force),
                )?;
                torque_mode_initialized = true;
            }

            client.set_joint_motor_control_array(
                body_id,
                &joint_indices[0..N],
                ControlModeArray::Torque(&torque),
                None,
            )?;

            Ok(is_finished_clone.load(Ordering::SeqCst))
        })
        .map_err(|e| RobotException::CommandException(format!("{e}")))?;

        Ok(handle)
    }

    fn cartesian_impedance_async(
        &mut self,
        stiffness: (f64, f64),
        damping: (f64, f64),
    ) -> RobotResult<CartesianImpedanceHandle> {
        let handle = CartesianImpedanceHandle {
            stiffness: Arc::new(Mutex::new(stiffness)),
            damping: Arc::new(Mutex::new(damping)),
            target: Arc::new(Mutex::new(None)),
            is_finished: Arc::new(AtomicBool::new(false)),
        };

        let stiffness_clone = handle.stiffness.clone();
        let damping_clone = handle.damping.clone();
        let target_clone = handle.target.clone();
        let is_finished_clone = handle.is_finished.clone();

        let body_id = self.body_id;
        let joint_indices = self.joint_indices.clone();
        let end_effector_link = self.end_effector_link;
        let cache_clone = self.state_cache.clone();
        let zero_velocity = vec![0.0; N];
        let zero_force = vec![0.0; N];
        let mut torque_mode_initialized = false;

        self.enqueue(move |client, _| {
            let state: ArmState<N> = {
                let cache = cache_clone.lock().map_err(|_| BulletError::CommandFailed {
                    message: "state cache poisoned",
                    code: -1,
                })?;
                cache.clone().into()
            };

            let q = state.measured.joint.unwrap_or([0.; N]);
            let dq = state.measured.joint_vel.unwrap_or([0.; N]);
            let current_pose = state.measured.pose_o_to_ee.unwrap_or_default();

            let target_pose = {
                let t = target_clone.lock().unwrap();
                t.unwrap_or(current_pose)
            };
            let (trans_stiffness, rot_stiffness) = *stiffness_clone.lock().unwrap();
            let (trans_damping, rot_damping) = *damping_clone.lock().unwrap();

            // Compute Jacobian via physics engine
            let zero_acc = vec![0.0; N];
            let jacobian = client.calculate_jacobian(
                body_id,
                end_effector_link,
                [0.0, 0.0, 0.0],
                &q,
                &dq,
                &zero_acc,
            )?;

            // Cartesian position/orientation error
            let current_quat = current_pose.quat();
            let target_quat = target_pose.quat();

            let pos_error = target_quat.translation.vector - current_quat.translation.vector;
            let rot_error = {
                let q_cur = current_quat.rotation;
                let q_des = target_quat.rotation;
                let q_err = q_des * q_cur.inverse();
                q_err.scaled_axis()
            };

            // Cartesian force: F = K_t * Δx - D_t * J * dq (translational)
            //                   τ_c = K_r * Δθ - D_r * J_r * dq (rotational)
            let j_lin = &jacobian.linear; // 3xN
            let j_ang = &jacobian.angular; // 3xN
            let dq_vec = nalgebra::DVector::from_column_slice(&dq);
            let lin_vel = j_lin * &dq_vec; // 3x1
            let ang_vel = j_ang * &dq_vec; // 3x1

            let mut force = nalgebra::Vector3::zeros();
            let mut torque_cart = nalgebra::Vector3::zeros();
            for i in 0..3 {
                force[i] = trans_stiffness * pos_error[i] - trans_damping * lin_vel[i];
                torque_cart[i] = rot_stiffness * rot_error[i] - rot_damping * ang_vel[i];
            }

            // Map wrench to joint torques: τ = J_lin^T * F + J_ang^T * τ_cart
            let tau = j_lin.transpose() * force + j_ang.transpose() * torque_cart;

            let mut torque = [0.0; N];
            for i in 0..N.min(tau.len()) {
                torque[i] = tau[i];
            }

            // 扭矩限幅,避免控制力不足或过大震荡。
            for i in 0..N {
                let tau = torque[i];
                let limit = R::TORQUE_BOUND[i].abs();
                torque[i] = tau.clamp(-limit, limit);
            }

            if !torque_mode_initialized {
                client.set_joint_motor_control_array(
                    body_id,
                    &joint_indices[0..N],
                    ControlModeArray::Velocity(&zero_velocity),
                    Some(&zero_force),
                )?;
                torque_mode_initialized = true;
            }

            client.set_joint_motor_control_array(
                body_id,
                &joint_indices[0..N],
                ControlModeArray::Torque(&torque),
                None,
            )?;

            Ok(is_finished_clone.load(Ordering::SeqCst))
        })
        .map_err(|e| RobotException::CommandException(format!("{e}")))?;

        Ok(handle)
    }

    fn joint_impedance_control(
        &mut self,
        stiffness: &[f64; N],
        damping: &[f64; N],
    ) -> RobotResult<(
        JointImpedanceHandle<N>,
        impl FnMut() -> BoxFuture<'static, RobotResult<()>> + Send + 'static,
    )> {
        let handle = self.joint_impedance_async(stiffness, damping)?;
        let is_finished = handle.is_finished.clone();

        let closure = Box::new(move || {
            let is_finished = is_finished.clone();
            Box::pin(async move {
                while !is_finished.load(Ordering::SeqCst) {
                    tokio::time::sleep(Duration::from_millis(10)).await;
                }
                Ok(())
            }) as BoxFuture<'static, RobotResult<()>>
        });

        Ok((handle, closure))
    }

    fn cartesian_impedance_control(
        &mut self,
        stiffness: (f64, f64),
        damping: (f64, f64),
    ) -> RobotResult<(
        CartesianImpedanceHandle,
        impl FnMut() -> BoxFuture<'static, RobotResult<()>> + Send + 'static,
    )> {
        let handle = self.cartesian_impedance_async(stiffness, damping)?;
        let is_finished = handle.is_finished.clone();

        let closure = Box::new(move || {
            let is_finished = is_finished.clone();
            Box::pin(async move {
                while !is_finished.load(Ordering::SeqCst) {
                    tokio::time::sleep(Duration::from_millis(10)).await;
                }
                Ok(())
            }) as BoxFuture<'static, RobotResult<()>>
        });

        Ok((handle, closure))
    }
}