aada 0.1.1

纯 Rust 的 2D 骨骼动画引擎,兼容 Spine 4.x 导出格式(JSON + atlas)。求解到分层 Mesh 与各 Mesh 渲染设置为止,之后交给渲染器。
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
//! 类型化索引基础设施:解析期把名称一次性映射为强类型索引,运行时零字符串查找。
//!
//! - [`macro@crate::new_index!`] 宏生成强类型索引(如 `BoneIdx` / `MeshIdx`),底层是 [`RawIndex`]。
//! - [`NameMap`]:名称 -> 索引 + Vec 数据存储,提供索引/名称/数据的三向访问。
//! - [`TypedIndexVec`]:按索引对齐的 Vec 数据(如 `Pose` 的每骨骼变换),支持"无效"空状态。

use crate::error::Error;
use std::{
    collections::HashMap,
    fmt::Debug,
    marker::PhantomData,
    ops::{Index, IndexMut},
};

#[cfg(feature = "bevy_reflect")]
pub use bevy::RawIndex;
#[cfg(feature = "bevy_reflect")]
mod bevy {
    use std::fmt::Debug;

    use bevy_reflect::prelude::*;

    /// do not use directly, use new_index! macro to define new index types
    // 反射模式下安全性会被破坏,但是这是不可避免的,为了方便调试必须实现Default
    #[derive(Reflect, Clone, Copy, PartialEq, Eq, Hash, Default, PartialOrd, Ord)]
    #[reflect(Default)]
    pub struct RawIndex(usize);
    impl RawIndex {
        pub fn as_index(&self) -> usize {
            self.0
        }
        /// # Safety
        /// 手动构造时必须保证 index 是从有效数据获得的,
        /// 一般来自相同类型的 as_index 方法,并且需要保证是从同一个容器对象获取的
        pub unsafe fn from_index(index: usize) -> Self {
            Self(index)
        }
    }
    // #[test]
    // fn _a() {
    //     let rd: ReflectDefault = FromType::<RawIndex>::from_type();
    //     dbg!(rd.default());
    // }

    impl Debug for RawIndex {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "{}", self.as_index())
        }
    }
}
#[cfg(not(feature = "bevy_reflect"))]
pub use common_raw_index::RawIndex;
#[cfg(not(feature = "bevy_reflect"))]
mod common_raw_index {
    use std::fmt::Debug;
    use std::num::NonZero;

    /// do not use directly, use new_index! macro to define new index types
    #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
    pub struct RawIndex(NonZero<usize>);
    impl RawIndex {
        pub fn as_index(&self) -> usize {
            self.0.get() - 1
        }
        /// # Safety
        /// 手动构造时必须保证 index 是从有效数据获得的,
        /// 一般来自相同类型的 as_index 方法,并且需要保证是从同一个容器对象获取的
        pub unsafe fn from_index(index: usize) -> Self {
            Self(unsafe { NonZero::new_unchecked(index + 1) })
        }
    }
    impl Debug for RawIndex {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "{}", self.as_index())
        }
    }
}

/// 生成强类型索引类型的宏。
///
/// 生成的类型包装 [`RawIndex`] 并实现 [`AsIndex`]、`Display`、拷贝/比较/哈希等 trait。
/// 用法:`new_index!(BoneIdx)` 或一次声明多个 `new_index!(A, B, C)`。
#[macro_export]
macro_rules! new_index {
    ($name:ident) => {
        #[cfg(feature = "bevy_reflect")]
        use bevy_reflect::prelude::ReflectDefault; // 反射模式下需要用到这个 trait,即使会造成命名冲突也引用(正常不该开反射模式)
        #[cfg_attr(
            feature = "bevy_reflect",
            derive(::bevy_reflect::Reflect, ::core::default::Default)
        )]
        #[derive(
            ::core::fmt::Debug,
            ::core::clone::Clone,
            ::core::marker::Copy,
            ::core::cmp::PartialEq,
            ::core::cmp::Eq,
            ::core::hash::Hash,
            ::core::cmp::PartialOrd,
            ::core::cmp::Ord,
        )]
        #[cfg_attr(feature = "bevy_reflect", reflect(Default))]
        pub struct $name($crate::custom_index::RawIndex);

        unsafe impl $crate::custom_index::AsIndex for $name {
            fn as_index(&self) -> ::core::primitive::usize {
                self.0.as_index()
            }
            unsafe fn from_index(index: ::core::primitive::usize) -> Self {
                Self(unsafe { $crate::custom_index::RawIndex::from_index(index) })
            }
        }

        impl ::core::fmt::Display for $name {
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                ::core::fmt::Debug::fmt(self, f)
            }
        }
    };
    ($($name:ident),*) => {
        #[cfg(feature = "bevy_reflect")]
        use bevy_reflect::prelude::ReflectDefault; // 反射模式下需要用到这个 trait,即使会造成命名冲突也引用(正常不该开反射模式)
        $(
        #[cfg_attr(
            feature = "bevy_reflect",
            derive(::bevy_reflect::Reflect, ::core::default::Default)
        )]
        #[derive(
            ::core::fmt::Debug,
            ::core::clone::Clone,
            ::core::marker::Copy,
            ::core::cmp::PartialEq,
            ::core::cmp::Eq,
            ::core::hash::Hash,
            ::core::cmp::PartialOrd,
            ::core::cmp::Ord,
        )]
        #[cfg_attr(feature = "bevy_reflect", reflect(Default))]
        pub struct $name($crate::custom_index::RawIndex);

        unsafe impl $crate::custom_index::AsIndex for $name {
            fn as_index(&self) -> ::core::primitive::usize {
                self.0.as_index()
            }
            unsafe fn from_index(index: ::core::primitive::usize) -> Self {
                Self(unsafe { $crate::custom_index::RawIndex::from_index(index) })
            }
        }

        impl ::core::fmt::Display for $name {
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                ::core::fmt::Debug::fmt(self, f)
            }
        }
        )*
    };
}

/// # Safety
/// 对于每个from_index构造的对象,整个生命周期内as_index必须返回对应的usize值
pub unsafe trait AsIndex {
    fn as_index(&self) -> usize;
    /// # Safety
    /// 手动构造时必须保证 index 是从有效数据获得的,
    /// 一般来自相同类型的 as_index 方法,并且需要保证是从同一个容器对象获取的
    unsafe fn from_index(index: usize) -> Self;
}

/// 名称 -> 强类型索引的映射容器,数据存储在平行 Vec 中。
///
/// 用于解析期一次性把名称(骨骼/slot/皮肤/网格/动画名等)映射为类型化索引,
/// 运行时只通过索引访问(`Index`/`IndexMut` 或 `get_data*`)。
#[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))]
#[derive(Debug, Clone)]
pub struct NameMap<IndexType, Data>
where
    IndexType: Copy + AsIndex + std::fmt::Debug,
{
    map: HashMap<String, IndexType>,
    data: Vec<Data>,
    names: Vec<String>,
}
impl<IndexType, Data> Default for NameMap<IndexType, Data>
where
    IndexType: Copy + AsIndex + std::fmt::Debug,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<IndexType, Data> NameMap<IndexType, Data>
where
    IndexType: Copy + AsIndex + std::fmt::Debug,
{
    /// 空容器
    pub fn new() -> Self {
        Self {
            map: HashMap::new(),
            data: Vec::new(),
            names: Vec::new(),
        }
    }
    /// 按名称查索引
    pub fn get_index(&self, name: &str) -> Option<IndexType> {
        self.map.get(name).copied()
    }
    /// 名称是否已存在
    pub fn exist(&self, name: &str) -> bool {
        self.map.contains_key(name)
    }
    /// 插入(名称重复时返回已有索引,不重复插入数据)
    pub fn insert(&mut self, name: String, data: Data) -> IndexType {
        if let Some(&idx) = self.map.get(&name) {
            return idx;
        }
        let idx = unsafe { IndexType::from_index(self.data.len()) };
        self.data.push(data);
        self.names.push(name.clone());
        self.map.insert(name, idx);
        idx
    }
    /// 按索引取名称(越界返回 [`Error::InvalidIndex`])
    pub fn get_name(&self, index: IndexType) -> Result<&str, Error> {
        let idx: usize = index.as_index();
        if idx >= self.names.len() {
            return Err(Error::InvalidIndex(format!("{:?}", index)));
        }
        Ok(&self.names[idx])
    }
    /// 用原始数字下标取名称(不校验类型,越界返回 None)
    pub fn get_name_with_number(&self, index: usize) -> Option<&str> {
        self.names.get(index).map(|s| s.as_str())
    }
    /// 按索引取数据(越界返回 [`Error::InvalidIndex`])
    pub fn get_data(&self, index: IndexType) -> Result<&Data, Error> {
        let idx: usize = index.as_index();
        match self.data.get(idx) {
            None => Err(Error::InvalidIndex(format!("{:?}", index))),
            Some(v) => Ok(v),
        }
    }
    /// 按索引取可变数据(越界返回 [`Error::InvalidIndex`])
    pub fn get_data_mut(&mut self, index: IndexType) -> Result<&mut Data, Error> {
        let idx: usize = index.as_index();
        match self.data.get_mut(idx) {
            None => Err(Error::InvalidIndex(format!("{:?}", index))),
            Some(v) => Ok(v),
        }
    }
    /// 把全部数据映射为按索引对齐的 [`TypedIndexVec`]
    pub fn map_to_vec<Data1>(
        &self,
        mut data_mapper: impl FnMut(&str, &Data) -> Data1,
    ) -> TypedIndexVec<IndexType, Data1> {
        let vec = self
            .iter()
            .map(|(_, name, data)| data_mapper(name, data))
            .collect();
        TypedIndexVec {
            data: vec,
            phantom: PhantomData,
        }
    }
    /// 元素数量
    pub fn len(&self) -> usize {
        self.data.len()
    }
    /// 是否为空
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// 所有名称
    pub fn keys(&self) -> impl Iterator<Item = &str> {
        self.names.iter().map(|s| s.as_str())
    }
    /// 所有索引
    pub fn indexs(&self) -> impl Iterator<Item = IndexType> + '_ {
        self.data
            .iter()
            .enumerate()
            .map(|(i, _)| unsafe { IndexType::from_index(i) })
    }
    /// (索引, 名称, 数据) 迭代器
    pub fn iter(&self) -> impl Iterator<Item = (IndexType, &str, &Data)> {
        self.names.iter().enumerate().map(move |(i, name)| {
            (
                unsafe { IndexType::from_index(i) },
                name.as_str(),
                &self.data[i],
            )
        })
    }
    /// (索引, 名称, 可变数据) 迭代器
    pub fn iter_mut(&mut self) -> impl Iterator<Item = (IndexType, &str, &mut Data)> {
        let names = &self.names;
        self.data
            .iter_mut()
            .enumerate()
            .map(move |(i, data)| (unsafe { IndexType::from_index(i) }, names[i].as_str(), data))
    }
}
impl<IndexType, Data> Index<IndexType> for NameMap<IndexType, Data>
where
    IndexType: Copy + AsIndex + std::fmt::Debug,
{
    type Output = Data;

    fn index(&self, index: IndexType) -> &Self::Output {
        self.get_data(index).expect("Invalid index in NameMap")
    }
}
impl<IndexType, Data> IndexMut<IndexType> for NameMap<IndexType, Data>
where
    IndexType: Copy + AsIndex + std::fmt::Debug,
{
    fn index_mut(&mut self, index: IndexType) -> &mut Self::Output {
        self.get_data_mut(index).expect("Invalid index in NameMap")
    }
}

/// 按强类型索引对齐的 Vec 数据。
///
/// 与 [`NameMap`] 不同,它不保存名称,直接以索引下标访问。支持"无效"空状态
/// ([`TypedIndexVec::new_invalid`] / [`TypedIndexVec::invalidate`]),
/// 用于需要占位但不希望用 `Option<TypedIndexVec>` 的场景(如 `Skeleton.children`)。
#[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TypedIndexVec<IndexType, Data>
where
    IndexType: Copy + AsIndex + std::fmt::Debug,
{
    data: Vec<Data>,
    #[cfg_attr(feature = "bevy_reflect", reflect(ignore))]
    phantom: PhantomData<IndexType>,
}

impl<IndexType, Data> TypedIndexVec<IndexType, Data>
where
    IndexType: Copy + AsIndex + std::fmt::Debug,
{
    /// 元素数量
    pub fn len(&self) -> usize {
        self.data.len()
    }
    /// 是否为空
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }
    /// 按索引取数据(无效状态或越界返回 [`Error::InvalidIndex`])
    pub fn get_data(&self, index: IndexType) -> Result<&Data, Error> {
        if !self.valid() {
            return Err(Error::InvalidIndex("TypedIndexVec is invalid".to_string()));
        }
        let idx: usize = index.as_index();
        match self.data.get(idx) {
            None => Err(Error::InvalidIndex(format!("{:?}", index))),
            Some(v) => Ok(v),
        }
    }
    /// 按索引取可变数据(无效状态或越界返回 [`Error::InvalidIndex`])
    pub fn get_data_mut(&mut self, index: IndexType) -> Result<&mut Data, Error> {
        if !self.valid() {
            return Err(Error::InvalidIndex("TypedIndexVec is invalid".to_string()));
        }
        let idx: usize = index.as_index();
        match self.data.get_mut(idx) {
            None => Err(Error::InvalidIndex(format!("{:?}", index))),
            Some(v) => Ok(v),
        }
    }

    /// 把全部数据映射为新类型的 [`TypedIndexVec`]
    pub fn map_to_vec<Data1>(
        &self,
        data_mapper: impl FnMut(&Data) -> Data1,
    ) -> TypedIndexVec<IndexType, Data1> {
        let vec = self.data.iter().map(data_mapper).collect();
        TypedIndexVec {
            data: vec,
            phantom: PhantomData,
        }
    }
    /// 所有索引
    pub fn indexs(&self) -> impl Iterator<Item = IndexType> + '_ {
        self.data
            .iter()
            .enumerate()
            .map(|(i, _)| unsafe { IndexType::from_index(i) })
    }
    /// (索引, 数据) 迭代器
    pub fn iter(&self) -> impl Iterator<Item = (IndexType, &Data)> {
        self.data
            .iter()
            .enumerate()
            .map(move |(i, data)| (unsafe { IndexType::from_index(i) }, data))
    }
    /// (索引, 可变数据) 迭代器
    pub fn iter_mut(&mut self) -> impl Iterator<Item = (IndexType, &mut Data)> {
        self.data
            .iter_mut()
            .enumerate()
            .map(move |(i, data)| (unsafe { IndexType::from_index(i) }, data))
    }

    /// 创建一个无效的空 `TypedIndexVec`
    /// 用于避免 `Option<TypedIndexVec>` 的使用
    pub fn new_invalid() -> Self {
        Self {
            data: Vec::new(),
            phantom: PhantomData,
        }
    }

    /// 清空数据,使其变为无效状态
    pub fn invalidate(&mut self) {
        self.data.clear();
    }

    /// 检查当前是否有效(包含数据)
    pub fn valid(&self) -> bool {
        !self.data.is_empty()
    }
    /// 根据给定的 NameMap 重建数据
    pub fn reconstruct_from_map<Data0>(
        &mut self,
        map: &NameMap<IndexType, Data0>,
        mut data_mapper: impl FnMut(&str, &Data0) -> Data,
    ) {
        self.data.clear();
        for data in map.iter() {
            let (_, name, d0) = data;
            let d1 = data_mapper(name, d0);
            self.data.push(d1);
        }
    }
    /// 根据给定的数组重建数据
    pub fn reconstruct_from_vec<Data0>(
        &mut self,
        vec: &TypedIndexVec<IndexType, Data0>,
        mut data_mapper: impl FnMut(&Data0) -> Data,
    ) {
        self.data.clear();
        for (_, d0) in vec.iter() {
            let d1 = data_mapper(d0);
            self.data.push(d1);
        }
    }
}
impl<IndexType, Data> Index<IndexType> for TypedIndexVec<IndexType, Data>
where
    IndexType: Copy + AsIndex + std::fmt::Debug,
{
    type Output = Data;

    fn index(&self, index: IndexType) -> &Self::Output {
        self.get_data(index)
            .expect("Invalid index in TypedIndexVec")
    }
}

impl<IndexType, Data> IndexMut<IndexType> for TypedIndexVec<IndexType, Data>
where
    IndexType: Copy + AsIndex + std::fmt::Debug,
{
    fn index_mut(&mut self, index: IndexType) -> &mut Self::Output {
        self.get_data_mut(index)
            .expect("Invalid index in TypedIndexVec")
    }
}

#[test]
fn t() {
    new_index!(DebugIdx);
    let mut a = NameMap::<DebugIdx, u32>::new();
    let idx = a.insert("dd".to_owned(), 32);
    let idx1 = a.insert("d2".to_owned(), 14);
    assert!(idx.as_index() == 0);
    assert_ne!(idx, idx1);
    assert!(idx1.as_index() == 1);
    let b = a.map_to_vec(|_name, e| *e);
    b.iter()
        .for_each(|(idx, data)| println!("{} {}", idx, data));
    let c = b.map_to_vec(|e| e + 2);
    c.iter()
        .for_each(|(idx, data)| println!("{} {}", idx, data));

    assert_eq!(idx1, unsafe { DebugIdx::from_index(idx1.as_index()) });
    assert_eq!(idx, unsafe { DebugIdx::from_index(idx.as_index()) });
}