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
use crate::*;
#[derive(Clone, Debug)]
pub struct Accessor {
pub count: usize,
pub offset: usize,
pub source: Url,
pub stride: usize,
pub param: Vec<Param>,
}
impl XNode for Accessor {
const NAME: &'static str = "accessor";
fn parse(element: &Element) -> Result<Self> {
debug_assert_eq!(element.name(), Self::NAME);
let mut it = element.children().peekable();
let res = Accessor {
count: parse_attr(element.attr("count"))?.ok_or("expected 'count' attr")?,
offset: parse_attr(element.attr("offset"))?.unwrap_or(0),
source: parse_attr(element.attr("source"))?.ok_or("missing source attr")?,
stride: parse_attr(element.attr("stride"))?.unwrap_or(1),
param: Param::parse_list(&mut it)?,
};
if res.stride < res.param.len() {
return Err("accessor stride does not match params".into());
}
finish(res, it)
}
}
fn parse_array_count<T: FromStr>(e: &Element) -> Result<Box<[T]>> {
let count: usize = parse_attr(e.attr("count"))?.ok_or("expected 'count' attr")?;
let mut vec = Vec::with_capacity(count);
for s in get_text(e)
.ok_or("expected text node")?
.split_ascii_whitespace()
{
vec.push(s.parse().map_err(|_| "parse error")?)
}
if vec.len() != count {
return Err("'count' does not match array length".into());
}
Ok(vec.into())
}
macro_rules! mk_arrays {
($($(#[$doc:meta])* $name:ident($tyname:ident($ty:ty)) = $s:literal,)*) => {
$(
$(#[$doc])*
#[derive(Clone, Debug)]
pub struct $tyname {
pub id: Option<String>,
pub val: $ty,
}
impl Deref for $tyname {
type Target = $ty;
fn deref(&self) -> &Self::Target {
&self.val
}
}
impl XNode for $tyname {
const NAME: &'static str = $s;
fn parse(element: &Element) -> Result<Self> {
debug_assert_eq!(element.name(), Self::NAME);
Ok(Self {
id: element.attr("id").map(Into::into),
val: parse_array_count(element)?,
})
}
}
impl CollectLocalMaps for $tyname {
fn collect_local_maps<'a>(&'a self, maps: &mut LocalMaps<'a>) {
maps.insert(self)
}
}
)*
#[derive(Clone, Debug)]
pub enum ArrayElement {
$($(#[$doc])* $name($tyname),)*
}
impl ArrayElement {
pub fn parse(e: &Element) -> Result<Option<Self>> {
Ok(Some(match e.name() {
$($tyname::NAME => Self::$name($tyname::parse(e)?),)*
_ => return Ok(None),
}))
}
}
impl CollectLocalMaps for ArrayElement {
fn collect_local_maps<'a>(&'a self, maps: &mut LocalMaps<'a>) {
match self {
$(Self::$name(arr) => arr.collect_local_maps(maps),)*
}
}
}
}
}
mk_arrays! {
IdRef(IdRefArray(Box<[String]>)) = "IDREF_array",
Name(NameArray(Box<[String]>)) = "Name_array",
Bool(BoolArray(Box<[bool]>)) = "bool_array",
Float(FloatArray(Box<[f32]>)) = "float_array",
Int(IntArray(Box<[u32]>)) = "int_array",
}
#[derive(Clone, Debug)]
pub struct Param {
pub sid: Option<String>,
pub name: Option<String>,
pub ty: String,
pub semantic: Option<Semantic>,
}
impl XNode for Param {
const NAME: &'static str = "param";
fn parse(element: &Element) -> Result<Self> {
debug_assert_eq!(element.name(), Self::NAME);
Ok(Param {
sid: element.attr("sid").map(Into::into),
name: element.attr("name").map(Into::into),
ty: element.attr("type").ok_or("expecting 'type' attr")?.into(),
semantic: parse_attr(element.attr("semantic"))?,
})
}
}
#[derive(Clone, Debug)]
pub struct Source {
pub id: Option<String>,
pub name: Option<String>,
pub asset: Option<Box<Asset>>,
pub array: Option<ArrayElement>,
pub accessor: Accessor,
pub technique: Vec<Technique>,
}
impl XNode for Source {
const NAME: &'static str = "source";
fn parse(element: &Element) -> Result<Self> {
debug_assert_eq!(element.name(), Self::NAME);
let mut it = element.children().peekable();
let res = Source {
id: element.attr("id").map(Into::into),
name: element.attr("name").map(Into::into),
asset: Asset::parse_opt_box(&mut it)?,
array: parse_opt_many(&mut it, ArrayElement::parse)?,
accessor: parse_one(Technique::COMMON, &mut it, |e| {
let mut it = e.children().peekable();
finish(Accessor::parse_one(&mut it)?, it)
})?,
technique: Technique::parse_list(&mut it)?,
};
finish(res, it)
}
}
impl CollectLocalMaps for Source {
fn collect_local_maps<'a>(&'a self, maps: &mut LocalMaps<'a>) {
maps.insert(self);
self.array.collect_local_maps(maps);
}
}
impl Traversable for Source {
fn traverse<'a, E>(
doc: &'a Document,
mut f: impl FnMut(&'a Self) -> Result<(), E>,
) -> Result<(), E>
where
Self: 'a,
{
doc.library.iter().try_for_each(|elem| match elem {
LibraryElement::Animations(lib) => lib
.items
.iter()
.try_for_each(|anim| anim.source.iter().try_for_each(&mut f)),
LibraryElement::Controllers(lib) => lib
.items
.iter()
.try_for_each(|con| con.element.sources().iter().try_for_each(&mut f)),
LibraryElement::Geometries(lib) => lib
.items
.iter()
.try_for_each(|geom| geom.element.sources().iter().try_for_each(&mut f)),
_ => Ok(()),
})
}
}
#[derive(Clone, Debug)]
pub struct Input {
pub semantic: Semantic,
pub source: Url,
}
impl XNode for Input {
const NAME: &'static str = "input";
fn parse(element: &Element) -> Result<Self> {
debug_assert_eq!(element.name(), Self::NAME);
Ok(Input {
semantic: parse_attr(element.attr("semantic"))?.ok_or("missing semantic attr")?,
source: parse_attr(element.attr("source"))?.ok_or("missing source attr")?,
})
}
}
impl Input {
pub fn source_as_source(&self) -> &UrlRef<Source> {
debug_assert!(!matches!(self.semantic, Semantic::Vertex));
ref_cast::RefCast::ref_cast(&self.source)
}
pub fn source_as_vertices(&self) -> &UrlRef<Vertices> {
debug_assert!(matches!(self.semantic, Semantic::Vertex));
ref_cast::RefCast::ref_cast(&self.source)
}
}
#[derive(Clone, Debug)]
pub struct InputS {
pub input: Input,
pub offset: u32,
pub set: Option<u32>,
}
impl Deref for InputS {
type Target = Input;
fn deref(&self) -> &Self::Target {
&self.input
}
}
impl XNode for InputS {
const NAME: &'static str = "input";
fn parse(element: &Element) -> Result<Self> {
Ok(InputS {
input: Input::parse(element)?,
offset: parse_attr(element.attr("offset"))?.ok_or("missing offset attr")?,
set: parse_attr(element.attr("set"))?,
})
}
}
#[derive(Clone, Default, Debug)]
pub struct InputList {
pub inputs: Vec<InputS>,
pub depth: usize,
}
impl Deref for InputList {
type Target = Vec<InputS>;
fn deref(&self) -> &Self::Target {
&self.inputs
}
}
impl InputList {
pub(crate) fn parse<const N: usize>(it: &mut ElementIter<'_>) -> Result<Self> {
let inputs = InputS::parse_list_n::<N>(it)?;
let depth = inputs.iter().map(|i| i.offset).max().map_or(0, |n| n + 1) as usize;
Ok(InputList { inputs, depth })
}
pub(crate) fn check_prim<const MIN: usize>(&self, data: &[u32]) -> bool {
self.depth != 0 && data.len() < self.depth * MIN && data.len() % self.depth == 0
}
}
mk_extensible_enum! {
pub enum Semantic {
Binormal = "BINORMAL",
Color = "COLOR",
Continuity = "CONTINUITY",
Image = "IMAGE",
Input = "INPUT",
InTangent = "IN_TANGENT",
Interpolation = "INTERPOLATION",
InvBindMatrix = "INV_BIND_MATRIX",
Joint = "JOINT",
LinearSteps = "LINEAR_STEPS",
MorphTarget = "MORPH_TARGET",
MorphWeight = "MORPH_WEIGHT",
Normal = "NORMAL",
Output = "OUTPUT",
OutTangent = "OUT_TANGENT",
Position = "POSITION",
Tangent = "TANGENT",
TexBinormal = "TEXBINORMAL",
TexCoord = "TEXCOORD",
TexTangent = "TEXTANGENT",
UV = "UV",
Vertex = "VERTEX",
Weight = "WEIGHT",
}
}