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
581
582
583
//! Direct and ambient lighting with version-dependent shadow settings.
use crate::model::conversion::ConversionContext;
use crate::model::Color;
use crate::model::ConversionError;
use crate::model::KnownChunk;
use crate::model::LightsChunk;
use crate::model::ValueError;
use crate::model::{mdl, mdx};
use crate::model::{Animatable, Track};
use crate::model::{Model, Node};
use crate::model::{
    ModelVersion, SupportsLightFalloff, SupportsLightShadowCasting, SupportsLightShadowIntensity,
};
use mdl_codec::{damping, is_zero, quadratic, white, zero};
use std::fmt::Debug;
use std::marker::PhantomData;

/// How a light illuminates the model. Unknown values round-trip through MDX.
#[derive(
    Clone,
    Copy,
    Debug,
    Default,
    Eq,
    PartialEq,
    Hash,
    mdx::Read,
    mdx::Write,
    mdx::Value,
    mdl::Read,
    mdl::Write,
)]
#[mdx(value = u32)]
#[mdl(choice)]
pub enum LightType {
    #[default]
    #[mdx(value = 0)]
    /// A point source radiating in all directions.
    Omnidirectional,
    #[mdx(value = 1)]
    /// A source with a fixed illumination direction.
    Directional,
    #[mdx(value = 2)]
    /// Ambient illumination without a directional source.
    Ambient,
    #[mdx(unknown)]
    #[mdl(unknown)]
    /// An unrecognized wire value preserved by MDX; unsupported in MDL.
    Unknown(u32),
}

/// Light features available in a particular model version.
pub trait ShadowCastingField: Default + mdx::Read + mdx::Write + Clone + Debug + PartialEq {
    fn shadow_casting(&self) -> Option<u32> {
        None
    }
    fn shadow_casting_mut(&mut self) -> Option<&mut u32> {
        None
    }
}

#[derive(Clone, Debug, Default, PartialEq, mdx::Read, mdx::Write)]
pub struct NoShadowCasting;
impl ShadowCastingField for NoShadowCasting {}

#[derive(Clone, Debug, Default, PartialEq, mdx::Read, mdx::Write)]
pub struct ShadowCasting(u32);
impl ShadowCastingField for ShadowCasting {
    fn shadow_casting(&self) -> Option<u32> {
        Some(self.0)
    }
    fn shadow_casting_mut(&mut self) -> Option<&mut u32> {
        Some(&mut self.0)
    }
}

pub trait ShadowIntensityField:
    Default + mdx::Read + mdx::Write + Clone + Debug + PartialEq
{
    fn shadow_intensity(&self) -> Option<f32> {
        None
    }
    fn shadow_intensity_mut(&mut self) -> Option<&mut f32> {
        None
    }
}

#[derive(Clone, Debug, Default, PartialEq, mdx::Read, mdx::Write)]
pub struct NoShadowIntensity;
impl ShadowIntensityField for NoShadowIntensity {}

#[derive(Clone, Debug, Default, PartialEq, mdx::Read, mdx::Write)]
pub struct LightShadowIntensity {
    pub shadow_intensity: f32,
}
impl ShadowIntensityField for LightShadowIntensity {
    fn shadow_intensity(&self) -> Option<f32> {
        Some(self.shadow_intensity)
    }
    fn shadow_intensity_mut(&mut self) -> Option<&mut f32> {
        Some(&mut self.shadow_intensity)
    }
}

pub trait ShadowRangeField:
    Default + mdx::Read + mdx::Write + mdx::ReadTracks + mdx::WriteTracks + Clone + Debug + PartialEq
{
    fn shadow_casting_range(&self) -> Option<&LightShadowRange> {
        None
    }
    fn shadow_casting_range_mut(&mut self) -> Option<&mut LightShadowRange> {
        None
    }
}

#[derive(Clone, Debug, Default, PartialEq, mdx::Read, mdx::Write)]
pub struct NoShadowRange;
impl ShadowRangeField for NoShadowRange {}

/// Start and end distances for a light's shadow-casting range.
#[derive(Clone, Debug, Default, PartialEq, mdx::Read, mdx::Write)]
pub struct LightShadowRange {
    #[mdx(tag = *b"KLSS")]
    /// Animated start distance of the shadow-casting range.
    pub start: Animatable<f32>,
    #[mdx(tag = *b"KLSE")]
    /// Animated end distance of the shadow-casting range.
    pub end: Animatable<f32>,
}
impl ShadowRangeField for LightShadowRange {
    fn shadow_casting_range(&self) -> Option<&LightShadowRange> {
        Some(self)
    }
    fn shadow_casting_range_mut(&mut self) -> Option<&mut LightShadowRange> {
        Some(self)
    }
}

pub trait FalloffField:
    Default + mdx::Read + mdx::Write + mdx::ReadTracks + mdx::WriteTracks + Clone + Debug + PartialEq
{
    fn falloff(&self) -> Option<&LightFalloff> {
        None
    }
    fn falloff_mut(&mut self) -> Option<&mut LightFalloff> {
        None
    }
}

#[derive(Clone, Debug, Default, PartialEq, mdx::Read, mdx::Write)]
pub struct NoFalloff;
impl FalloffField for NoFalloff {}

/// Distance falloff coefficients, editable in version 1600 and newer.
#[derive(Clone, Debug, PartialEq, mdx::Read, mdx::Write)]
pub struct LightFalloff {
    #[mdx(tag = *b"KLQF")]
    /// Animated quadratic distance-falloff coefficient.
    pub quadratic: Animatable<f32>,
    #[mdx(tag = *b"KLLF")]
    /// Animated linear distance-falloff coefficient.
    pub linear: Animatable<f32>,
    #[mdx(tag = *b"KLDA")]
    /// Animated damping coefficient.
    pub damping: Animatable<f32>,
}
impl Default for LightFalloff {
    fn default() -> Self {
        Self {
            quadratic: Animatable::Static(0.0005),
            linear: Animatable::Static(0.0),
            damping: Animatable::Static(0.00001),
        }
    }
}
impl FalloffField for LightFalloff {
    fn falloff(&self) -> Option<&LightFalloff> {
        Some(self)
    }
    fn falloff_mut(&mut self) -> Option<&mut LightFalloff> {
        Some(self)
    }
}

/// Selects version-dependent light fields.
pub trait LightLayout {
    /// Storage for the shadow-casting flag.
    type ShadowCasting: ShadowCastingField;
    /// Storage for shadow intensity.
    type ShadowIntensity: ShadowIntensityField;
    /// Storage for the animated shadow range.
    type ShadowRange: ShadowRangeField;
    /// Storage for animated distance-falloff controls.
    type Falloff: FalloffField;
}
use crate::model::{V1000, V1100, V1200, V1300, V1400, V1600, V1800, V800, V900};
macro_rules! light_layout {
    ($version:ty, $casting:ty, $intensity:ty, $range:ty, $falloff:ty) => {
        impl LightLayout for $version {
            type ShadowCasting = $casting;
            type ShadowIntensity = $intensity;
            type ShadowRange = $range;
            type Falloff = $falloff;
        }
    };
}
light_layout!(
    V800,
    NoShadowCasting,
    NoShadowIntensity,
    NoShadowRange,
    NoFalloff
);
light_layout!(
    V900,
    NoShadowCasting,
    NoShadowIntensity,
    NoShadowRange,
    NoFalloff
);
light_layout!(
    V1000,
    NoShadowCasting,
    NoShadowIntensity,
    NoShadowRange,
    NoFalloff
);
light_layout!(
    V1100,
    NoShadowCasting,
    NoShadowIntensity,
    NoShadowRange,
    NoFalloff
);
light_layout!(
    V1200,
    NoShadowCasting,
    LightShadowIntensity,
    NoShadowRange,
    NoFalloff
);
light_layout!(
    V1300,
    ShadowCasting,
    LightShadowIntensity,
    LightShadowRange,
    NoFalloff
);
light_layout!(
    V1400,
    ShadowCasting,
    LightShadowIntensity,
    LightShadowRange,
    NoFalloff
);
light_layout!(
    V1600,
    ShadowCasting,
    LightShadowIntensity,
    LightShadowRange,
    LightFalloff
);
light_layout!(
    V1800,
    ShadowCasting,
    LightShadowIntensity,
    LightShadowRange,
    LightFalloff
);

/// A node that supplies direct and ambient lighting.
///
/// Shadow settings depend on the model version; checked accessors report
/// unavailable features. MDL supports static shadow intensity, not an animated
/// shadow-intensity channel.
#[derive(Clone, Debug, PartialEq, mdx::Read, mdx::Write, mdl::Read, mdl::Write)]
#[mdx(sized(tag = LightsChunk::<V>::TAG))]
#[mdl(block = "Light", after_read = "Self::finish_mdl", validate_write = "Self::validate_mdl",
    write_order(node, light_type, attenuation_start, attenuation_end, color, intensity,
        ambient_color, ambient_intensity, shadow_value, casting, shadow_start,
        shadow_end, quadratic, linear, damping, visibility),
    virtual_fields(
        #[mdl(flag = "ShadowCasting", default)]
        #[mdl(get = "Self::mdl_casting", set = "Self::set_mdl_casting")]
        casting: bool,
        #[mdl(
            static_property = "ShadowIntensity",
            default,
            skip_if = "is_zero"
        )]
        #[mdl(get = "Self::mdl_shadow_intensity", slot = "Self::mdl_shadow_intensity_mut")]
        shadow_value: f32,
        #[mdl(
            property = "ShadowCastingStart",
            default = "zero"
        )]
        #[mdl(get = "Self::mdl_shadow_start", slot = "Self::mdl_shadow_start_mut")]
        shadow_start: Animatable<f32>,
        #[mdl(
            property = "ShadowCastingEnd",
            default = "zero"
        )]
        #[mdl(get = "Self::mdl_shadow_end", slot = "Self::mdl_shadow_end_mut")]
        shadow_end: Animatable<f32>,
        #[mdl(
            property = "QuadraticFalloff",
            default = "quadratic"
        )]
        #[mdl(get = "Self::mdl_quadratic", slot = "Self::mdl_quadratic_mut")]
        quadratic: Animatable<f32>,
        #[mdl(
            property = "LinearFalloff",
            default = "zero"
        )]
        #[mdl(get = "Self::mdl_linear", slot = "Self::mdl_linear_mut")]
        linear: Animatable<f32>,
        #[mdl(
            property = "Damping",
            default = "damping"
        )]
        #[mdl(get = "Self::mdl_damping", slot = "Self::mdl_damping_mut")]
        damping: Animatable<f32>
    )
)]
pub struct Light<V: ModelVersion> {
    #[mdl(flatten)]
    /// Shared node.
    pub node: Node,
    #[mdl(flatten)]
    /// The kind of illumination.
    pub light_type: LightType,
    #[mdl(skip, default)]
    shadow_casting: V::ShadowCasting,
    #[mdx(tag = *b"KLAS")]
    #[mdl(property = "AttenuationStart", default = "zero")]
    /// Attenuation start distance.
    pub attenuation_start: Animatable<f32>,
    #[mdx(tag = *b"KLAE")]
    #[mdl(property = "AttenuationEnd", default = "zero")]
    /// Attenuation end distance.
    pub attenuation_end: Animatable<f32>,
    #[mdx(tag = *b"KLAC")]
    #[mdl(property = "Color", default = "white")]
    /// RGB light color.
    pub color: Animatable<Color>,
    #[mdx(tag = *b"KLAI")]
    #[mdl(property = "Intensity", default = "zero")]
    /// Light intensity.
    pub intensity: Animatable<f32>,
    #[mdx(tag = *b"KLBC")]
    #[mdl(property = "AmbColor", default = "white")]
    /// Ambient RGB color.
    pub ambient_color: Animatable<Color>,
    #[mdx(tag = *b"KLBI")]
    #[mdl(property = "AmbIntensity", default = "zero")]
    /// Ambient intensity.
    pub ambient_intensity: Animatable<f32>,
    #[mdl(skip, default)]
    shadow_intensity: V::ShadowIntensity,
    #[mdl(skip, default)]
    #[mdx(flatten)]
    shadow_range: V::ShadowRange,
    #[mdl(skip, default)]
    #[mdx(flatten)]
    falloff: V::Falloff,
    #[mdl(skip, default)]
    version: PhantomData<V>,
    #[mdx(tag = *b"KLAV")]
    #[mdl(property = "Visibility")]
    /// Optional visibility animation.
    pub visibility: Option<Track<f32>>,
}

impl<V: ModelVersion> Light<V> {
    /// Creates a light with white colors and the format defaults for versioned fields.
    pub fn new(node: Node, light_type: LightType) -> Self {
        Self {
            node,
            light_type,
            shadow_casting: V::ShadowCasting::default(),
            attenuation_start: Animatable::Static(0.0),
            attenuation_end: Animatable::Static(0.0),
            color: Animatable::Static([1.0; 3]),
            intensity: Animatable::Static(0.0),
            ambient_color: Animatable::Static([1.0; 3]),
            ambient_intensity: Animatable::Static(0.0),
            shadow_intensity: V::ShadowIntensity::default(),
            shadow_range: V::ShadowRange::default(),
            falloff: V::Falloff::default(),
            visibility: None,
            version: PhantomData,
        }
    }

    /// Returns the shadow-casting flag available from version 1300.
    pub fn try_shadow_casting(&self) -> Result<bool, ValueError> {
        self.shadow_casting
            .shadow_casting()
            .map(|value| value != 0)
            .ok_or(ValueError::UnsupportedVersion {
                tag: LightsChunk::<V>::TAG,
                minimum: 1300,
                actual: V::NUMBER,
            })
    }
    /// Sets the shadow-casting flag available from version 1300.
    pub fn try_set_shadow_casting(&mut self, enabled: bool) -> Result<(), ValueError> {
        *self
            .shadow_casting
            .shadow_casting_mut()
            .ok_or(ValueError::UnsupportedVersion {
                tag: LightsChunk::<V>::TAG,
                minimum: 1300,
                actual: V::NUMBER,
            })? = u32::from(enabled);
        Ok(())
    }
    /// Returns shadow intensity, available from version 1200.
    pub fn try_shadow_intensity(&self) -> Result<f32, ValueError> {
        self.shadow_intensity
            .shadow_intensity()
            .ok_or(ValueError::UnsupportedVersion {
                tag: LightsChunk::<V>::TAG,
                minimum: 1200,
                actual: V::NUMBER,
            })
    }
    /// Sets shadow intensity, available from version 1200.
    pub fn try_set_shadow_intensity(&mut self, value: f32) -> Result<(), ValueError> {
        *self
            .shadow_intensity
            .shadow_intensity_mut()
            .ok_or(ValueError::UnsupportedVersion {
                tag: LightsChunk::<V>::TAG,
                minimum: 1200,
                actual: V::NUMBER,
            })? = value;
        Ok(())
    }
    /// Returns shadow-casting start and end, available from version 1300.
    pub fn try_shadow_casting_range(&self) -> Result<LightShadowRange, ValueError> {
        self.shadow_range
            .shadow_casting_range()
            .cloned()
            .ok_or(ValueError::UnsupportedVersion {
                tag: LightsChunk::<V>::TAG,
                minimum: 1300,
                actual: V::NUMBER,
            })
    }
    /// Sets shadow-casting start and end, available from version 1300.
    pub fn try_set_shadow_casting_range(
        &mut self,
        range: LightShadowRange,
    ) -> Result<(), ValueError> {
        *self
            .shadow_range
            .shadow_casting_range_mut()
            .ok_or(ValueError::UnsupportedVersion {
                tag: LightsChunk::<V>::TAG,
                minimum: 1300,
                actual: V::NUMBER,
            })? = range;
        Ok(())
    }
    /// Returns the falloff values used by the game, including older-version defaults.
    pub fn falloff(&self) -> LightFalloff {
        self.falloff.falloff().cloned().unwrap_or_default()
    }
    /// Sets the three serialized falloff fields from version 1600 onward.
    pub fn try_set_falloff(&mut self, falloff: LightFalloff) -> Result<(), ValueError> {
        *self
            .falloff
            .falloff_mut()
            .ok_or(ValueError::UnsupportedVersion {
                tag: LightsChunk::<V>::TAG,
                minimum: 1600,
                actual: V::NUMBER,
            })? = falloff;
        Ok(())
    }
}

impl<V: SupportsLightShadowIntensity> Light<V> {
    /// Returns shadow intensity.
    pub fn shadow_intensity(&self) -> f32 {
        self.try_shadow_intensity().expect("supported version")
    }

    /// Sets shadow intensity.
    pub fn set_shadow_intensity(&mut self, value: f32) {
        self.try_set_shadow_intensity(value)
            .expect("supported version");
    }
}

impl<V: SupportsLightShadowCasting> Light<V> {
    /// Returns whether shadow casting is enabled.
    pub fn shadow_casting(&self) -> bool {
        self.try_shadow_casting().expect("supported version")
    }

    /// Enables or disables shadow casting.
    pub fn set_shadow_casting(&mut self, enabled: bool) {
        self.try_set_shadow_casting(enabled)
            .expect("supported version");
    }

    /// Returns the shadow-casting range.
    pub fn shadow_casting_range(&self) -> LightShadowRange {
        self.try_shadow_casting_range().expect("supported version")
    }

    /// Sets the shadow-casting range.
    pub fn set_shadow_casting_range(&mut self, range: LightShadowRange) {
        self.try_set_shadow_casting_range(range)
            .expect("supported version");
    }
}

impl<V: SupportsLightFalloff> Light<V> {
    /// Sets the serialized falloff coefficients.
    pub fn set_falloff(&mut self, falloff: LightFalloff) {
        self.try_set_falloff(falloff).expect("supported version");
    }
}

impl<V: ModelVersion> Model<V> {
    /// Returns owned copies of `LITE` records in file order.
    pub fn lights(&self) -> Vec<Light<V>> {
        self.collect_chunk_records::<LightsChunk<V>>()
    }

    /// Replaces lights with one `LITE` chunk, removing any duplicate chunks.
    pub fn set_lights(&mut self, lights: &[Light<V>]) {
        self.replace_chunk(LightsChunk::new(lights.to_vec()));
    }
}

impl<V: ModelVersion> Light<V> {
    pub(crate) fn convert_with<T: ModelVersion>(
        &self,
        context: &mut ConversionContext<'_>,
        path: &str,
    ) -> Result<Light<T>, ConversionError> {
        let mut target = Light::<T>::new(self.node.clone(), self.light_type);
        target.attenuation_start = self.attenuation_start.clone();
        target.attenuation_end = self.attenuation_end.clone();
        target.color = self.color.clone();
        target.intensity = self.intensity.clone();
        target.ambient_color = self.ambient_color.clone();
        target.ambient_intensity = self.ambient_intensity.clone();

        context.field(
            self.shadow_casting.shadow_casting(),
            target.shadow_casting.shadow_casting_mut(),
            0,
            &format!("{path}.shadow_casting"),
        )?;
        context.field(
            self.shadow_intensity.shadow_intensity(),
            target.shadow_intensity.shadow_intensity_mut(),
            0.0,
            &format!("{path}.shadow_intensity"),
        )?;
        context.field(
            self.shadow_range.shadow_casting_range().cloned(),
            target.shadow_range.shadow_casting_range_mut(),
            LightShadowRange::default(),
            &format!("{path}.shadow_range"),
        )?;
        context.field(
            self.falloff.falloff().cloned(),
            target.falloff.falloff_mut(),
            LightFalloff::default(),
            &format!("{path}.falloff"),
        )?;
        target.visibility = self.visibility.clone();
        Ok(target)
    }
}

mod mdl_codec;