anvilkit-core 0.1.0

Core types, math library, and time system for AnvilKit game engine
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
//! # 数学常量和工具函数
//! 
//! 提供游戏开发中常用的数学常量、转换函数和工具函数。
//! 
//! ## 常量分类
//! 
//! - **角度转换**: 弧度和角度之间的转换常量
//! - **物理常量**: 重力、阻尼等物理模拟常量
//! - **几何常量**: 常用的几何数值
//! - **颜色常量**: 预定义的颜色值
//! 
//! ## 使用示例
//! 
//! ```rust
//! use anvilkit_core::math::constants::*;
//! use glam::Vec3;
//! 
//! // 角度转换
//! let radians = 90.0 * DEG_TO_RAD;
//! let degrees = std::f32::consts::PI * RAD_TO_DEG;
//! 
//! // 物理模拟
//! let gravity = Vec3::new(0.0, -GRAVITY_EARTH, 0.0);
//! 
//! // 几何计算
//! let radius = 5.0;
//! let circle_area = std::f32::consts::PI * radius * radius;
//! ```

use glam::{Vec2, Vec3, Vec4};

// ============================================================================
// 角度和弧度转换常量
// ============================================================================

/// 将角度转换为弧度的乘数 (π/180)
pub const DEG_TO_RAD: f32 = std::f32::consts::PI / 180.0;

/// 将弧度转换为角度的乘数 (180/π)
pub const RAD_TO_DEG: f32 = 180.0 / std::f32::consts::PI;

/// 半圆的弧度值 (π)
pub const HALF_CIRCLE_RAD: f32 = std::f32::consts::PI;

/// 四分之一圆的弧度值 (π/2)
pub const QUARTER_CIRCLE_RAD: f32 = std::f32::consts::FRAC_PI_2;

/// 完整圆的弧度值 (2π)
pub const FULL_CIRCLE_RAD: f32 = std::f32::consts::TAU;

// ============================================================================
// 物理常量
// ============================================================================

/// 地球表面重力加速度 (m/s²)
pub const GRAVITY_EARTH: f32 = 9.80665;

/// 月球表面重力加速度 (m/s²)
pub const GRAVITY_MOON: f32 = 1.625;

/// 火星表面重力加速度 (m/s²)
pub const GRAVITY_MARS: f32 = 3.711;

/// 标准大气压 (Pa)
pub const ATMOSPHERIC_PRESSURE: f32 = 101325.0;

/// 空气密度 (kg/m³) - 海平面,15°C
pub const AIR_DENSITY: f32 = 1.225;

/// 水的密度 (kg/m³) - 4°C
pub const WATER_DENSITY: f32 = 1000.0;

/// 光速 (m/s)
pub const SPEED_OF_LIGHT: f32 = 299_792_458.0;

/// 声速 (m/s) - 20°C,干燥空气
pub const SPEED_OF_SOUND: f32 = 343.0;

// ============================================================================
// 几何和数学常量
// ============================================================================

/// 黄金比例 (φ = (1 + √5) / 2)
pub const GOLDEN_RATIO: f32 = 1.618033988749;

/// 黄金比例的倒数 (1/φ)
pub const GOLDEN_RATIO_INVERSE: f32 = 0.618033988749;

/// 欧拉数 (e)
pub const EULER: f32 = std::f32::consts::E;

/// 自然对数的底数 (ln(2))
pub const LN_2: f32 = std::f32::consts::LN_2;

/// 自然对数的底数 (ln(10))
pub const LN_10: f32 = std::f32::consts::LN_10;

/// 平方根 2
pub const SQRT_2: f32 = std::f32::consts::SQRT_2;

/// 平方根 3
pub const SQRT_3: f32 = 1.732050807569;

/// 平方根 5
pub const SQRT_5: f32 = 2.236067977499;

// ============================================================================
// 浮点数精度常量
// ============================================================================

/// 单精度浮点数的机器精度
pub const F32_EPSILON: f32 = f32::EPSILON;

/// 用于比较的小数值
pub const SMALL_NUMBER: f32 = 1e-6;

/// 用于比较的极小数值
pub const TINY_NUMBER: f32 = 1e-8;

/// 用于角度比较的小数值(约 0.01 度)
pub const ANGLE_EPSILON: f32 = 0.0001745329;

// ============================================================================
// 常用向量常量
// ============================================================================

/// 2D 向量常量
pub mod vec2 {
    use super::*;
    
    /// 零向量
    pub const ZERO: Vec2 = Vec2::ZERO;
    
    /// 单位向量
    pub const ONE: Vec2 = Vec2::ONE;
    
    /// X 轴单位向量
    pub const X: Vec2 = Vec2::X;
    
    /// Y 轴单位向量
    pub const Y: Vec2 = Vec2::Y;
    
    /// 负 X 轴单位向量
    pub const NEG_X: Vec2 = Vec2::NEG_X;
    
    /// 负 Y 轴单位向量
    pub const NEG_Y: Vec2 = Vec2::NEG_Y;
    
    /// 右方向(正 X)
    pub const RIGHT: Vec2 = Vec2::X;
    
    /// 左方向(负 X)
    pub const LEFT: Vec2 = Vec2::NEG_X;
    
    /// 上方向(正 Y)
    pub const UP: Vec2 = Vec2::Y;
    
    /// 下方向(负 Y)
    pub const DOWN: Vec2 = Vec2::NEG_Y;
}

/// 3D 向量常量
pub mod vec3 {
    use super::*;
    
    /// 零向量
    pub const ZERO: Vec3 = Vec3::ZERO;
    
    /// 单位向量
    pub const ONE: Vec3 = Vec3::ONE;
    
    /// X 轴单位向量
    pub const X: Vec3 = Vec3::X;
    
    /// Y 轴单位向量
    pub const Y: Vec3 = Vec3::Y;
    
    /// Z 轴单位向量
    pub const Z: Vec3 = Vec3::Z;
    
    /// 负 X 轴单位向量
    pub const NEG_X: Vec3 = Vec3::NEG_X;
    
    /// 负 Y 轴单位向量
    pub const NEG_Y: Vec3 = Vec3::NEG_Y;
    
    /// 负 Z 轴单位向量
    pub const NEG_Z: Vec3 = Vec3::NEG_Z;
    
    /// 右方向(正 X)
    pub const RIGHT: Vec3 = Vec3::X;
    
    /// 左方向(负 X)
    pub const LEFT: Vec3 = Vec3::NEG_X;
    
    /// 上方向(正 Y)
    pub const UP: Vec3 = Vec3::Y;
    
    /// 下方向(负 Y)
    pub const DOWN: Vec3 = Vec3::NEG_Y;
    
    /// 前方向(负 Z,右手坐标系)
    pub const FORWARD: Vec3 = Vec3::NEG_Z;
    
    /// 后方向(正 Z)
    pub const BACKWARD: Vec3 = Vec3::Z;
}

// ============================================================================
// 颜色常量 (RGBA)
// ============================================================================

/// 颜色常量模块
pub mod colors {
    use super::*;
    
    /// 透明色
    pub const TRANSPARENT: Vec4 = Vec4::new(0.0, 0.0, 0.0, 0.0);
    
    /// 白色
    pub const WHITE: Vec4 = Vec4::new(1.0, 1.0, 1.0, 1.0);
    
    /// 黑色
    pub const BLACK: Vec4 = Vec4::new(0.0, 0.0, 0.0, 1.0);
    
    /// 红色
    pub const RED: Vec4 = Vec4::new(1.0, 0.0, 0.0, 1.0);
    
    /// 绿色
    pub const GREEN: Vec4 = Vec4::new(0.0, 1.0, 0.0, 1.0);
    
    /// 蓝色
    pub const BLUE: Vec4 = Vec4::new(0.0, 0.0, 1.0, 1.0);
    
    /// 黄色
    pub const YELLOW: Vec4 = Vec4::new(1.0, 1.0, 0.0, 1.0);
    
    /// 青色
    pub const CYAN: Vec4 = Vec4::new(0.0, 1.0, 1.0, 1.0);
    
    /// 洋红色
    pub const MAGENTA: Vec4 = Vec4::new(1.0, 0.0, 1.0, 1.0);
    
    /// 橙色
    pub const ORANGE: Vec4 = Vec4::new(1.0, 0.5, 0.0, 1.0);
    
    /// 紫色
    pub const PURPLE: Vec4 = Vec4::new(0.5, 0.0, 1.0, 1.0);
    
    /// 灰色
    pub const GRAY: Vec4 = Vec4::new(0.5, 0.5, 0.5, 1.0);
    
    /// 浅灰色
    pub const LIGHT_GRAY: Vec4 = Vec4::new(0.75, 0.75, 0.75, 1.0);
    
    /// 深灰色
    pub const DARK_GRAY: Vec4 = Vec4::new(0.25, 0.25, 0.25, 1.0);
}

// ============================================================================
// 工具函数
// ============================================================================

/// 将角度转换为弧度
/// 
/// # 示例
/// 
/// ```rust
/// use anvilkit_core::math::constants::degrees_to_radians;
/// 
/// let radians = degrees_to_radians(90.0);
/// assert!((radians - std::f32::consts::FRAC_PI_2).abs() < 1e-6);
/// ```
pub fn degrees_to_radians(degrees: f32) -> f32 {
    degrees * DEG_TO_RAD
}

/// 将弧度转换为角度
/// 
/// # 示例
/// 
/// ```rust
/// use anvilkit_core::math::constants::radians_to_degrees;
/// 
/// let degrees = radians_to_degrees(std::f32::consts::PI);
/// assert!((degrees - 180.0).abs() < 1e-6);
/// ```
pub fn radians_to_degrees(radians: f32) -> f32 {
    radians * RAD_TO_DEG
}

/// 将角度标准化到 [0, 360) 范围
/// 
/// # 示例
/// 
/// ```rust
/// use anvilkit_core::math::constants::normalize_degrees;
/// 
/// assert_eq!(normalize_degrees(450.0), 90.0);
/// assert_eq!(normalize_degrees(-90.0), 270.0);
/// ```
pub fn normalize_degrees(degrees: f32) -> f32 {
    let mut result = degrees % 360.0;
    if result < 0.0 {
        result += 360.0;
    }
    result
}

/// 将弧度标准化到 [0, 2π) 范围
/// 
/// # 示例
/// 
/// ```rust
/// use anvilkit_core::math::constants::normalize_radians;
/// 
/// let normalized = normalize_radians(3.0 * std::f32::consts::PI);
/// assert!((normalized - std::f32::consts::PI).abs() < 1e-6);
/// ```
pub fn normalize_radians(radians: f32) -> f32 {
    let mut result = radians % FULL_CIRCLE_RAD;
    if result < 0.0 {
        result += FULL_CIRCLE_RAD;
    }
    result
}

/// 检查两个浮点数是否近似相等
/// 
/// # 参数
/// 
/// - `a`, `b`: 要比较的数值
/// - `epsilon`: 容差值,默认使用 `SMALL_NUMBER`
/// 
/// # 示例
/// 
/// ```rust
/// use anvilkit_core::math::constants::approximately_equal;
/// 
/// assert!(approximately_equal(0.1 + 0.2, 0.3, None));
/// assert!(!approximately_equal(1.0, 2.0, None));
/// ```
pub fn approximately_equal(a: f32, b: f32, epsilon: Option<f32>) -> bool {
    let eps = epsilon.unwrap_or(SMALL_NUMBER);
    (a - b).abs() <= eps
}

/// 检查浮点数是否接近零
/// 
/// # 示例
/// 
/// ```rust
/// use anvilkit_core::math::constants::is_nearly_zero;
/// 
/// assert!(is_nearly_zero(1e-7));
/// assert!(!is_nearly_zero(0.1));
/// ```
pub fn is_nearly_zero(value: f32) -> bool {
    value.abs() <= SMALL_NUMBER
}

/// 安全的平方根函数,确保输入非负
/// 
/// # 示例
/// 
/// ```rust
/// use anvilkit_core::math::constants::safe_sqrt;
/// 
/// assert_eq!(safe_sqrt(4.0), 2.0);
/// assert_eq!(safe_sqrt(-1.0), 0.0); // 负数返回 0
/// ```
pub fn safe_sqrt(value: f32) -> f32 {
    if value < 0.0 {
        0.0
    } else {
        value.sqrt()
    }
}

/// 计算两点之间的距离
/// 
/// # 示例
/// 
/// ```rust
/// use anvilkit_core::math::constants::distance_2d;
/// use glam::Vec2;
/// 
/// let dist = distance_2d(Vec2::ZERO, Vec2::new(3.0, 4.0));
/// assert_eq!(dist, 5.0); // 3-4-5 三角形
/// ```
pub fn distance_2d(a: Vec2, b: Vec2) -> f32 {
    (b - a).length()
}

/// 计算两点之间的距离(3D)
pub fn distance_3d(a: Vec3, b: Vec3) -> f32 {
    (b - a).length()
}

/// 计算两点之间的距离的平方(避免开方运算)
/// 
/// 用于性能敏感的距离比较。
pub fn distance_squared_2d(a: Vec2, b: Vec2) -> f32 {
    (b - a).length_squared()
}

/// 计算两点之间的距离的平方(3D)
pub fn distance_squared_3d(a: Vec3, b: Vec3) -> f32 {
    (b - a).length_squared()
}

#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_relative_eq;

    #[test]
    fn test_angle_conversion() {
        assert_relative_eq!(degrees_to_radians(90.0), std::f32::consts::FRAC_PI_2, epsilon = 1e-6);
        assert_relative_eq!(degrees_to_radians(180.0), std::f32::consts::PI, epsilon = 1e-6);
        assert_relative_eq!(radians_to_degrees(std::f32::consts::PI), 180.0, epsilon = 1e-6);
    }

    #[test]
    fn test_angle_normalization() {
        assert_eq!(normalize_degrees(450.0), 90.0);
        assert_eq!(normalize_degrees(-90.0), 270.0);
        assert_eq!(normalize_degrees(0.0), 0.0);
        assert_eq!(normalize_degrees(360.0), 0.0);
        
        let normalized = normalize_radians(3.0 * std::f32::consts::PI);
        assert_relative_eq!(normalized, std::f32::consts::PI, epsilon = 1e-6);
    }

    #[test]
    fn test_approximately_equal() {
        assert!(approximately_equal(0.1 + 0.2, 0.3, None));
        assert!(approximately_equal(1.0, 1.0000001, Some(1e-5)));
        assert!(!approximately_equal(1.0, 2.0, None));
    }

    #[test]
    fn test_is_nearly_zero() {
        assert!(is_nearly_zero(1e-7));
        assert!(is_nearly_zero(0.0));
        assert!(!is_nearly_zero(0.1));
        assert!(!is_nearly_zero(-0.1));
    }

    #[test]
    fn test_safe_sqrt() {
        assert_eq!(safe_sqrt(4.0), 2.0);
        assert_eq!(safe_sqrt(0.0), 0.0);
        assert_eq!(safe_sqrt(-1.0), 0.0);
    }

    #[test]
    fn test_distance_functions() {
        let a = Vec2::ZERO;
        let b = Vec2::new(3.0, 4.0);
        
        assert_eq!(distance_2d(a, b), 5.0);
        assert_eq!(distance_squared_2d(a, b), 25.0);
        
        let a3 = Vec3::ZERO;
        let b3 = Vec3::new(1.0, 2.0, 2.0);
        
        assert_eq!(distance_3d(a3, b3), 3.0);
        assert_eq!(distance_squared_3d(a3, b3), 9.0);
    }

    #[test]
    fn test_constants() {
        // 测试一些重要常量的值
        assert_relative_eq!(GOLDEN_RATIO, 1.618033988749, epsilon = 1e-6);
        assert_relative_eq!(GOLDEN_RATIO * GOLDEN_RATIO_INVERSE, 1.0, epsilon = 1e-6);
        assert!((DEG_TO_RAD * RAD_TO_DEG - 1.0).abs() < 1e-6);
    }

    #[test]
    fn test_vector_constants() {
        assert_eq!(vec2::RIGHT, Vec2::new(1.0, 0.0));
        assert_eq!(vec2::UP, Vec2::new(0.0, 1.0));
        assert_eq!(vec3::FORWARD, Vec3::new(0.0, 0.0, -1.0));
        assert_eq!(vec3::UP, Vec3::new(0.0, 1.0, 0.0));
    }

    #[test]
    fn test_color_constants() {
        assert_eq!(colors::WHITE, Vec4::new(1.0, 1.0, 1.0, 1.0));
        assert_eq!(colors::BLACK, Vec4::new(0.0, 0.0, 0.0, 1.0));
        assert_eq!(colors::TRANSPARENT, Vec4::new(0.0, 0.0, 0.0, 0.0));
    }

    #[test]
    fn test_smoothstep_function() {
        use crate::math::interpolation::smoothstep;

        let result = smoothstep(0.5);
        assert_relative_eq!(result, 0.5, epsilon = 1e-6);
    }

    #[test]
    fn test_normalize_degrees_edge_cases() {
        assert_relative_eq!(normalize_degrees(720.0), 0.0, epsilon = 1e-6);
        assert_relative_eq!(normalize_degrees(-360.0), 0.0, epsilon = 1e-6);
        assert_relative_eq!(normalize_degrees(180.0), 180.0, epsilon = 1e-6);
        assert_relative_eq!(normalize_degrees(-180.0), 180.0, epsilon = 1e-6);
    }

    #[test]
    fn test_normalize_radians_edge_cases() {
        assert_relative_eq!(normalize_radians(0.0), 0.0, epsilon = 1e-6);
        assert_relative_eq!(
            normalize_radians(-std::f32::consts::PI),
            std::f32::consts::PI,
            epsilon = 1e-5
        );
    }

    #[test]
    fn test_approximately_equal_custom_epsilon() {
        assert!(approximately_equal(1.0, 1.001, Some(0.01)));
        assert!(!approximately_equal(1.0, 1.001, Some(0.0001)));
    }

    #[test]
    fn test_distance_squared_performance() {
        // 距离平方应始终等于距离的平方
        let a = Vec2::new(1.0, 2.0);
        let b = Vec2::new(4.0, 6.0);
        let dist = distance_2d(a, b);
        let dist_sq = distance_squared_2d(a, b);
        assert_relative_eq!(dist * dist, dist_sq, epsilon = 1e-6);
    }

    #[test]
    fn test_distance_same_point() {
        assert_eq!(distance_2d(Vec2::ONE, Vec2::ONE), 0.0);
        assert_eq!(distance_3d(Vec3::ONE, Vec3::ONE), 0.0);
        assert_eq!(distance_squared_2d(Vec2::ONE, Vec2::ONE), 0.0);
        assert_eq!(distance_squared_3d(Vec3::ONE, Vec3::ONE), 0.0);
    }

    #[test]
    fn test_precision_constants() {
        assert!(F32_EPSILON > 0.0);
        assert!(SMALL_NUMBER > 0.0);
        assert!(TINY_NUMBER > 0.0);
        assert!(SMALL_NUMBER > TINY_NUMBER);
        assert!(F32_EPSILON < SMALL_NUMBER);
    }
}