wc3 0.2.0

Read, edit, and write Warcraft III models, BLP textures, and MPQ archives
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
//! Typed keyframe tracks.
use super::{
    AnimationTime, Interpolate, Interpolation, Keyframe, TangentKeyframe, TrackValue, ValueKeyframe,
};
use crate::model::mdl::{Parser, TokenKind, Writer};
use crate::model::IoError;
use crate::model::{mdl, mdx};
use crate::model::{Cursor, Encoder, ValueError};
use std::io::Write as IoWrite;
use std::ops::RangeInclusive;

#[derive(Clone, Debug, PartialEq)]
enum Keyframes<T> {
    Step(Vec<ValueKeyframe<T>>),
    Linear(Vec<ValueKeyframe<T>>),
    Hermite(Vec<TangentKeyframe<T>>),
    Bezier(Vec<TangentKeyframe<T>>),
}

/// Keyframes for one animated property.
///
/// The type `T` selects the keyframe value type. Constructors select the
/// interpolation and matching keyframe shape. Times are in milliseconds;
/// `global_sequence_id` is an index into the model global-sequence collection,
/// or `None` to use the current model sequence.
///
/// Constructors and readers stably sort keys by ascending frame time. Duplicate
/// timestamps retain their input order, and evaluation uses the last key at each
/// timestamp. Writing a parsed track emits this sorted order.
#[derive(Clone, Debug, PartialEq)]
pub struct Track<T: TrackValue> {
    global_sequence_id: Option<u32>,
    keyframes: Keyframes<T>,
}

impl<T: TrackValue> Track<T> {
    /// A constant animation represented by one stepped key at time zero.
    pub fn constant(value: T) -> Self {
        Self::step(vec![ValueKeyframe { frame: 0, value }], None)
            .expect("one key without a global sequence is valid")
    }

    /// Creates stepped animation: each key value holds until the next key.
    pub fn step(
        keys: Vec<ValueKeyframe<T>>,
        global_sequence_id: Option<u32>,
    ) -> Result<Self, ValueError> {
        Self::new(Keyframes::Step(keys), global_sequence_id)
    }
    /// Creates animation that interpolates linearly between adjacent key values.
    pub fn linear(
        keys: Vec<ValueKeyframe<T>>,
        global_sequence_id: Option<u32>,
    ) -> Result<Self, ValueError> {
        Self::new(Keyframes::Linear(keys), global_sequence_id)
    }
    /// Creates a Hermite track whose keys each have two tangents.
    pub fn hermite(
        keys: Vec<TangentKeyframe<T>>,
        global_sequence_id: Option<u32>,
    ) -> Result<Self, ValueError> {
        Self::new(Keyframes::Hermite(keys), global_sequence_id)
    }
    /// Creates a Bezier track whose keys each have two tangents.
    pub fn bezier(
        keys: Vec<TangentKeyframe<T>>,
        global_sequence_id: Option<u32>,
    ) -> Result<Self, ValueError> {
        Self::new(Keyframes::Bezier(keys), global_sequence_id)
    }
    fn new(keyframes: Keyframes<T>, global_sequence_id: Option<u32>) -> Result<Self, ValueError> {
        if keyframes.len() > u32::MAX as usize {
            return Err(ValueError::CountTooLarge {
                tag: *b"TRAK",
                count: keyframes.len(),
            });
        }
        if global_sequence_id == Some(u32::MAX) {
            return Err(ValueError::InvalidGlobalSequenceId { id: u32::MAX });
        }
        Ok(Self {
            global_sequence_id,
            keyframes: keyframes.into_sorted(),
        })
    }
    /// Returns the optional global sequence index.
    pub fn global_sequence_id(&self) -> Option<u32> {
        self.global_sequence_id
    }
    /// Returns the interpolation mode shared by all keys.
    pub fn interpolation(&self) -> Interpolation {
        match self.keyframes {
            Keyframes::Step(_) => Interpolation::Step,
            Keyframes::Linear(_) => Interpolation::Linear,
            Keyframes::Hermite(_) => Interpolation::Hermite,
            Keyframes::Bezier(_) => Interpolation::Bezier,
        }
    }
    /// Returns keys in ascending frame order only for stepped interpolation.
    pub fn step_keys(&self) -> Option<&[ValueKeyframe<T>]> {
        match &self.keyframes {
            Keyframes::Step(keys) => Some(keys),
            _ => None,
        }
    }
    /// Returns keys in ascending frame order only for linear interpolation.
    pub fn linear_keys(&self) -> Option<&[ValueKeyframe<T>]> {
        match &self.keyframes {
            Keyframes::Linear(keys) => Some(keys),
            _ => None,
        }
    }
    /// Returns keys and tangents in ascending frame order only for Hermite interpolation.
    pub fn hermite_keys(&self) -> Option<&[TangentKeyframe<T>]> {
        match &self.keyframes {
            Keyframes::Hermite(keys) => Some(keys),
            _ => None,
        }
    }
    /// Returns keys and tangents in ascending frame order only for Bezier interpolation.
    pub fn bezier_keys(&self) -> Option<&[TangentKeyframe<T>]> {
        match &self.keyframes {
            Keyframes::Bezier(keys) => Some(keys),
            _ => None,
        }
    }
}
impl<T> Keyframes<T> {
    fn into_sorted(mut self) -> Self {
        match &mut self {
            Self::Step(keys) | Self::Linear(keys) => keys.sort_by_key(Keyframe::frame),
            Self::Hermite(keys) | Self::Bezier(keys) => keys.sort_by_key(Keyframe::frame),
        }
        self
    }

    fn len(&self) -> usize {
        match self {
            Self::Step(v) | Self::Linear(v) => v.len(),
            Self::Hermite(v) | Self::Bezier(v) => v.len(),
        }
    }
    fn interpolation(&self) -> u32 {
        match self {
            Self::Step(_) => 0,
            Self::Linear(_) => 1,
            Self::Hermite(_) => 2,
            Self::Bezier(_) => 3,
        }
    }
}
impl<T: TrackValue> mdx::Read for Track<T> {
    fn read_mdx(cursor: &mut Cursor<'_>) -> Result<Self, mdx::ReadError> {
        let mut next = *cursor;
        let offset = next.absolute_position();
        let overflow = || mdx::ReadError::new(offset, mdx::ReadErrorKind::SizeOverflow);
        let count = next.read::<u32>()? as usize;
        let interpolation = next.read::<u32>()?;
        if interpolation > 3 {
            return Err(mdx::ReadError::new(
                offset + 4,
                mdx::ReadErrorKind::UnknownEnumValue {
                    enum_name: "Interpolation",
                    value: interpolation,
                },
            ));
        }
        let sequence = next.read::<u32>()?;
        let components = T::COMPONENTS;
        let vector_count = if interpolation >= 2 { 3usize } else { 1usize };
        let key_size = components
            .checked_mul(vector_count)
            .and_then(|n| n.checked_mul(4))
            .and_then(|n| n.checked_add(4))
            .ok_or_else(overflow)?;
        let body_size = count.checked_mul(key_size).ok_or_else(overflow)?;
        let mut body = next.subcursor(body_size)?;
        let keyframes = match interpolation {
            0 | 1 => {
                let mut keys = Vec::with_capacity(count);
                for _ in 0..count {
                    keys.push(body.read::<ValueKeyframe<T>>()?);
                }
                if interpolation == 0 {
                    Keyframes::Step(keys)
                } else {
                    Keyframes::Linear(keys)
                }
            }
            2 | 3 => {
                let mut keys = Vec::with_capacity(count);
                for _ in 0..count {
                    keys.push(body.read::<TangentKeyframe<T>>()?);
                }
                if interpolation == 2 {
                    Keyframes::Hermite(keys)
                } else {
                    Keyframes::Bezier(keys)
                }
            }
            _ => unreachable!(),
        };
        *cursor = next;
        Ok(Self {
            global_sequence_id: (sequence != u32::MAX).then_some(sequence),
            keyframes: keyframes.into_sorted(),
        })
    }
}
impl<T: TrackValue> mdx::Write for Track<T> {
    fn write_mdx(&self, encoder: &mut Encoder<'_>) -> Result<(), mdx::WriteError> {
        encoder.write(&(self.keyframes.len() as u32))?;
        encoder.write(&(self.keyframes.interpolation()))?;
        encoder.write(&(self.global_sequence_id.unwrap_or(u32::MAX)))?;
        match &self.keyframes {
            Keyframes::Step(keys) | Keyframes::Linear(keys) => {
                for key in keys {
                    encoder.write(key)?;
                }
            }
            Keyframes::Hermite(keys) | Keyframes::Bezier(keys) => {
                for key in keys {
                    encoder.write(key)?;
                }
            }
        }
        Ok(())
    }
}

impl<T: TrackValue> mdl::Read for Track<T>
where
    T: mdl::Read,
{
    fn read_mdl(parser: &mut Parser<'_>) -> Result<Self, mdl::ReadError> {
        parser.expect_ident("Track")?;
        Self::read_mdl_payload(parser)
    }
}
impl<T: TrackValue> Track<T>
where
    T: mdl::Read,
{
    /// Reads the ordinary track grammar under an enclosing record's alias.
    pub fn read_mdl_named(
        parser: &mut Parser<'_>,
        name: &'static str,
    ) -> Result<Self, mdl::ReadError> {
        parser.expect_ident(name)?;
        Self::read_mdl_payload(parser)
    }

    /// Reads a counted MDL track body after its property name.
    /// The payload includes the key count, interpolation mode, and optional global sequence.
    pub fn read_mdl_payload(parser: &mut Parser<'_>) -> Result<Self, mdl::ReadError> {
        let count = parser.read::<u32>()? as usize;
        parser.expect(TokenKind::OpenBrace)?;
        let mut interpolation = None;
        let mut sequence = None;
        while let Some(token) = parser.peek()? {
            let TokenKind::Ident(name) = token.kind else {
                break;
            };
            if name == "GlobalSeqId" {
                parser.next_token()?;
                if sequence.is_some() {
                    return Err(mdl::ReadError::new(
                        token.span,
                        mdl::ReadErrorKind::DuplicateField,
                    ));
                }
                parser.peek()?;
                let span = parser
                    .error(mdl::ReadErrorKind::InvalidNumber("global sequence ID"))
                    .span;
                let id = parser.read_property::<u32>()?;
                if id == u32::MAX {
                    return Err(mdl::ReadError::new(
                        span,
                        mdl::ReadErrorKind::InvalidNumber("global sequence ID"),
                    ));
                }
                sequence = Some(id);
            } else {
                let mode = parser.read::<Interpolation>()?;
                if interpolation.replace(mode).is_some() {
                    return Err(mdl::ReadError::new(
                        token.span,
                        mdl::ReadErrorKind::DuplicateField,
                    ));
                }
                parser.expect(TokenKind::Comma)?;
            }
        }
        let interpolation = interpolation
            .ok_or_else(|| parser.error(mdl::ReadErrorKind::MissingField("interpolation")))?;
        // Grow from actual input, rather than trusting the declared count.
        let mut values = Vec::new();
        let mut tangents = Vec::new();
        let mut actual = 0;
        loop {
            if let Some(token) = parser.peek()? {
                if token.kind == TokenKind::CloseBrace {
                    if actual != count {
                        return Err(mdl::ReadError::new(
                            token.span,
                            mdl::ReadErrorKind::CountMismatch {
                                expected: count,
                                actual,
                            },
                        ));
                    }
                    parser.next_token()?;
                    break;
                }
            }
            if actual == count {
                return Err(parser.error(mdl::ReadErrorKind::CountMismatch {
                    expected: count,
                    actual: actual + 1,
                }));
            }
            let frame = parser.read::<i32>()?;
            parser.expect(TokenKind::Colon)?;
            let value = parser.read_property::<T>()?;
            if matches!(
                interpolation,
                Interpolation::Hermite | Interpolation::Bezier
            ) {
                parser.expect_ident("InTan")?;
                let in_tangent = parser.read_property()?;
                parser.expect_ident("OutTan")?;
                let out_tangent = parser.read_property()?;
                tangents.push(TangentKeyframe {
                    frame,
                    value,
                    in_tangent,
                    out_tangent,
                });
            } else {
                values.push(ValueKeyframe { frame, value });
            }
            actual += 1;
        }
        let keyframes = match interpolation {
            Interpolation::Step => Keyframes::Step(values),
            Interpolation::Linear => Keyframes::Linear(values),
            Interpolation::Hermite => Keyframes::Hermite(tangents),
            Interpolation::Bezier => Keyframes::Bezier(tangents),
        };
        Ok(Self {
            global_sequence_id: sequence,
            keyframes: keyframes.into_sorted(),
        })
    }
}

impl<T: TrackValue> mdl::Write for Track<T>
where
    T: mdl::Write,
{
    fn write_mdl<W: IoWrite>(
        &self,
        writer: &mut Writer<W>,
    ) -> Result<(), IoError<mdl::WriteError>> {
        self.write_mdl_named(writer, "Track")
    }
}
impl<T: TrackValue> Track<T>
where
    T: mdl::Write,
{
    /// Writes a borrowed track under an enclosing record's alias.
    pub fn write_mdl_named<W: IoWrite>(
        &self,
        writer: &mut Writer<W>,
        name: &str,
    ) -> Result<(), IoError<mdl::WriteError>> {
        writer.begin_counted_block(name, self.keyframes.len())?;
        writer.indent()?;
        writer.write(&self.interpolation())?;
        writer.raw(",\n")?;
        if let Some(sequence) = self.global_sequence_id {
            writer.property("GlobalSeqId", &sequence)?;
        }
        match &self.keyframes {
            Keyframes::Step(keys) | Keyframes::Linear(keys) => {
                for key in keys {
                    write_key(writer, key.frame, &key.value)?;
                }
            }
            Keyframes::Hermite(keys) | Keyframes::Bezier(keys) => {
                for key in keys {
                    write_key(writer, key.frame, &key.value)?;
                    write_tangent(writer, "InTan", &key.in_tangent)?;
                    write_tangent(writer, "OutTan", &key.out_tangent)?;
                }
            }
        }
        writer.end_block()
    }
}

fn write_key<W: IoWrite, T: mdl::Write>(
    writer: &mut Writer<W>,
    frame: i32,
    value: &T,
) -> Result<(), IoError<mdl::WriteError>> {
    writer.indent()?;
    writer.write(&frame)?;
    writer.raw(": ")?;
    writer.write(value)?;
    writer.raw(",\n")
}

fn write_tangent<W: IoWrite, T: mdl::Write>(
    writer: &mut Writer<W>,
    name: &str,
    value: &T,
) -> Result<(), IoError<mdl::WriteError>> {
    writer.indent()?;
    writer.raw("\t")?;
    writer.identifier(name)?;
    writer.raw(" ")?;
    writer.write(value)?;
    writer.raw(",\n")
}

impl<T: TrackValue> Track<T> {
    /// Returns the latest key timestamp at or before an absolute track time.
    ///
    /// Lookup takes O(log n) time. Empty tracks, nonfinite times, and times before
    /// the first key return `None`. Callers resolve clocks and looping.
    pub fn key_frame_at_or_before(&self, time_ms: f64) -> Option<i32> {
        self.key_frame_at_or_before_in(time_ms, i32::MIN..=i32::MAX)
    }

    /// Returns the latest key timestamp at or before an absolute track time,
    /// considering only keys within the inclusive sequence interval.
    pub fn key_frame_at_or_before_in(
        &self,
        time_ms: f64,
        interval: RangeInclusive<i32>,
    ) -> Option<i32> {
        if !time_ms.is_finite() || interval.is_empty() {
            return None;
        }
        match &self.keyframes {
            Keyframes::Step(keys) | Keyframes::Linear(keys) => {
                latest_frame(keys, time_ms, &interval)
            }
            Keyframes::Hermite(keys) | Keyframes::Bezier(keys) => {
                latest_frame(keys, time_ms, &interval)
            }
        }
    }
}

fn latest_frame<K: Keyframe>(
    keys: &[K],
    time_ms: f64,
    interval: &RangeInclusive<i32>,
) -> Option<i32> {
    let keys = keys_in(keys, interval);
    let end = keys.partition_point(|key| f64::from(key.frame()) <= time_ms);
    end.checked_sub(1).map(|index| keys[index].frame())
}

impl<T: Interpolate> Track<T> {
    /// Samples this track using its model or global sequence clock.
    pub fn sample(&self, time: &AnimationTime<'_>) -> Option<T> {
        let (time_ms, interval) = time.track_time(self)?;
        self.evaluate_in(time_ms, interval)
    }

    /// Samples at a time in milliseconds in this track's timeline.
    ///
    /// Empty tracks and nonfinite times return `None`. Outside the key range,
    /// the nearest endpoint is returned. At duplicate timestamps the last
    /// stored key wins. Evaluation takes O(log n) time.
    /// Global sequence IDs do not affect sampling: callers resolve clocks and
    /// looping before calling this method.
    pub fn evaluate(&self, time_ms: f64) -> Option<T> {
        self.evaluate_in(time_ms, i32::MIN..=i32::MAX)
    }

    /// Samples using only keys within the inclusive sequence interval.
    ///
    /// Returns `None` when the interval contains no keys or is reversed.
    /// Time is an absolute track timestamp, not an offset from the interval's
    /// start. Endpoint clamping and duplicate handling match [`Self::evaluate`].
    pub fn evaluate_in(&self, time_ms: f64, interval: RangeInclusive<i32>) -> Option<T> {
        if !time_ms.is_finite() || interval.is_empty() {
            return None;
        }
        match &self.keyframes {
            Keyframes::Step(keys) | Keyframes::Linear(keys) => {
                let (a, b) = surrounding(keys, time_ms, &interval)?;
                if a.frame == b.frame || matches!(self.keyframes, Keyframes::Step(_)) {
                    return Some(a.value);
                }
                let t = ((time_ms - f64::from(a.frame)) / (f64::from(b.frame) - f64::from(a.frame)))
                    as f32;
                Some(T::linear(a.value, b.value, t))
            }
            Keyframes::Hermite(keys) | Keyframes::Bezier(keys) => {
                let (a, b) = surrounding(keys, time_ms, &interval)?;
                if a.frame == b.frame {
                    return Some(a.value);
                }
                let t = ((time_ms - f64::from(a.frame)) / (f64::from(b.frame) - f64::from(a.frame)))
                    as f32;
                Some(if matches!(self.keyframes, Keyframes::Hermite(_)) {
                    T::hermite(a.value, a.out_tangent, b.in_tangent, b.value, t)
                } else {
                    T::bezier(a.value, a.out_tangent, b.in_tangent, b.value, t)
                })
            }
        }
    }
}

fn surrounding<'a, K: Keyframe>(
    keys: &'a [K],
    time: f64,
    interval: &RangeInclusive<i32>,
) -> Option<(&'a K, &'a K)> {
    let keys = keys_in(keys, interval);
    let end = keys.partition_point(|key| f64::from(key.frame()) <= time);
    let left = end.checked_sub(1).map(|index| &keys[index]);
    let right = if left.is_some_and(|key| f64::from(key.frame()) == time) {
        left
    } else {
        keys.get(end).map(|first| {
            // Use the last duplicate for the right endpoint, too.
            let after = keys.partition_point(|key| key.frame() <= first.frame());
            &keys[after - 1]
        })
    };
    Some((left.or(right)?, right.or(left)?))
}

/// Restricts a sorted track to an inclusive sequence interval.
fn keys_in<'a, K: Keyframe>(keys: &'a [K], interval: &RangeInclusive<i32>) -> &'a [K] {
    let start = keys.partition_point(|key| key.frame() < *interval.start());
    let end = keys.partition_point(|key| key.frame() <= *interval.end());
    &keys[start..end]
}

#[cfg(test)]
mod key_lookup_tests {
    use super::*;

    #[test]
    fn lookup_respects_time_and_sequence_for_unordered_keys() {
        let track = Track::step(
            vec![
                ValueKeyframe {
                    frame: 200,
                    value: 1.0,
                },
                ValueKeyframe {
                    frame: 50,
                    value: 2.0,
                },
                ValueKeyframe {
                    frame: 150,
                    value: 3.0,
                },
            ],
            None,
        )
        .unwrap();
        assert_eq!(track.key_frame_at_or_before(175.0), Some(150));
        assert_eq!(track.key_frame_at_or_before(25.0), None);
        assert_eq!(track.key_frame_at_or_before_in(125.0, 100..=200), None);
        assert_eq!(track.key_frame_at_or_before_in(250.0, 100..=175), Some(150));
        assert_eq!(track.key_frame_at_or_before(f64::NAN), None);
    }
}