zmatrix 0.4.2

Compile-time dimensional analysis & physics-aware linear algebra for aerospace and robotics
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
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
//! 物理量系统:25 种物理量及其量纲安全运算。
//!
//! # 物理量与裸 `f64` 的运算
//!
//! `X + f64`、`X - f64`、`X * f64`、`X / f64` 这类实现,语义都是:
//! **裸数直接作用于物理量的内部存储值,按其当前单位理解,不做任何单位换算。**
//!
//! 这是**有意设计**,不是缺陷。`f64` 自身不带单位,库无从判断它代表 1 m 还是 1 km;
//! 若擅自按基准单位换算,等于替调用方做了一个它并未表达的假设。
//!
//! ```
//! use zmatrix::physics::basic::Distance;
//!
//! // 由 from_km 构造:内部单位是 km,+ 1.0 即在 km 上加 1
//! let a = Distance::from_km(1.0) + 1.0;
//! // 由 from_m 构造:内部单位是 m,+ 1.0 即在 m 上加 1
//! let b = Distance::from_m(1000.0) + 1.0;
//!
//! assert_eq!(a.as_km(), 2.0);
//! assert_eq!(b.as_m(), 1001.0);
//! ```
//!
//! 注意 `a` 与 `b` 在加 `1.0` **之前**是相等的(都是 1000 m),加完之后不等。
//! 这就是"裸数与物理量混算"必须付出的代价 —— 单位信息在运算符里丢失了。
//!
//! **需要单位安全时,请让两个物理量直接运算**,把单位写进类型:
//!
//! ```
//! use zmatrix::physics::basic::Distance;
//!
//! let a = Distance::from_km(1.0);
//! let b = Distance::from_m(1000.0);
//! let c = a + b;                  // 由编译器统一换算到 m,再相加
//!
//! assert_eq!(c.as_m(), 2000.0);
//! ```
//!
//! 判定口径:只要参与运算的两侧有一侧是裸数,就没有单位保证;
//! 两侧都是物理量时,单位由类型系统负责。

use std::any::Any;
use std::fmt::{Display, Formatter};
use std::ops::Div;

mod acceleration;
mod angular;
mod angular_acceleration;
mod angular_momentum;
mod angular_velocity;
mod area;
mod coef;
mod distance;
mod electric_capacitance;
mod electric_charge;
mod electric_conductance;
mod electric_current;
mod electric_potential;
mod electric_resistance;
mod energy;
mod force;
pub mod heat_capacity;
pub mod heat_flux;
pub mod inertia;
mod magnetic_angular_velocity;
mod magnetic_induction;
mod magnetic_moment;
pub mod mass;
mod momentum;
mod power;
mod temperature;
mod temperature_difference;
pub mod thermal_conductance;
mod thermal_conductivity;
mod torque;
pub mod vector;
mod velocity;
mod volume;

//支持向量的物理量
pub trait VectorQuantity: PhysicalQuantity {}

pub trait PhysicalQuantity: Any {
    fn as_any(&self) -> &dyn Any;

    fn is_zero(&self) -> bool;

    fn default_unit_value(&self) -> f64;

    fn set_value(&mut self, value: f64);

    /// 返回物理量名称和单位,如 "Distance (m)", "Velocity (m/s)"
    fn unit_display_name(&self) -> String;
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DistanceType {
    M,
    KM,
    LightYear,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum VelocityType {
    MPerSecond,
    KmPerHour,
    KmPerSecond,
    LightSpeed,
}
/// 距离物理量结构体
///
/// 表示空间中的距离,支持多种单位制
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::Distance;
///
/// let distance = Distance::from_m(100.0);
/// println!("距离: {} 米", distance.as_m());
/// ```
#[derive(Clone, Debug, PartialEq, Copy)]
pub struct Distance {
    default_type: DistanceType,
    v: f64,
}

/// 速度物理量结构体
///
/// 表示物体运动的快慢和方向,支持多种单位制
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::Velocity;
///
/// let velocity = Velocity::from_m_per_sec(10.0);
/// println!("速度: {} m/s", velocity.as_m_per_sec());
/// ```
#[derive(Clone, Debug, PartialEq, Copy)]
pub struct Velocity {
    default_type: VelocityType,
    v: f64,
}


/// 加速度物理量结构体
///
/// 表示速度变化的快慢,支持多种单位制
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::Acceleration;
///
/// let acceleration = Acceleration::from_g(1.0);
/// println!("加速度: {} g", acceleration.as_g());
/// ```
#[derive(Clone, Debug, PartialEq, Copy)]
pub struct Acceleration {
    default_type: AccelerationType,
    v: f64,
}

#[derive(Clone, Debug, PartialEq, Copy)]
pub enum AccelerationType {
    MPerSecond2,
    KmPerHour2,
    G,
}

#[derive(Clone, Debug, PartialEq, Copy)]
pub enum AngularType {
    Rad,
    Deg,
}

/// 角度物理量结构体
///
/// 表示角度大小,支持弧度和度数单位
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::Angular;
///
/// let angle = Angular::from_rad(std::f64::consts::PI);
/// println!("角度: {} 弧度", angle.as_rad());
/// ```
#[derive(Clone, Debug, PartialEq, Copy)]
pub struct Angular {
    default_type: AngularType,
    v: f64,
}

#[derive(Clone, Debug, PartialEq, Copy, Default)]
pub enum AngularVelocityType {
    #[default]
    RadperSecond,
    DegPerSecond,
    RadperHour,
    DegperHour,
}

/// 角速度物理量结构体
///
/// 表示角度变化的快慢,支持多种单位制
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::AngularVelocity;
///
/// let angular_velocity = AngularVelocity::from_rad_per_second(1.0);
/// println!("角速度: {} rad/s", angular_velocity.as_rad_per_second());
/// ```
#[derive(Clone, Debug, PartialEq, Copy)]
pub struct AngularVelocity {
    default_type: AngularVelocityType,
    v: f64,
}


#[derive(Clone, Debug, PartialEq, Copy)]
pub enum AngularAccelerationType {
    RadperSecond2,
    DegPerSecond2,
}

/// 角加速度物理量结构体
///
/// 表示角速度变化的快慢,支持多种单位制
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::AngularAcceleration;
///
/// let angular_acceleration = AngularAcceleration::from_rad_per_second2(1.0);
/// println!("角加速度: {} rad/s²", angular_acceleration.as_rad_per_second2());
/// ```
#[derive(Clone, Debug, PartialEq, Copy)]
pub struct AngularAcceleration {
    default_type: AngularAccelerationType,
    v: f64,
}

/// 系数物理量结构体
///
/// 表示无量纲的系数或比例因子
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::Coef;
///
/// let coefficient = Coef::new(0.5);
/// println!("系数: {}", coefficient.get_value());
/// ```
#[derive(Clone, Debug, PartialEq, PartialOrd, Copy)]
pub struct Coef {
    v: f64,
}

#[derive(Clone, Debug, PartialEq, Copy)]
pub enum MassType {
    Kg,
    g,
}

/// 质量物理量结构体
///
/// 表示物体的质量,支持千克和克单位
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::Mass;
///
/// let mass = Mass::from_kg(1.0);
/// println!("质量: {} kg", mass.as_kg());
/// ```
#[derive(Clone, Debug, PartialEq, Copy)]
pub struct Mass {
    default_type: MassType,
    pub v: f64,
}

#[derive(Clone, Debug, PartialEq, Copy)]
pub enum InertiaType {
    /// 千克·平方米(SI 基本单位)
    KgM2,
    /// 千克·平方毫米(工程图纸与 CAD 常用,也是 aods 的 J_kgmm2 单位)
    KgMm2,
}

/// 转动惯量(标量)
///
/// 描述刚体绕**某一指定轴**的转动惯性,量纲 kg·m²。
/// 这是标量形态:飞轮转子惯量、单轴转动惯量都属于它。
///
/// 完整描述刚体在任意轴向上的转动惯性需要 3×3 的转动惯量张量,
/// 标量是该张量沿某条主轴的投影。区分两者很重要:只有标量值时,
/// 姿态动力学只能按"惯量各向同性"处理。
///
/// 与 [`AngularMomentum`] / [`AngularVelocity`] 的关系:
/// `L = J·ω`,故 `AngularMomentum / AngularVelocity = Inertia`。
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::Inertia;
///
/// let j = Inertia::from_kg_m2(0.5);
/// println!("转动惯量: {} kg·m²", j.as_kg_m2());
///
/// // 工程图纸给的 kg·mm² 需除以 10^6
/// let j2 = Inertia::from_kg_mm2(500_000.0);
/// assert_eq!(j2.as_kg_m2(), 0.5);
/// ```
#[derive(Clone, Debug, PartialEq, Copy)]
pub struct Inertia {
    default_type: InertiaType,
    pub v: f64,
}

#[derive(Clone, Debug, PartialEq, Copy)]
pub enum AngularMomentumType {
    KgM2perSecond,  // 每秒1千克1平方米
    KgKm2perSecond, // 每秒1千克1平方公里
    Nms,            // 牛顿·米·秒 (N·m·s)
    MillNms,        // 毫牛顿·米·秒 (mN·m·s)
    MicroNms,       // 微牛顿·米·秒 (μN·m·s)
    NanoNms,        // 纳牛顿·米·秒 (nN·m·s)
}
/// 角动量物理量结构体
///
/// 表示物体绕轴旋转的动量,是质量、速度和距离的乘积
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::AngularMomentum;
///
/// let angular_momentum = AngularMomentum::from_kg_m2_per_second(1.0);
/// println!("角动量: {} kg·m²/s", angular_momentum.as_kg_m2_per_second());
/// ```
#[derive(Clone, Debug, PartialEq, Copy)]
pub struct AngularMomentum {
    default_type: AngularMomentumType,
    pub v: f64,
}

#[derive(Clone, Debug, PartialEq, Copy)]
pub enum MomentumType {
    KgMperSecond,  // 每秒1千克1米
    KgKmperSecond, // 每秒1千克1千米
}
/// 动量物理量结构体
///
/// 表示物体运动的动量,是质量和速度的乘积
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::Momentum;
///
/// let momentum = Momentum::from_kg_m_s(1.0);
/// println!("动量: {} kg·m/s", momentum.as_kg_m_s());
/// ```
#[derive(Clone, Debug, PartialEq, Copy)]
pub struct Momentum {
    default_type: MomentumType,
    pub v: f64,
}


/// 三维向量结构体
///
/// 表示三维空间中的向量,包含x、y、z三个分量
///
/// # 类型参数
/// * `T` - 向量分量的物理量类型,必须实现 `VectorQuantity` 和 `Default` trait
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::{Vector3, Distance};
///
/// let position = Vector3 {
///     x: Distance::from_m(1.0),
///     y: Distance::from_m(2.0),
///     z: Distance::from_m(3.0),
/// };
/// println!("位置: ({}, {}, {})", position.x.as_m(), position.y.as_m(), position.z.as_m());
/// ```
#[derive(Clone, Debug, PartialEq, Copy)]
pub struct Vector3<T: VectorQuantity + Default> {
    pub x: T,
    pub y: T,
    pub z: T,
}

impl<T: VectorQuantity + Default + Display> Display for Vector3<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "({}, {}, {})", self.x, self.y, self.z)
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AreaType {
    M2,
    KM2,
}

/// 面积物理量结构体
///
/// 表示二维空间的面积大小,支持平方米和平方千米单位
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::Area;
///
/// let area = Area::from_m2(100.0);
/// println!("面积: {} m²", area.as_m2());
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Area {
    default_type: AreaType,
    pub v: f64,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
pub enum MagneticInductionType {
    Gauss,
    #[default]
    Tesla,
    MillTesla,  // 毫
    MicroTesla, // 微
    NanoTesla,  //; 纳
    MillGauss,  // 毫
    KiloGauss,  // 千
}
/// 磁感应强度物理量结构体
///
/// 表示磁场强度,单位是特斯拉或高斯
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::MagneticInduction;
///
/// let magnetic_field = MagneticInduction::from_tesla(1.0);
/// println!("磁感应强度: {} T", magnetic_field.as_tesla());
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MagneticInduction {
    default_type: MagneticInductionType,
    pub v: f64,
}


#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MagneticMomentType {
    AM2,            // 安培·平方米 (A·m²)
    MillAM2,        // 毫安培·平方米 (mA·m²)
    MicroAM2,       // 微安培·平方米 (μA·m²)
    NanoAM2,        // 纳安培·平方米 (nA·m²)
    JPerTesla,      // 焦耳/特斯拉 (J/T)
    MillJPerTesla,  // 毫焦耳/特斯拉 (mJ/T)
    MicroJPerTesla, // 微焦耳/特斯拉 (μJ/T)
    NanoJPerTesla,  // 纳焦耳/特斯拉 (nJ/T)
}

/// 磁矩物理量结构体
///
/// 表示磁偶极子的磁矩,单位是安培·平方米或焦耳/特斯拉
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::MagneticMoment;
///
/// let magnetic_moment = MagneticMoment::from_am2(1.0);
/// println!("磁矩: {} A·m²", magnetic_moment.as_am2());
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MagneticMoment {
    default_type: MagneticMomentType,
    pub v: f64,
}


#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TorqueType {
    NM,      // 牛顿·米 (N·m)
    MillNM,  // 毫牛顿·米 (mN·m)
    MicroNM, // 微牛顿·米 (μN·m)
    NanoNM,  // 纳牛顿·米 (nN·m)
    KNM,     // 千牛顿·米 (kN·m)
    MNM,     // 兆牛顿·米 (MN·m)
}

/// 力矩物理量结构体
///
/// 表示力对物体产生的转动效应,单位是牛顿·米
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::Torque;
///
/// let torque = Torque::from_nm(10.0);
/// println!("力矩: {} N·m", torque.as_nm());
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Torque {
    default_type: TorqueType,
    pub v: f64,
}


#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum EnergyType {
    Joule,            // 焦耳 (J)
    MillJoule,        // 毫焦耳 (mJ)
    MicroJoule,       // 微焦耳 (μJ)
    NanoJoule,        // 纳焦耳 (nJ)
    KiloJoule,        // 千焦耳 (kJ)
    MegaJoule,        // 兆焦耳 (MJ)
    ElectronVolt,     // 电子伏特 (eV)
    KiloElectronVolt, // 千电子伏特 (keV)
    MegaElectronVolt, // 兆电子伏特 (MeV)
}

/// 能量物理量结构体
///
/// 表示物体做功的能力,单位是焦耳
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::Energy;
///
/// let energy = Energy::from_joule(100.0);
/// println!("能量: {} J", energy.as_joule());
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Energy {
    default_type: EnergyType,
    pub v: f64,
}


#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ForceType {
    Newton,      // 牛顿 (N)
    MillNewton,  // 毫牛顿 (mN)
    MicroNewton, // 微牛顿 (μN)
    NanoNewton,  // 纳牛顿 (nN)
    KiloNewton,  // 千牛顿 (kN)
    MegaNewton,  // 兆牛顿 (MN)
}

/// 力物理量结构体
///
/// 表示物体间的相互作用,单位是牛顿
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::Force;
///
/// let force = Force::from_newton(10.0);
/// println!("力: {} N", force.as_newton());
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Force {
    default_type: ForceType,
    pub v: f64,
}


#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PowerType {
    Watt,       // 瓦特 (W)
    MillWatt,   // 毫瓦特 (mW)
    MicroWatt,  // 微瓦特 (μW)
    NanoWatt,   // 纳瓦特 (nW)
    KiloWatt,   // 千瓦特 (kW)
    MegaWatt,   // 兆瓦特 (MW)
    HorsePower, // 马力 (hp)
}

/// 功率物理量结构体
///
/// 表示单位时间内做功的多少,单位是瓦特
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::Power;
///
/// let power = Power::from_watt(100.0);
/// println!("功率: {} W", power.as_watt());
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Power {
    default_type: PowerType,
    pub v: f64,
}


#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MagneticAngularVelocityType {
    TeslaRadPerSecond,      // 特斯拉·弧度/秒 (T·rad/s)
    MillTeslaRadPerSecond,  // 毫特斯拉·弧度/秒 (mT·rad/s)
    MicroTeslaRadPerSecond, // 微特斯拉·弧度/秒 (μT·rad/s)
    NanoTeslaRadPerSecond,  // 纳特斯拉·弧度/秒 (nT·rad/s)
    GaussRadPerSecond,      // 高斯·弧度/秒 (G·rad/s)
    MillGaussRadPerSecond,  // 毫高斯·弧度/秒 (mG·rad/s)
    KiloGaussRadPerSecond,  // 千高斯·弧度/秒 (kG·rad/s)
}

/// 磁角速度物理量结构体
///
/// 表示磁场中的角速度,单位是特斯拉·弧度/秒或高斯·弧度/秒
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::MagneticAngularVelocity;
///
/// let magnetic_angular_velocity = MagneticAngularVelocity::from_tesla_rad_per_second(1.0);
/// println!("磁角速度: {} T·rad/s", magnetic_angular_velocity.as_tesla_rad_per_second());
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MagneticAngularVelocity {
    default_type: MagneticAngularVelocityType,
    pub v: f64,
}


#[derive(Clone, Debug, PartialEq, Copy)]
pub enum VolumeType {
    M3,
    KM3,
}
/// 体积物理量结构体
///
/// 表示三维空间的体积大小,支持立方米和立方千米单位
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::Volume;
///
/// let volume = Volume::from_m3(1000.0);
/// println!("体积: {} m³", volume.as_m3());
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Volume {
    default_type: VolumeType,
    pub v: f64,
}

// ── 电学物理量 ───────────────────────────────────────────────────────────────

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ElectricCurrentType {
    A,
    MilliA,
    MicroA,
    KiloA,
}

/// 电流物理量结构体
///
/// 表示电荷流动的速率,单位是安培 (A)
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ElectricCurrent {
    default_type: ElectricCurrentType,
    pub v: f64,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ElectricPotentialType {
    V,
    MilliV,
    MicroV,
    KiloV,
}

/// 电压(电势差)物理量结构体
///
/// 表示两点间的电势差,单位是伏特 (V)
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ElectricPotential {
    default_type: ElectricPotentialType,
    pub v: f64,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ElectricResistanceType {
    Ohm,
    MillOhm,
    KiloOhm,
    MegaOhm,
}

/// 电阻物理量结构体
///
/// 表示导体对电流的阻碍能力,单位是欧姆 (Ω)
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ElectricResistance {
    default_type: ElectricResistanceType,
    pub v: f64,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ElectricChargeType {
    Coulomb,
    MilliCoulomb,
    MicroCoulomb,
    NanoCoulomb,
}

/// 电荷量物理量结构体
///
/// 表示物体所带的电荷量,单位是库仑 (C)
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ElectricCharge {
    default_type: ElectricChargeType,
    pub v: f64,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ElectricCapacitanceType {
    Farad,
    MilliFarad,
    MicroFarad,
    NanoFarad,
    PicoFarad,
}

/// 电容物理量结构体
///
/// 表示存储电荷的能力,单位是法拉 (F)
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ElectricCapacitance {
    default_type: ElectricCapacitanceType,
    pub v: f64,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ElectricConductanceType {
    Siemens,
    MilliSiemens,
    MicroSiemens,
}

/// 电导物理量结构体
///
/// 表示导体导电的能力(电阻的倒数),单位是西门子 (S)
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ElectricConductance {
    default_type: ElectricConductanceType,
    pub v: f64,
}

/// 温度(绝对温度)
///
/// 内部统一以开尔文存储,不保留构造时使用的单位。这是与库内其他物理量的
/// 一处**有意差异**:摄氏/华氏与开尔文之间是带偏移的仿射换算
/// (`T_K = T_C + 273.15`),若沿用"原始单位下的值 + 单位标记"的范式,
/// 每个 `as_*` 都要重复一遍偏移逻辑,极易漏。统一存 K 后,偏移只在构造
/// 和取值两处出现,内部运算不需要 `match`。
///
/// # 允许的运算
///
/// | 运算 | 结果 | 含义 |
/// |---|---|---|
/// | `T - T` | `TemperatureDifference` | 求温差,唯一有意义的减法 |
/// | `T + ΔT` | `Temperature` | 加热 |
/// | `T - ΔT` | `Temperature` | 冷却 |
/// | `T / T` | `Coef` | 温度比,如 Carnot 效率 `1 - Tc/Th` |
///
/// # 刻意不实现的运算
///
/// - `T + T`:两个位置温度之和不是温度,物理上无意义。
/// - `T * f64`:从摄氏构造时会产生严重违背直觉的结果 ——
///   `20°C` 内部是 `293.15 K`,乘 2 得 `586.3 K` 即 `313.15°C`,
///   而不是直觉上的 `40°C`。真需要时请显式写
///   `Temperature::from_kelvin(t.as_kelvin() * 2.0)`。
/// - `T * T`:输出应是 K²,库中没有也不应有这个量纲。
///
/// # 注意
///
/// 温度是标量量,**刻意不实现 [`VectorQuantity`]**,因此 `Vector3<Temperature>`
/// 在编译期即不可构造。空间温度梯度 ∇T 虽然是向量,但单位是 K/m,
/// 其元素类型不是温度本身。
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::Temperature;
///
/// let t = Temperature::from_celsius(20.0);
/// assert!((t.as_kelvin() - 293.15).abs() < 1e-9);
/// assert!((t.as_celsius() - 20.0).abs() < 1e-9);
///
/// // 与华氏互转
/// let f = Temperature::from_fahrenheit(212.0);
/// assert!((f.as_celsius() - 100.0).abs() < 1e-9);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
pub struct Temperature {
    /// 绝对温度,单位 K。私有字段:外部只能通过 `from_*` / `as_*` 访问,
    /// 保证偏移换算不会绕过。
    kelvin: f64,
}

/// 温度差(相对温度)
///
/// 与 [`Temperature`] 的唯一区别是**零点**:温度有偏移,温差没有。
///
/// - `Δ°C` 与 `ΔK` 数值**完全相同**(换算系数 1、偏移 0)
/// - `Δ°F` 与 `ΔK` 相差 `9/5`
///
/// # 为什么必须是独立类型
///
/// 若只保留一个温度类型,`G * T`(热导 × 温度)与 `G * ΔT`(热导 × 温差)
/// 在量纲上**都成立**(`W/K × K = W`),但数值可相差几十倍:
///
/// ```
/// # use zmatrix::physics::basic::{Temperature, TemperatureDifference};
/// let t1 = Temperature::from_celsius(30.0);   // 303.15 K
/// let t2 = Temperature::from_celsius(20.0);   // 293.15 K
///
/// // 正确:温差 10 K
/// let dt: TemperatureDifference = t1 - t2;
/// assert!((dt.as_kelvin() - 10.0).abs() < 1e-9);
///
/// // 若误把绝对温度当温差用,数值会是 303.15 而非 10,差 30 倍。
/// // 量纲检查对此无能为力 —— 只有类型系统能挡。
/// ```
///
/// 同样**刻意不实现 [`VectorQuantity`]**:梯度 ∇T 的单位是 K/m,不是 K。
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
pub struct TemperatureDifference {
    /// 温度差,单位 K。私有字段,理由同上。
    kelvin: f64,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum HeatFluxType {
    /// 瓦特每平方米(SI 导出单位)
    WattPerSquareMeter,
    /// 千瓦每平方米
    KiloWattPerSquareMeter,
    /// 毫瓦每平方厘米。文献与涂层数据手册常用;
    /// `1 mW/cm² = 10 W/m²`(注意不是 1e-3 的关系,分母是 cm² 不是 m²)
    MilliWattPerSquareCentiMeter,
}

/// 热流密度
///
/// **单位面积上的热功率**,量纲 W/m²。中文也叫「热通量」,但严格说 *flux*
/// 指通过某个面的总流量(W),*flux density* 才是每平方米的值(W/m²);
/// 工程上 `heat flux` 几乎一律指后者,本类型采用这一约定。
///
/// # 与热量、热功率的区别
///
/// | 量 | 单位 | 含义 | 本库类型 |
/// |---|---|---|---|
/// | 热量 Q | J | 累计能量 | [`Energy`] |
/// | 热功率 Q̇ | W | 单位时间的能量 | [`Power`] |
/// | 热流密度 q | W/m² | 单位时间、单位面积 | `HeatFlux` |
///
/// 密度与总量无关:两块各 1 m² 的板共承受 2000 W 热功率,但每块的
/// 热流密度仍是 1000 W/m²。热控设计关心后者 —— 它与材料耐受温度和
/// 涂层退化直接挂钩,与板子多大无关。
///
/// # 典型量级
///
/// - 太阳常数:1361 W/m²
/// - 地球红外辐照:约 230 W/m²
/// - 地球反照:0–400 W/m²,随轨道位置变化
/// - 多层隔热材料漏热:几 W/m²
///
/// # 为什么它是热学量里唯一的向量量
///
/// 热流有方向。太阳照到倾斜面上,实际吸收量为 `q · n̂`(点乘),
/// 与入射角余弦成正比。因此 `Vector3<HeatFlux>` 有意义,而
/// [`Temperature`] 与 [`TemperatureDifference`] 都不实现
/// [`VectorQuantity`] —— 温度是标量场,梯度 ∇T 虽是向量但单位是 K/m。
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::{Area, HeatFlux, Power};
///
/// // 太阳常数
/// let q = HeatFlux::from_w_per_m2(1361.0);
/// assert_eq!(q.as_w_per_m2(), 1361.0);
///
/// // 换算:涂层手册常给 mW/cm²
/// let q2 = HeatFlux::from_mw_per_cm2(1.0);
/// assert_eq!(q2.as_w_per_m2(), 10.0);
///
/// // 热流密度 × 面积 = 热功率
/// let area = Area::from_m2(2.0);
/// let power: Power = q * area;
/// assert_eq!(power.as_watt(), 2722.0);
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct HeatFlux {
    default_type: HeatFluxType,
    pub v: f64,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ThermalConductivityType {
    /// 瓦特每米开尔文(SI 导出单位)
    WattPerMeterKelvin,
    /// 千瓦每米开尔文
    KiloWattPerMeterKelvin,
    /// 毫瓦每厘米开尔文。隔热材料数据手册常用:
    /// 气凝胶、隔热毡的 k 常在 0.02–0.04 W/(m·K),用 W/(m·K) 写全是零。
    /// `1 mW/(cm·K) = 0.1 W/(m·K)`
    MilliWattPerCentiMeterKelvin,
}

/// 导热系数(也称热导率)
///
/// **材料本身的属性**:单位长度、单位温差下通过的热流密度,量纲 W/(m·K)。
/// 傅里叶定律的一维形式:`q = k · ΔT / L`。
///
/// # 与两个近名量的区分(中文术语极易混淆)
///
/// | 英文 | 中文 | 单位 | 层级 |
/// |---|---|---|---|
/// | `ThermalConductivity` | **导热系数**(热导率) | W/(m·K) | 材料属性 |
/// | `HeatTransferCoefficient` | 传热系数(表面传热系数) | W/(m²·K) | 表面对流 |
/// | `ThermalConductance` | 热导 | W/K | 构件级 |
///
/// - 与「传热系数」只差一个字,但单位多一个 m²:前者是材料内部导热的本领,
///   后者是表面对流换热的强弱,两者不可互换。
/// - 与「热导」也不同:热导是构件级的整体值,
///   等于 `导热系数 × 面积 ÷ 长度`。
///
/// # 与比热容的区别
///
/// 导热系数管「热传得多快」,比热容(`SpecificHeatCapacity`,尚未实现)管
/// 「热存得住多少」。两者量纲完全不同、可自由组合:隔热毡的 k 比铝小 6000 倍,
/// c 反而更大 —— 阻断传导的同时靠自身热容缓冲温度波动。
///
/// # 典型量级
///
/// | 材料 | k (W/(m·K)) |
/// |---|---|
/// | 铝 | 237 |
/// | 钛 | 22 |
/// | 隔热毡 | 0.04 |
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::{Distance, HeatFlux, TemperatureDifference, ThermalConductivity};
///
/// // 10 mm 厚的铝板,两面温差 20 K
/// let k = ThermalConductivity::from_w_per_m_k(237.0);
/// let thickness = Distance::from_m(0.01);
/// let dt = TemperatureDifference::from_celsius(20.0);
///
/// // 傅里叶定律:q = k·ΔT/L
/// let q = k.heat_flux(dt, thickness);
/// assert!((q.as_w_per_m2() - 474_000.0).abs() < 1e-6);
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ThermalConductivity {
    default_type: ThermalConductivityType,
    pub v: f64,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum HeatCapacityType {
    /// 焦耳每开尔文(SI 导出单位)
    JoulePerKelvin,
    /// 千焦每开尔文
    KiloJoulePerKelvin,
}

/// 热容
///
/// **整个物体**温度升高 1 K 所需的热量,量纲 J/K。
/// 显热公式:`Q = C · ΔT`。
///
/// # 与比热容的区别(中文只差一个「比」字)
///
/// | 英文 | 中文 | 单位 | 层级 |
/// |---|---|---|---|
/// | `HeatCapacity` | **热容** | J/K | 整个物体 |
/// | `SpecificHeatCapacity` | 比热容 | J/(kg·K) | 材料属性 |
///
/// 关系:`C = c · m`。热容是「这个物体存多少热」,比热容是「这种材料每千克存多少热」。
/// 比热容尚未实现。
///
/// # 与热导的区别
///
/// 热容管**储热**(`C · dT/dt`),热导 [`ThermalConductance`] 管**传热**(`G · ΔT`)。
/// 两者在热网络方程里分别占据左右两侧,量纲不同:
///
/// ```text
/// C · dT/dt = G · ΔT + Q̇
/// J/K · K/s   W/K · K     W        ← 三项都是 W
/// ```
///
/// # 为什么要用热容而不是比热容
///
/// 集总参数热网络里,每个节点是一个等温体,需要的是「这个节点整体存多少热」,
/// 而不是材料的单位质量属性。TD/SINDA 输出的 `CAPACITANCE` 就是本类型。
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::{HeatCapacity, TemperatureDifference, Energy};
///
/// // 10 kg 铝件,比热容 900 J/(kg·K)
/// let c = HeatCapacity::from_j_per_k(9000.0);
///
/// // 升温 20 K 需要多少热量
/// let q: Energy = c * TemperatureDifference::from_celsius(20.0);
/// assert_eq!(q.as_joule(), 180_000.0);
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct HeatCapacity {
    default_type: HeatCapacityType,
    pub v: f64,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ThermalConductanceType {
    /// 瓦特每开尔文(SI 导出单位)
    WattPerKelvin,
    /// 毫瓦每开尔文
    MilliWattPerKelvin,
}

/// 热导
///
/// **整条连接**两端温差 1 K 时通过的热功率,量纲 W/K。
/// 热网络公式:`Q̇ = G · ΔT`。
///
/// # 与导热系数的区别(名字相近,层级不同)
///
/// | 英文 | 中文 | 单位 | 层级 |
/// |---|---|---|---|
/// | `ThermalConductance` | **热导** | W/K | 整条构件 |
/// | `ThermalConductivity` | 导热系数 | W/(m·K) | 材料属性 |
///
/// 关系:`G = k · A / L`。热导已经包含了面积和长度,是「这根构件能过多少热」;
/// 导热系数只是材料本身的属性。
///
/// # 热导 vs 热阻
///
/// `R = 1/G`,量纲 K/W。热阻尚未实现,但热网络里两种写法等价:
/// 串联用热阻相加更直观,并联用热导相加更直观。
///
/// # 与热容的区别
///
/// 热导管**传热**(`G · ΔT`),热容 [`HeatCapacity`] 管**储热**(`C · dT/dt`)。
/// 前者决定节点之间耦合多强,后者决定节点温度变化多慢。
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::{Power, TemperatureDifference, ThermalConductance};
///
/// // 一条 12 W/K 的导热路径,两端温差 20 K
/// let g = ThermalConductance::from_w_per_k(12.0);
/// let q: Power = g * TemperatureDifference::from_celsius(20.0);
/// assert_eq!(q.as_watt(), 240.0);
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ThermalConductance {
    default_type: ThermalConductanceType,
    pub v: f64,
}


impl Default for Distance {
    fn default() -> Self {
        Distance::from_m(0.0)
    }
}

impl PhysicalQuantity for Distance {
    fn as_any(&self) -> &dyn Any {
        self
}
    fn is_zero(&self) -> bool {
        self.v == 0.0
    }

    fn default_unit_value(&self) -> f64 {
        self.as_m()
    }

    fn set_value(&mut self, value: f64) {
        self.v = value;
    }
    fn unit_display_name(&self) -> String {
        "Distance (m)".to_string()
    }
}

impl Default for Angular {
    fn default() -> Self {
        Angular::from_rad(0.0)
    }
}

impl PhysicalQuantity for Angular {
    fn as_any(&self) -> &dyn Any {
        self
}
    fn is_zero(&self) -> bool {
        self.v == 0.0
    }
    fn default_unit_value(&self) -> f64 {
        self.as_rad()
    }

    fn set_value(&mut self, value: f64) {
        self.v = value;
    }
    fn unit_display_name(&self) -> String {
        "Angular (rad)".to_string()
    }
}

impl Default for AngularVelocity {
    fn default() -> Self {
        AngularVelocity::from_rad_per_second(0.0)
    }
}

impl Div for AngularMomentum {
    type Output = Coef;
    fn div(self, rhs: Self) -> Self::Output {
        let v = self.default_unit_value() / rhs.default_unit_value();
        Coef::new(v)
    }
}

impl Default for Coef {
    fn default() -> Self {
        Coef::new(1.0)
    }
}

impl Default for AngularAcceleration {
    fn default() -> Self {
        AngularAcceleration::from_rad_per_second2(0.0)
    }
}

impl<T: VectorQuantity + Default> Default for Vector3<T> {
    fn default() -> Self {
        Vector3 {
            x: T::default(),
            y: T::default(),
            z: T::default(),
        }
    }
}

/// 从 f64 秒数创建 chrono::TimeDelta(支持负数)
pub fn time_delta_from_secs_f64(secs: f64) -> chrono::TimeDelta {
    let nanos = (secs * 1_000_000_000.0) as i64;
    chrono::TimeDelta::nanoseconds(nanos)
}

/// 将 chrono::TimeDelta 转换为 f64 秒数
pub fn time_delta_to_secs_f64(td: &chrono::TimeDelta) -> f64 {
    td.num_seconds() as f64 + td.subsec_nanos() as f64 * 1e-9
}


// Display impls for physical quantities — show f64 value only (unit is available via unit_display_name)

// Display impls for physical quantities — show f64 value (unit available via unit_display_name)
macro_rules! impl_display_physics {
    ($type:ty) => {
        impl std::fmt::Display for $type {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "{}", self.default_unit_value())
            }
        }
    };
}

impl_display_physics!(Distance);
impl_display_physics!(Velocity);
impl_display_physics!(Acceleration);
impl_display_physics!(Angular);
impl_display_physics!(AngularVelocity);
impl_display_physics!(AngularAcceleration);
impl_display_physics!(Coef);
impl_display_physics!(Mass);
impl_display_physics!(Momentum);
impl_display_physics!(AngularMomentum);
impl_display_physics!(Area);
impl_display_physics!(Volume);
impl_display_physics!(MagneticInduction);
impl_display_physics!(MagneticMoment);
impl_display_physics!(Torque);
impl_display_physics!(Energy);
impl_display_physics!(Force);
impl_display_physics!(Power);
impl_display_physics!(MagneticAngularVelocity);
impl_display_physics!(ElectricCurrent);
impl_display_physics!(ElectricPotential);
impl_display_physics!(ElectricResistance);
impl_display_physics!(ElectricCharge);
impl_display_physics!(ElectricCapacitance);
impl_display_physics!(ElectricConductance);
#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_relative_eq;
    #[test]
    fn test_as_any() {
        let g: &dyn PhysicalQuantity = &Acceleration::from_g(1.23);
        let _d = g.as_any().downcast_ref::<Acceleration>().unwrap();

        let g: &dyn PhysicalQuantity = &Area::from_m2(10.0);
        let _d = g.as_any().downcast_ref::<Area>().unwrap();

        let g: &dyn PhysicalQuantity = &Distance::from_m(10.0);
        let d = g.as_any().downcast_ref::<Distance>().unwrap();
        assert_eq!(d.default_type, DistanceType::M);

        let g: &dyn PhysicalQuantity = &Velocity::from_m_per_sec(10.0);
        let d = g.as_any().downcast_ref::<Velocity>().unwrap();
        assert_eq!(d.default_type, VelocityType::MPerSecond);

        let g: &dyn PhysicalQuantity = &Acceleration::from_g(1.23);
        let d = g.as_any().downcast_ref::<Acceleration>().unwrap();
        assert_eq!(d.default_type, AccelerationType::G);

        let g: &dyn PhysicalQuantity = &Angular::from_rad(1.23);
        let d = g.as_any().downcast_ref::<Angular>().unwrap();
        assert_eq!(d.default_type, AngularType::Rad);

        let g: &dyn PhysicalQuantity = &AngularVelocity::from_rad_per_hour(1.23);
        let d = g.as_any().downcast_ref::<AngularVelocity>().unwrap();
        assert_eq!(d.default_type, AngularVelocityType::RadperHour);

        let g: &dyn PhysicalQuantity = &Coef::new(1.23);
        let d = g.as_any().downcast_ref::<Coef>().unwrap();
        assert_eq!(d.v, 1.23);

        let g: &dyn PhysicalQuantity = &AngularAcceleration::from_rad_per_second2(1.23);
        let d = g.as_any().downcast_ref::<AngularAcceleration>().unwrap();
        assert_eq!(d.default_type, AngularAccelerationType::RadperSecond2);
    }

    #[test]
    fn test_acceleration_default() {
        let a = Acceleration::default();
        assert_eq!(0.0, a.as_m_per_s2());
    }

    #[test]
    fn test_angular_velocity_default() {
        let a = AngularVelocity::default();
        assert_eq!(0.0, a.as_rad_per_hour());

        let a = AngularAcceleration::default();
        assert_eq!(0.0, a.as_rad_per_second2());
    }

    #[test]
    fn test_angular_is_zero() {
        let a = Angular::from_rad(0.0);
        assert_eq!(true, a.is_zero());
        let a = Angular::from_rad(1.0);
        assert_eq!(false, a.is_zero());
    }

    #[test]
    fn test_volume_clone() {
        let a = Volume::from_m3(3.8);
        let b = a.clone();
        assert_relative_eq!(a.as_km3(), b.as_km3(), epsilon = 1e-8);
    }

    #[test]
    fn test_magnetic_moment_as_any() {
        let g: &dyn PhysicalQuantity = &MagneticMoment::from_am2(1.23);
        let d = g.as_any().downcast_ref::<MagneticMoment>().unwrap();
        assert_eq!(d.default_type, MagneticMomentType::AM2);
    }

    #[test]
    fn test_magnetic_moment_default() {
        let mm = MagneticMoment::default();
        assert_eq!(0.0, mm.as_am2());
    }

    #[test]
    fn test_magnetic_moment_is_zero() {
        let mm = MagneticMoment::from_am2(0.0);
        assert_eq!(true, mm.is_zero());
        let mm = MagneticMoment::from_am2(1.0);
        assert_eq!(false, mm.is_zero());
    }

    #[test]
    fn test_torque_as_any() {
        let g: &dyn PhysicalQuantity = &Torque::from_nm(1.23);
        let d = g.as_any().downcast_ref::<Torque>().unwrap();
        assert_eq!(d.default_type, TorqueType::NM);
    }

    #[test]
    fn test_torque_default() {
        let t = Torque::default();
        assert_eq!(0.0, t.as_nm());
    }

    #[test]
    fn test_torque_is_zero() {
        let t = Torque::from_nm(0.0);
        assert_eq!(true, t.is_zero());
        let t = Torque::from_nm(1.0);
        assert_eq!(false, t.is_zero());
    }

    #[test]
    fn test_energy_as_any() {
        let g: &dyn PhysicalQuantity = &Energy::from_joule(1.23);
        let d = g.as_any().downcast_ref::<Energy>().unwrap();
        assert_eq!(d.default_type, EnergyType::Joule);
    }

    #[test]
    fn test_energy_default() {
        let e = Energy::default();
        assert_eq!(0.0, e.as_joule());
    }

    #[test]
    fn test_energy_is_zero() {
        let e = Energy::from_joule(0.0);
        assert_eq!(true, e.is_zero());
        let e = Energy::from_joule(1.0);
        assert_eq!(false, e.is_zero());
    }

    #[test]
    fn test_angular_default_unit_value_is_rad() {
        // 默认单位为弧度时,default_unit_value 应等于 as_rad()
        let a_rad = Angular::from_rad(std::f64::consts::PI);
        assert_relative_eq!(a_rad.default_unit_value(), a_rad.as_rad(), epsilon = 1e-12);

        // 默认单位为度时,default_unit_value 也应返回弧度
        let a_deg = Angular::from_deg(180.0);
        assert_relative_eq!(a_deg.default_unit_value(), a_deg.as_rad(), epsilon = 1e-12);

        // 随机值覆盖(包括负值和小数),确保统一弧度输出
        let cases = vec![
            -720.0, -360.0, -45.5, 0.0, 12.34, 90.0, 123.456, 360.0, 720.0,
        ];
        for deg in cases {
            let a = Angular::from_deg(deg);
            assert_relative_eq!(a.default_unit_value(), a.as_rad(), epsilon = 1e-12);
        }
    }

    #[test]
    fn test_unit_display_name_and_display() {
        // 验证所有物理量的 unit_display_name 与 Display 实现

        assert_eq!(Distance::from_m(1.5).unit_display_name(), "Distance (m)");
        assert_eq!(format!("{}", Distance::from_m(2.5)), "2.5");

        assert_eq!(Velocity::from_m_per_sec(3.0).unit_display_name(), "Velocity (m/s)");
        assert_eq!(format!("{}", Velocity::from_km_per_h(36.0)), "10");

        assert_eq!(Acceleration::from_m_per_s2(9.8).unit_display_name(), "Acceleration (m/s²)");
        assert_eq!(format!("{}", Acceleration::from_g(1.0)), format!("{}", 9.80665));

        assert_eq!(Angular::from_rad(1.0).unit_display_name(), "Angular (rad)");
        assert_eq!(format!("{}", Angular::from_deg(180.0)), format!("{}", std::f64::consts::PI));

        assert_eq!(AngularVelocity::from_rad_per_second(2.0).unit_display_name(), "AngularVelocity (rad/s)");
        assert_eq!(format!("{}", AngularVelocity::from_rad_per_second(2.0)), "2");

        assert_eq!(AngularAcceleration::from_rad_per_second2(1.0).unit_display_name(), "AngularAcceleration (rad/s²)");
        assert_eq!(format!("{}", AngularAcceleration::from_rad_per_second2(3.0)), "3");

        assert_eq!(Coef::new(3.14).unit_display_name(), "Coef");
        assert_eq!(format!("{}", Coef::new(3.14)), "3.14");

        assert_eq!(Mass::from_kg(1.0).unit_display_name(), "Mass (kg)");
        assert_eq!(format!("{}", Mass::from_kg(5.0)), "5");

        assert_eq!(Momentum::from_kg_m_s(10.0).unit_display_name(), "Momentum (kg·m/s)");
        assert_eq!(format!("{}", Momentum::from_kg_m_s(10.0)), "10");

        assert_eq!(AngularMomentum::from_kg_m2_per_second(100.0).unit_display_name(), "AngularMomentum (kg·m²/s)");
        assert_eq!(format!("{}", AngularMomentum::from_nms(50.0)), "50");

        assert_eq!(Area::from_m2(4.0).unit_display_name(), "Area (m²)");
        assert_eq!(format!("{}", Area::from_m2(12.0)), "12");

        assert_eq!(Volume::from_m3(8.0).unit_display_name(), "Volume (m³)");
        assert_eq!(format!("{}", Volume::from_m3(8.0)), "8");

        assert_eq!(MagneticInduction::from_tesla(1.0).unit_display_name(), "MagneticInduction (T)");
        assert_eq!(format!("{}", MagneticInduction::from_gauss(10000.0)), "1");

        assert_eq!(MagneticMoment::from_am2(1.0).unit_display_name(), "MagneticMoment (A·m²)");
        assert_eq!(format!("{}", MagneticMoment::from_am2(2.0)), "2");

        assert_eq!(Torque::from_nm(10.0).unit_display_name(), "Torque (N·m)");
        assert_eq!(format!("{}", Torque::from_nm(0.0)), "0");

        assert_eq!(Energy::from_joule(42.0).unit_display_name(), "Energy (J)");
        assert_eq!(format!("{}", Energy::from_joule(0.0)), "0");

        assert_eq!(Force::from_newton(100.0).unit_display_name(), "Force (N)");
        assert_eq!(format!("{}", Force::from_newton(100.0)), "100");

        assert_eq!(Power::from_watt(60.0).unit_display_name(), "Power (W)");
        assert_eq!(format!("{}", Power::from_watt(60.0)), "60");

        assert_eq!(MagneticAngularVelocity::from_tesla_rad_per_second(1.0).unit_display_name(), "MagneticAngularVelocity (T·rad/s)");
        assert_eq!(format!("{}", MagneticAngularVelocity::from_tesla_rad_per_second(1.0)), "1");

        // 电学物理量
        assert_eq!(ElectricCurrent::from_a(2.5).unit_display_name(), "ElectricCurrent (A)");
        assert_eq!(format!("{}", ElectricCurrent::from_a(2.5)), "2.5");

        assert_eq!(ElectricPotential::from_v(12.0).unit_display_name(), "ElectricPotential (V)");
        assert_eq!(format!("{}", ElectricPotential::from_v(12.0)), "12");

        assert_eq!(ElectricResistance::from_ohm(100.0).unit_display_name(), "ElectricResistance (Ohm)");
        assert_eq!(format!("{}", ElectricResistance::from_ohm(100.0)), "100");

        assert_eq!(ElectricCharge::from_coulomb(5.0).unit_display_name(), "ElectricCharge (C)");
        assert_eq!(format!("{}", ElectricCharge::from_coulomb(5.0)), "5");

        assert_eq!(ElectricCapacitance::from_farad(0.001).unit_display_name(), "ElectricCapacitance (F)");
        assert_eq!(format!("{}", ElectricCapacitance::from_farad(0.001)), "0.001");

        assert_eq!(ElectricConductance::from_siemens(0.01).unit_display_name(), "ElectricConductance (S)");
        assert_eq!(format!("{}", ElectricConductance::from_siemens(0.01)), "0.01");
    }

    #[test]
    fn test_vector3_display() {
        let v: Vector3<Distance> = Vector3::new(
            Distance::from_m(1.0),
            Distance::from_m(2.0),
            Distance::from_m(3.0),
        );
        assert_eq!(format!("{}", v), "(1, 2, 3)");
    }
}

// 手动实现 VectorQuantity trait 给所有支持向量的物理量
impl VectorQuantity for Distance {}
impl VectorQuantity for Velocity {}
impl VectorQuantity for Acceleration {}
impl VectorQuantity for Angular {}
impl VectorQuantity for AngularVelocity {}
impl VectorQuantity for AngularAcceleration {}
impl VectorQuantity for Coef {}
impl VectorQuantity for AngularMomentum {}
impl VectorQuantity for Momentum {}
impl VectorQuantity for MagneticInduction {}
impl VectorQuantity for MagneticMoment {}
impl VectorQuantity for Torque {}
impl VectorQuantity for Force {}
impl VectorQuantity for MagneticAngularVelocity {}
impl VectorQuantity for HeatFlux {}