vrm-runtime 0.1.0

Renderer-agnostic VRM 1.0 loader, validator, animation system, and runtime
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
use glam::Vec3;
use serde::Deserialize;
use vrm_spec::vrmc_materials_mtoon_1_0 as mtoon_spec;

use crate::{ImageId, TextureId};

/// glTF alpha composition mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AlphaMode {
    /// Draws fully opaque without alpha testing or blending.
    #[default]
    Opaque,
    /// Discards fragments below [`Material::alpha_cutoff`].
    Mask,
    /// Uses alpha blending for translucent fragments.
    Blend,
}

/// How MToon outline width is interpreted.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OutlineWidthMode {
    /// Disables the MToon outline.
    #[default]
    None,
    /// Interprets outline width in world-space meters.
    WorldCoordinates,
    /// Interprets outline width as a ratio of the screen height.
    ScreenCoordinates,
}

impl From<mtoon_spec::OutlineWidthMode> for OutlineWidthMode {
    fn from(mode: mtoon_spec::OutlineWidthMode) -> Self {
        match mode {
            mtoon_spec::OutlineWidthMode::None => Self::None,
            mtoon_spec::OutlineWidthMode::WorldCoordinates => Self::WorldCoordinates,
            mtoon_spec::OutlineWidthMode::ScreenCoordinates => Self::ScreenCoordinates,
        }
    }
}

/// UV transform attached to an individual texture reference.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TextureTransform {
    /// UV translation applied after scale and rotation.
    pub offset: [f32; 2],
    /// Counter-clockwise rotation in radians.
    pub rotation: f32,
    /// Per-axis UV scale.
    pub scale: [f32; 2],
}

impl Default for TextureTransform {
    fn default() -> Self {
        Self {
            offset: [0.0, 0.0],
            rotation: 0.0,
            scale: [1.0, 1.0],
        }
    }
}

/// A texture reference with its UV set and local transform.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TextureInfo {
    texture_id: TextureId,
    tex_coord: u32,
    transform: TextureTransform,
}

impl TextureInfo {
    /// Creates a reference to `texture_id` using UV set 0 and the identity transform.
    pub const fn new(texture_id: TextureId) -> Self {
        Self {
            texture_id,
            tex_coord: 0,
            transform: TextureTransform {
                offset: [0.0, 0.0],
                rotation: 0.0,
                scale: [1.0, 1.0],
            },
        }
    }

    /// Selects the UV set sampled by this texture reference.
    pub const fn with_tex_coord(mut self, tex_coord: u32) -> Self {
        self.tex_coord = tex_coord;
        self
    }

    /// Sets the local UV transform applied before sampling.
    pub const fn with_transform(mut self, transform: TextureTransform) -> Self {
        self.transform = transform;
        self
    }

    /// Returns the referenced texture identifier.
    pub fn texture_id(&self) -> TextureId {
        self.texture_id
    }

    /// Returns the selected UV set.
    pub fn tex_coord(&self) -> u32 {
        self.tex_coord
    }

    /// Returns the local UV transform.
    pub fn transform(&self) -> TextureTransform {
        self.transform
    }

    fn from_gltf(info: gltf::texture::Info<'_>) -> Self {
        let transform = info
            .texture_transform()
            .map(|transform| TextureTransform {
                offset: transform.offset(),
                rotation: transform.rotation(),
                scale: transform.scale(),
            })
            .unwrap_or_default();
        let tex_coord = info
            .texture_transform()
            .and_then(|transform| transform.tex_coord())
            .unwrap_or_else(|| info.tex_coord());
        Self {
            texture_id: TextureId::from_index(info.texture().index()),
            tex_coord,
            transform,
        }
    }

    fn from_json(info: &gltf::json::texture::Info) -> Self {
        let transform = info
            .extensions
            .as_ref()
            .and_then(|extensions| extensions.texture_transform.as_ref());
        Self {
            texture_id: TextureId::from_index(info.index.value()),
            tex_coord: transform
                .and_then(|transform| transform.tex_coord)
                .unwrap_or(info.tex_coord),
            transform: transform
                .map(|transform| TextureTransform {
                    offset: transform.offset.0,
                    rotation: transform.rotation.0,
                    scale: transform.scale.0,
                })
                .unwrap_or_default(),
        }
    }
}

/// A normal map reference and its scale multiplier.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct NormalTextureInfo {
    /// The referenced normal-map texture, UV set, and transform.
    pub texture: TextureInfo,
    /// Multiplier applied to the tangent-space X and Y components.
    pub scale: f32,
}

impl NormalTextureInfo {
    /// Creates a normal-map reference with the glTF default scale of one.
    pub const fn new(texture: TextureInfo) -> Self {
        Self {
            texture,
            scale: 1.0,
        }
    }

    /// Sets the normal-map scale multiplier.
    pub const fn with_scale(mut self, scale: f32) -> Self {
        self.scale = scale;
        self
    }
}

/// An occlusion map reference and its strength multiplier.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct OcclusionTextureInfo {
    /// The referenced occlusion texture, UV set, and transform.
    pub texture: TextureInfo,
    /// Occlusion influence in the inclusive range from zero to one.
    pub strength: f32,
}

impl OcclusionTextureInfo {
    /// Creates an occlusion-map reference with the glTF default strength of one.
    pub const fn new(texture: TextureInfo) -> Self {
        Self {
            texture,
            strength: 1.0,
        }
    }

    /// Sets the occlusion strength multiplier.
    pub const fn with_strength(mut self, strength: f32) -> Self {
        self.strength = strength;
        self
    }
}

/// The material model that a renderer should evaluate.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum MaterialShadingModel {
    /// The core glTF metallic-roughness model.
    #[default]
    PbrMetallicRoughness,
    /// The `KHR_materials_unlit` model.
    Unlit,
    /// The `VRMC_materials_mtoon` model.
    MToon,
}

/// The extension that supplied the effective emissive multiplier.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum EmissiveStrengthSource {
    /// Neither emissive-strength extension was present, so the multiplier is one.
    #[default]
    Default,
    /// `KHR_materials_emissive_strength` supplied the multiplier.
    KhrMaterialsEmissiveStrength,
    /// The archived `VRMC_materials_hdr_emissiveMultiplier` extension supplied it.
    VrmcMaterialsHdrEmissiveMultiplier,
}

/// Magnification filter of a texture sampler.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MagFilter {
    /// Selects the nearest texel.
    Nearest,
    /// Linearly interpolates adjacent texels.
    Linear,
}

/// Minification filter of a texture sampler.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MinFilter {
    /// Selects the nearest texel without mipmapping.
    Nearest,
    /// Linearly interpolates texels without mipmapping.
    Linear,
    /// Selects the nearest texel from the nearest mip level.
    NearestMipmapNearest,
    /// Linearly interpolates texels from the nearest mip level.
    LinearMipmapNearest,
    /// Selects nearest texels and blends between mip levels.
    NearestMipmapLinear,
    /// Linearly interpolates texels and blends between mip levels.
    LinearMipmapLinear,
}

/// Texture coordinate wrapping behavior.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WrapMode {
    /// Clamps texture coordinates to edge texels.
    ClampToEdge,
    /// Repeats the texture while mirroring every other interval.
    MirroredRepeat,
    /// Repeats the texture at every integer boundary.
    Repeat,
}

/// Renderer-independent texture sampler data.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TextureSampler {
    /// Optional magnification filter; `None` uses the glTF default.
    pub mag_filter: Option<MagFilter>,
    /// Optional minification filter; `None` uses the glTF default.
    pub min_filter: Option<MinFilter>,
    /// Horizontal texture-coordinate wrapping mode.
    pub wrap_s: WrapMode,
    /// Vertical texture-coordinate wrapping mode.
    pub wrap_t: WrapMode,
}

impl Default for TextureSampler {
    fn default() -> Self {
        Self {
            mag_filter: None,
            min_filter: None,
            wrap_s: WrapMode::Repeat,
            wrap_t: WrapMode::Repeat,
        }
    }
}

/// A glTF texture resolving a sampler and image separately.
#[derive(Debug, Clone)]
pub struct AvatarTexture {
    image_id: ImageId,
    sampler: TextureSampler,
}

impl AvatarTexture {
    /// Creates a texture that samples `image_id` with the glTF sampler defaults.
    pub fn new(image_id: ImageId) -> Self {
        Self {
            image_id,
            sampler: TextureSampler::default(),
        }
    }

    /// Replaces the texture sampler.
    pub const fn with_sampler(mut self, sampler: TextureSampler) -> Self {
        self.sampler = sampler;
        self
    }

    /// Returns the image sampled by this texture.
    pub fn image_id(&self) -> ImageId {
        self.image_id
    }

    /// Returns the renderer-independent sampler state.
    pub fn sampler(&self) -> TextureSampler {
        self.sampler
    }
}

/// Common glTF material data with an optional MToon extension.
#[derive(Debug, Clone)]
pub struct Material {
    /// Linear RGBA multiplier for the base color.
    pub base_color_factor: [f32; 4],
    /// Metallic multiplier used by the glTF PBR model.
    pub metallic_factor: f32,
    /// Roughness multiplier used by the glTF PBR model.
    pub roughness_factor: f32,
    /// Linear RGB emissive color before the HDR strength multiplier.
    pub emissive_factor: [f32; 3],
    base_color_texture: Option<TextureInfo>,
    metallic_roughness_texture: Option<TextureInfo>,
    normal_texture: Option<NormalTextureInfo>,
    occlusion_texture: Option<OcclusionTextureInfo>,
    emissive_texture: Option<TextureInfo>,
    unlit: bool,
    emissive_strength: f32,
    emissive_strength_source: EmissiveStrengthSource,
    legacy_emissive_multiplier: Option<f32>,
    /// Alpha composition mode used by the material.
    pub alpha_mode: AlphaMode,
    /// Alpha-test threshold used when [`Self::alpha_mode`] is [`AlphaMode::Mask`].
    pub alpha_cutoff: f32,
    double_sided: bool,
    mtoon: Option<MToonMaterial>,
}

impl Default for Material {
    fn default() -> Self {
        Self {
            base_color_factor: [1.0; 4],
            metallic_factor: 1.0,
            roughness_factor: 1.0,
            emissive_factor: [0.0; 3],
            base_color_texture: None,
            metallic_roughness_texture: None,
            normal_texture: None,
            occlusion_texture: None,
            emissive_texture: None,
            unlit: false,
            emissive_strength: 1.0,
            emissive_strength_source: EmissiveStrengthSource::Default,
            legacy_emissive_multiplier: None,
            alpha_mode: AlphaMode::Opaque,
            alpha_cutoff: 0.5,
            double_sided: false,
            mtoon: None,
        }
    }
}

impl Material {
    /// Creates a glTF metallic-roughness material with specification defaults.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the base-color factor shared by the supported shading models.
    pub const fn with_base_color_factor(mut self, factor: [f32; 4]) -> Self {
        self.base_color_factor = factor;
        self
    }

    /// Sets the metallic factor of the core glTF material model.
    pub const fn with_metallic_factor(mut self, factor: f32) -> Self {
        self.metallic_factor = factor;
        self
    }

    /// Sets the roughness factor of the core glTF material model.
    pub const fn with_roughness_factor(mut self, factor: f32) -> Self {
        self.roughness_factor = factor;
        self
    }

    /// Sets the emissive color before applying [`Self::emissive_strength`].
    pub const fn with_emissive_factor(mut self, factor: [f32; 3]) -> Self {
        self.emissive_factor = factor;
        self
    }

    /// Sets the base-color texture.
    pub const fn with_base_color_texture(mut self, texture: TextureInfo) -> Self {
        self.base_color_texture = Some(texture);
        self
    }

    /// Sets the texture whose green and blue channels provide roughness and metalness.
    pub const fn with_metallic_roughness_texture(mut self, texture: TextureInfo) -> Self {
        self.metallic_roughness_texture = Some(texture);
        self
    }

    /// Sets the tangent-space normal map.
    pub const fn with_normal_texture(mut self, texture: NormalTextureInfo) -> Self {
        self.normal_texture = Some(texture);
        self
    }

    /// Sets the red-channel occlusion map.
    pub const fn with_occlusion_texture(mut self, texture: OcclusionTextureInfo) -> Self {
        self.occlusion_texture = Some(texture);
        self
    }

    /// Sets the emissive texture.
    pub const fn with_emissive_texture(mut self, texture: TextureInfo) -> Self {
        self.emissive_texture = Some(texture);
        self
    }

    /// Enables or disables the `KHR_materials_unlit` shading model.
    pub const fn with_unlit(mut self, unlit: bool) -> Self {
        self.unlit = unlit;
        self
    }

    /// Sets the `KHR_materials_emissive_strength` multiplier.
    pub const fn with_emissive_strength(mut self, strength: f32) -> Self {
        self.emissive_strength = strength;
        self.emissive_strength_source = EmissiveStrengthSource::KhrMaterialsEmissiveStrength;
        self.legacy_emissive_multiplier = None;
        self
    }

    /// Sets the alpha composition mode.
    pub const fn with_alpha_mode(mut self, alpha_mode: AlphaMode) -> Self {
        self.alpha_mode = alpha_mode;
        self
    }

    /// Sets the cutoff used by [`AlphaMode::Mask`].
    pub const fn with_alpha_cutoff(mut self, alpha_cutoff: f32) -> Self {
        self.alpha_cutoff = alpha_cutoff;
        self
    }

    /// Enables or disables rendering both sides of each triangle.
    pub const fn with_double_sided(mut self, double_sided: bool) -> Self {
        self.double_sided = double_sided;
        self
    }

    /// Adds an MToon model, which takes precedence over Unlit and PBR rendering.
    pub fn with_mtoon(mut self, mtoon: MToonMaterial) -> Self {
        self.mtoon = Some(mtoon);
        self
    }

    /// Returns the base-color texture used by every supported material model.
    pub fn base_color_texture(&self) -> Option<&TextureInfo> {
        self.base_color_texture.as_ref()
    }

    /// Returns the texture whose green and blue channels contain roughness and metalness.
    pub fn metallic_roughness_texture(&self) -> Option<&TextureInfo> {
        self.metallic_roughness_texture.as_ref()
    }

    /// Returns the tangent-space normal map and its scale.
    pub fn normal_texture(&self) -> Option<&NormalTextureInfo> {
        self.normal_texture.as_ref()
    }

    /// Returns the red-channel occlusion map and its strength.
    pub fn occlusion_texture(&self) -> Option<&OcclusionTextureInfo> {
        self.occlusion_texture.as_ref()
    }

    /// Returns the emissive texture.
    pub fn emissive_texture(&self) -> Option<&TextureInfo> {
        self.emissive_texture.as_ref()
    }

    /// Returns whether `KHR_materials_unlit` was declared.
    ///
    /// This remains `true` when MToon is also present. Use [`Self::shading_model`]
    /// when selecting a renderer because MToon takes precedence over Unlit.
    pub fn unlit(&self) -> bool {
        self.unlit
    }

    /// Returns the selected emissive multiplier, defaulting to one.
    ///
    /// `KHR_materials_emissive_strength` takes precedence over the archived VRM
    /// multiplier when both extensions are present.
    pub fn emissive_strength(&self) -> f32 {
        self.emissive_strength
    }

    /// Returns the extension that supplied [`Self::emissive_strength`].
    pub fn emissive_strength_source(&self) -> EmissiveStrengthSource {
        self.emissive_strength_source
    }

    /// Returns the archived VRM emissive multiplier when it was declared.
    ///
    /// The value is retained even when the modern KHR extension overrides it so
    /// callers can emit a deprecation or precedence diagnostic.
    pub fn legacy_emissive_multiplier(&self) -> Option<f32> {
        self.legacy_emissive_multiplier
    }

    /// Returns `emissive_factor` after applying the selected HDR multiplier.
    pub fn effective_emissive_factor(&self) -> [f32; 3] {
        self.emissive_factor
            .map(|component| component * self.emissive_strength)
    }

    /// Returns the material model that takes precedence for rendering.
    pub fn shading_model(&self) -> MaterialShadingModel {
        if self.mtoon.is_some() {
            MaterialShadingModel::MToon
        } else if self.unlit {
            MaterialShadingModel::Unlit
        } else {
            MaterialShadingModel::PbrMetallicRoughness
        }
    }

    /// Reports whether back-face culling must be disabled.
    pub fn double_sided(&self) -> bool {
        self.double_sided
    }

    /// Returns the MToon extension parameters, if present.
    pub fn mtoon(&self) -> Option<&MToonMaterial> {
        self.mtoon.as_ref()
    }

    fn load(
        material: &gltf::Material<'_>,
        mtoon: Option<&mtoon_spec::VrmcMaterialsMtoonSchema>,
        texture_count: usize,
    ) -> Result<Self, crate::LoadError> {
        let pbr = material.pbr_metallic_roughness();
        let material_index = material.index().unwrap_or(0);
        let legacy_emissive_multiplier = load_legacy_emissive_multiplier(material, material_index)?;
        let khr_emissive_strength = material.emissive_strength();
        if let Some(value) = khr_emissive_strength {
            validate_emissive_strength(
                value,
                material_index,
                "KHR_materials_emissive_strength",
                "emissiveStrength",
            )?;
        }
        let (emissive_strength, emissive_strength_source) =
            if let Some(value) = khr_emissive_strength {
                (value, EmissiveStrengthSource::KhrMaterialsEmissiveStrength)
            } else if let Some(value) = legacy_emissive_multiplier {
                (
                    value,
                    EmissiveStrengthSource::VrmcMaterialsHdrEmissiveMultiplier,
                )
            } else {
                (1.0, EmissiveStrengthSource::Default)
            };

        let mtoon = mtoon
            .map(MToonMaterial::load)
            .transpose()
            .map_err(crate::LoadError::InvalidVrm)?;
        let loaded = Self {
            base_color_factor: pbr.base_color_factor(),
            metallic_factor: pbr.metallic_factor(),
            roughness_factor: pbr.roughness_factor(),
            emissive_factor: material.emissive_factor(),
            base_color_texture: pbr.base_color_texture().map(TextureInfo::from_gltf),
            metallic_roughness_texture: pbr
                .metallic_roughness_texture()
                .map(TextureInfo::from_gltf),
            normal_texture: material.normal_texture().map(|info| {
                let (transform, transformed_tex_coord) =
                    extension_transform(info.extension_value("KHR_texture_transform"));
                NormalTextureInfo {
                    texture: TextureInfo {
                        texture_id: TextureId::from_index(info.texture().index()),
                        tex_coord: transformed_tex_coord.unwrap_or_else(|| info.tex_coord()),
                        transform,
                    },
                    scale: info.scale(),
                }
            }),
            occlusion_texture: material.occlusion_texture().map(|info| {
                let (transform, transformed_tex_coord) =
                    extension_transform(info.extension_value("KHR_texture_transform"));
                OcclusionTextureInfo {
                    texture: TextureInfo {
                        texture_id: TextureId::from_index(info.texture().index()),
                        tex_coord: transformed_tex_coord.unwrap_or_else(|| info.tex_coord()),
                        transform,
                    },
                    strength: info.strength(),
                }
            }),
            emissive_texture: material.emissive_texture().map(TextureInfo::from_gltf),
            unlit: material.unlit(),
            emissive_strength,
            emissive_strength_source,
            legacy_emissive_multiplier,
            alpha_mode: match material.alpha_mode() {
                gltf::material::AlphaMode::Opaque => AlphaMode::Opaque,
                gltf::material::AlphaMode::Mask => AlphaMode::Mask,
                gltf::material::AlphaMode::Blend => AlphaMode::Blend,
            },
            alpha_cutoff: material.alpha_cutoff().unwrap_or(0.5),
            double_sided: material.double_sided(),
            mtoon,
        };
        loaded
            .validate_programmatic(material_index, texture_count)
            .map_err(crate::LoadError::InvalidVrm)?;
        Ok(loaded)
    }

    pub(crate) fn validate_programmatic(
        &self,
        material_index: usize,
        texture_count: usize,
    ) -> Result<(), String> {
        let label = format!("material {material_index}");
        if !unit_slice(&self.base_color_factor)
            || !unit_value(self.metallic_factor)
            || !unit_value(self.roughness_factor)
            || !unit_slice(&self.emissive_factor)
        {
            return Err(format!(
                "{label} color, metallic, roughness, and emissive factors must be finite and within 0..=1"
            ));
        }
        if !self.emissive_strength.is_finite() || self.emissive_strength < 0.0 {
            return Err(format!(
                "{label} emissive strength must be finite and non-negative"
            ));
        }
        if !self.alpha_cutoff.is_finite() || self.alpha_cutoff < 0.0 {
            return Err(format!(
                "{label} alpha cutoff must be finite and non-negative"
            ));
        }

        for (name, texture) in [
            ("base color", self.base_color_texture.as_ref()),
            (
                "metallic-roughness",
                self.metallic_roughness_texture.as_ref(),
            ),
            (
                "normal",
                self.normal_texture.as_ref().map(|value| &value.texture),
            ),
            (
                "occlusion",
                self.occlusion_texture.as_ref().map(|value| &value.texture),
            ),
            ("emissive", self.emissive_texture.as_ref()),
        ] {
            validate_programmatic_texture(texture, texture_count, &label, name)?;
        }
        if self
            .normal_texture
            .as_ref()
            .is_some_and(|texture| !texture.scale.is_finite())
        {
            return Err(format!("{label} normal texture scale must be finite"));
        }
        if self.occlusion_texture.as_ref().is_some_and(|texture| {
            !texture.strength.is_finite() || !(0.0..=1.0).contains(&texture.strength)
        }) {
            return Err(format!(
                "{label} occlusion texture strength must be finite and within 0..=1"
            ));
        }

        if let Some(mtoon) = &self.mtoon {
            mtoon.validate_programmatic(&label, texture_count)?;
        }
        Ok(())
    }
}

fn validate_programmatic_texture(
    texture: Option<&TextureInfo>,
    texture_count: usize,
    material_label: &str,
    texture_name: &str,
) -> Result<(), String> {
    let Some(texture) = texture else {
        return Ok(());
    };
    if texture.texture_id.index() >= texture_count {
        return Err(format!(
            "{material_label} {texture_name} texture references a missing texture"
        ));
    }
    let transform = texture.transform;
    if !transform.rotation.is_finite()
        || transform.offset.iter().any(|value| !value.is_finite())
        || transform.scale.iter().any(|value| !value.is_finite())
    {
        return Err(format!(
            "{material_label} {texture_name} texture has a non-finite UV transform"
        ));
    }
    Ok(())
}

fn unit_value(value: f32) -> bool {
    value.is_finite() && (0.0..=1.0).contains(&value)
}

fn unit_slice(values: &[f32]) -> bool {
    values.iter().copied().all(unit_value)
}

const VRMC_MATERIALS_HDR_EMISSIVE_MULTIPLIER: &str = "VRMC_materials_hdr_emissiveMultiplier";

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct LegacyHdrEmissiveMultiplier {
    emissive_multiplier: f32,
}

fn load_legacy_emissive_multiplier(
    material: &gltf::Material<'_>,
    material_index: usize,
) -> Result<Option<f32>, crate::LoadError> {
    let Some(value) = material.extension_value(VRMC_MATERIALS_HDR_EMISSIVE_MULTIPLIER) else {
        return Ok(None);
    };
    let extension = serde_json::from_value::<LegacyHdrEmissiveMultiplier>(value.to_owned())
        .map_err(|source| crate::LoadError::InvalidExtension {
            extension: VRMC_MATERIALS_HDR_EMISSIVE_MULTIPLIER,
            location: format!(
                "/materials/{material_index}/extensions/{VRMC_MATERIALS_HDR_EMISSIVE_MULTIPLIER}"
            ),
            source,
        })?;
    validate_emissive_strength(
        extension.emissive_multiplier,
        material_index,
        VRMC_MATERIALS_HDR_EMISSIVE_MULTIPLIER,
        "emissiveMultiplier",
    )?;
    Ok(Some(extension.emissive_multiplier))
}

fn validate_emissive_strength(
    value: f32,
    material_index: usize,
    extension: &str,
    property: &str,
) -> Result<(), crate::LoadError> {
    if value.is_finite() && value >= 0.0 {
        return Ok(());
    }
    Err(crate::LoadError::InvalidVrm(format!(
        "/materials/{material_index}/extensions/{extension}/{property} must be finite and non-negative"
    )))
}

/// Parameters defined by `VRMC_materials_mtoon` only.
#[derive(Debug, Clone)]
pub struct MToonMaterial {
    /// Enables depth writes for transparent materials.
    pub transparent_with_z_write: bool,
    /// Offset in the specification-defined MToon render queue range.
    pub render_queue_offset_number: i32,
    /// Linear RGB shadow-side color multiplier.
    pub shade_color: Vec3,
    /// Optional texture multiplied into [`Self::shade_color`].
    pub shade_multiply_texture: Option<TextureInfo>,
    /// Shifts the boundary between lit and shaded regions.
    pub shading_shift_factor: f32,
    /// Optional texture that varies the shading shift.
    pub shading_shift_texture: Option<TextureInfo>,
    /// Multiplier applied to the shading-shift texture value.
    pub shading_shift_texture_scale: f32,
    /// Controls the softness of the lit-to-shade transition.
    pub shading_toony_factor: f32,
    /// Controls how strongly global illumination affects shading.
    pub gi_equalization_factor: f32,
    /// Linear RGB multiplier for the matcap contribution.
    pub matcap_factor: Vec3,
    /// Optional sphere-mapped matcap texture.
    pub matcap_texture: Option<TextureInfo>,
    /// Linear RGB color of the procedural rim-light contribution.
    pub parametric_rim_color_factor: Vec3,
    /// Fresnel exponent of the procedural rim light.
    pub parametric_rim_fresnel_power_factor: f32,
    /// Additive lift applied before evaluating the rim-light Fresnel term.
    pub parametric_rim_lift_factor: f32,
    /// Optional texture multiplied into the rim-light contribution.
    pub rim_multiply_texture: Option<TextureInfo>,
    /// Mix factor between direct and indirect rim lighting.
    pub rim_lighting_mix_factor: f32,
    /// Coordinate system used to interpret outline width.
    pub outline_width_mode: OutlineWidthMode,
    /// Base outline width in the units selected by [`Self::outline_width_mode`].
    pub outline_width_factor: f32,
    /// Optional texture multiplied into the outline width.
    pub outline_width_multiply_texture: Option<TextureInfo>,
    /// Linear RGB outline color.
    pub outline_color_factor: Vec3,
    /// Mix factor between unlit and lit outline color.
    pub outline_lighting_mix_factor: f32,
    /// Optional mask controlling which pixels receive UV animation.
    pub uv_animation_mask_texture: Option<TextureInfo>,
    /// Horizontal UV scroll speed in UV units per second.
    pub uv_animation_scroll_x_speed_factor: f32,
    /// Vertical UV scroll speed in UV units per second.
    pub uv_animation_scroll_y_speed_factor: f32,
    /// Counter-clockwise UV rotation speed in radians per second.
    pub uv_animation_rotation_speed_factor: f32,
}

impl Default for MToonMaterial {
    fn default() -> Self {
        Self {
            transparent_with_z_write: false,
            render_queue_offset_number: 0,
            shade_color: Vec3::ONE,
            shade_multiply_texture: None,
            shading_shift_factor: 0.0,
            shading_shift_texture: None,
            shading_shift_texture_scale: 1.0,
            shading_toony_factor: 0.9,
            gi_equalization_factor: 0.9,
            matcap_factor: Vec3::ONE,
            matcap_texture: None,
            parametric_rim_color_factor: Vec3::ZERO,
            parametric_rim_fresnel_power_factor: 5.0,
            parametric_rim_lift_factor: 0.0,
            rim_multiply_texture: None,
            rim_lighting_mix_factor: 1.0,
            outline_width_mode: OutlineWidthMode::None,
            outline_width_factor: 0.0,
            outline_width_multiply_texture: None,
            outline_color_factor: Vec3::ZERO,
            outline_lighting_mix_factor: 1.0,
            uv_animation_mask_texture: None,
            uv_animation_scroll_x_speed_factor: 0.0,
            uv_animation_scroll_y_speed_factor: 0.0,
            uv_animation_rotation_speed_factor: 0.0,
        }
    }
}

impl MToonMaterial {
    /// Creates an MToon configuration using the VRM 1.0 specification defaults.
    pub fn new() -> Self {
        Self::default()
    }

    fn load(schema: &mtoon_spec::VrmcMaterialsMtoonSchema) -> Result<Self, String> {
        let render_queue_offset_number =
            i32::try_from(schema.render_queue_offset_number.unwrap_or(0))
                .map_err(|_| "MToon render queue offset is not representable as i32".to_string())?;
        Ok(Self {
            transparent_with_z_write: schema.transparent_with_z_write.unwrap_or(false),
            render_queue_offset_number,
            shade_color: color(schema.shade_color_factor, Vec3::ONE),
            shade_multiply_texture: schema
                .shade_multiply_texture
                .as_ref()
                .map(TextureInfo::from_json),
            shading_shift_factor: schema.shading_shift_factor.unwrap_or(0.0) as f32,
            shading_shift_texture: schema
                .shading_shift_texture
                .as_ref()
                .map(shading_shift_texture)
                .transpose()?,
            shading_shift_texture_scale: schema
                .shading_shift_texture
                .as_ref()
                .and_then(|texture| texture.scale)
                .unwrap_or(1.0) as f32,
            shading_toony_factor: schema.shading_toony_factor.unwrap_or(0.9) as f32,
            gi_equalization_factor: schema.gi_equalization_factor.unwrap_or(0.9) as f32,
            matcap_factor: color(schema.matcap_factor, Vec3::ONE),
            matcap_texture: schema.matcap_texture.as_ref().map(TextureInfo::from_json),
            parametric_rim_color_factor: color(schema.parametric_rim_color_factor, Vec3::ZERO),
            parametric_rim_fresnel_power_factor: schema
                .parametric_rim_fresnel_power_factor
                .unwrap_or(5.0) as f32,
            parametric_rim_lift_factor: schema.parametric_rim_lift_factor.unwrap_or(0.0) as f32,
            rim_multiply_texture: schema
                .rim_multiply_texture
                .as_ref()
                .map(TextureInfo::from_json),
            rim_lighting_mix_factor: schema.rim_lighting_mix_factor.unwrap_or(1.0) as f32,
            outline_width_mode: schema
                .outline_width_mode
                .map(Into::into)
                .unwrap_or_default(),
            outline_width_factor: schema.outline_width_factor.unwrap_or(0.0) as f32,
            outline_width_multiply_texture: schema
                .outline_width_multiply_texture
                .as_ref()
                .map(TextureInfo::from_json),
            outline_color_factor: color(schema.outline_color_factor, Vec3::ZERO),
            outline_lighting_mix_factor: schema.outline_lighting_mix_factor.unwrap_or(1.0) as f32,
            uv_animation_mask_texture: schema
                .uv_animation_mask_texture
                .as_ref()
                .map(TextureInfo::from_json),
            uv_animation_scroll_x_speed_factor: schema
                .uv_animation_scroll_x_speed_factor
                .unwrap_or(0.0) as f32,
            uv_animation_scroll_y_speed_factor: schema
                .uv_animation_scroll_y_speed_factor
                .unwrap_or(0.0) as f32,
            uv_animation_rotation_speed_factor: schema
                .uv_animation_rotation_speed_factor
                .unwrap_or(0.0) as f32,
        })
    }

    fn validate_programmatic(
        &self,
        material_label: &str,
        texture_count: usize,
    ) -> Result<(), String> {
        if !(-9..=9).contains(&self.render_queue_offset_number) {
            return Err(format!(
                "{material_label} MToon render queue offset must be within -9..=9"
            ));
        }
        if !unit_slice(&self.shade_color.to_array())
            || !unit_slice(&self.matcap_factor.to_array())
            || !unit_slice(&self.parametric_rim_color_factor.to_array())
            || !unit_slice(&self.outline_color_factor.to_array())
        {
            return Err(format!(
                "{material_label} MToon color factors must be finite and within 0..=1"
            ));
        }
        if !unit_value(self.shading_toony_factor)
            || !unit_value(self.gi_equalization_factor)
            || !unit_value(self.rim_lighting_mix_factor)
            || !unit_value(self.outline_lighting_mix_factor)
        {
            return Err(format!(
                "{material_label} MToon mix factors must be finite and within 0..=1"
            ));
        }
        if !self.parametric_rim_fresnel_power_factor.is_finite()
            || self.parametric_rim_fresnel_power_factor < 0.0
            || !self.outline_width_factor.is_finite()
            || self.outline_width_factor < 0.0
        {
            return Err(format!(
                "{material_label} MToon rim power and outline width must be finite and non-negative"
            ));
        }
        if [
            self.shading_shift_factor,
            self.shading_shift_texture_scale,
            self.parametric_rim_lift_factor,
            self.uv_animation_scroll_x_speed_factor,
            self.uv_animation_scroll_y_speed_factor,
            self.uv_animation_rotation_speed_factor,
        ]
        .iter()
        .any(|value| !value.is_finite())
        {
            return Err(format!(
                "{material_label} MToon scalar parameters must be finite"
            ));
        }

        for (name, texture) in [
            ("shade multiply", self.shade_multiply_texture.as_ref()),
            ("shading shift", self.shading_shift_texture.as_ref()),
            ("matcap", self.matcap_texture.as_ref()),
            ("rim multiply", self.rim_multiply_texture.as_ref()),
            (
                "outline width multiply",
                self.outline_width_multiply_texture.as_ref(),
            ),
            ("UV animation mask", self.uv_animation_mask_texture.as_ref()),
        ] {
            validate_programmatic_texture(texture, texture_count, material_label, name)?;
        }
        Ok(())
    }
}

fn color(value: Option<[f64; 3]>, default: Vec3) -> Vec3 {
    value
        .map(|value| Vec3::new(value[0] as f32, value[1] as f32, value[2] as f32))
        .unwrap_or(default)
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct RawTextureTransform {
    #[serde(default)]
    offset: Option<[f32; 2]>,
    #[serde(default)]
    rotation: Option<f32>,
    #[serde(default)]
    scale: Option<[f32; 2]>,
    #[serde(default)]
    tex_coord: Option<u32>,
}

pub(crate) fn extension_transform(
    value: Option<&serde_json::Value>,
) -> (TextureTransform, Option<u32>) {
    let Some(transform) =
        value.and_then(|value| serde_json::from_value::<RawTextureTransform>(value.clone()).ok())
    else {
        return (TextureTransform::default(), None);
    };
    (
        TextureTransform {
            offset: transform.offset.unwrap_or([0.0, 0.0]),
            rotation: transform.rotation.unwrap_or(0.0),
            scale: transform.scale.unwrap_or([1.0, 1.0]),
        },
        transform.tex_coord,
    )
}

fn shading_shift_texture(
    info: &mtoon_spec::ShadingShiftTextureInfo,
) -> Result<TextureInfo, String> {
    let extension_value = info
        .extensions
        .as_ref()
        .and_then(|extensions| extensions.get("KHR_texture_transform"))
        .map(|extension| {
            serde_json::Value::Object(
                extension
                    .iter()
                    .filter_map(|(key, value)| value.clone().map(|value| (key.clone(), value)))
                    .collect(),
            )
        });
    let (transform, transformed_tex_coord) = match extension_value {
        Some(value) => {
            let transform = serde_json::from_value::<RawTextureTransform>(value)
                .map_err(|error| format!("invalid MToon shading-shift UV transform: {error}"))?;
            (
                TextureTransform {
                    offset: transform.offset.unwrap_or([0.0, 0.0]),
                    rotation: transform.rotation.unwrap_or(0.0),
                    scale: transform.scale.unwrap_or([1.0, 1.0]),
                },
                transform.tex_coord,
            )
        }
        None => (TextureTransform::default(), None),
    };
    Ok(TextureInfo {
        texture_id: TextureId::from_index(info.index.value()),
        tex_coord: transformed_tex_coord.unwrap_or_else(|| {
            info.tex_coord
                .map(|value| value.value() as u32)
                .unwrap_or(0)
        }),
        transform,
    })
}

fn map_mag_filter(filter: gltf::texture::MagFilter) -> MagFilter {
    match filter {
        gltf::texture::MagFilter::Nearest => MagFilter::Nearest,
        gltf::texture::MagFilter::Linear => MagFilter::Linear,
    }
}

fn map_min_filter(filter: gltf::texture::MinFilter) -> MinFilter {
    match filter {
        gltf::texture::MinFilter::Nearest => MinFilter::Nearest,
        gltf::texture::MinFilter::Linear => MinFilter::Linear,
        gltf::texture::MinFilter::NearestMipmapNearest => MinFilter::NearestMipmapNearest,
        gltf::texture::MinFilter::LinearMipmapNearest => MinFilter::LinearMipmapNearest,
        gltf::texture::MinFilter::NearestMipmapLinear => MinFilter::NearestMipmapLinear,
        gltf::texture::MinFilter::LinearMipmapLinear => MinFilter::LinearMipmapLinear,
    }
}

fn map_wrap_mode(mode: gltf::texture::WrappingMode) -> WrapMode {
    match mode {
        gltf::texture::WrappingMode::ClampToEdge => WrapMode::ClampToEdge,
        gltf::texture::WrappingMode::MirroredRepeat => WrapMode::MirroredRepeat,
        gltf::texture::WrappingMode::Repeat => WrapMode::Repeat,
    }
}

pub(crate) fn load_textures(doc: &gltf::Document) -> Vec<AvatarTexture> {
    doc.textures()
        .map(|texture| {
            let sampler = texture.sampler();
            AvatarTexture {
                image_id: ImageId::from_index(texture.source().index()),
                sampler: TextureSampler {
                    mag_filter: sampler.mag_filter().map(map_mag_filter),
                    min_filter: sampler.min_filter().map(map_min_filter),
                    wrap_s: map_wrap_mode(sampler.wrap_s()),
                    wrap_t: map_wrap_mode(sampler.wrap_t()),
                },
            }
        })
        .collect()
}

pub(crate) fn load_materials(doc: &gltf::Document) -> Result<Vec<Material>, crate::LoadError> {
    use mtoon_spec::VRMC_MATERIALS_MTOON;

    doc.materials()
        .map(|material| {
            let mtoon = match material.extension_value(VRMC_MATERIALS_MTOON) {
                Some(value) => {
                    let schema = serde_json::from_value::<mtoon_spec::VrmcMaterialsMtoonSchema>(
                        value.to_owned(),
                    )
                    .map_err(|source| crate::LoadError::InvalidExtension {
                        extension: VRMC_MATERIALS_MTOON,
                        location: format!("/materials/{}", material.index().unwrap_or(0)),
                        source,
                    })?;
                    if schema.spec_version != "1.0" {
                        return Err(crate::LoadError::InvalidVrm(format!(
                            "/materials/{}/extensions/{VRMC_MATERIALS_MTOON}/specVersion must be `1.0`",
                            material.index().unwrap_or(0)
                        )));
                    }
                    Some(schema)
                }
                None => None,
            };
            Material::load(&material, mtoon.as_ref(), doc.textures().count())
        })
        .collect()
}

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

    fn load_test_material(material: serde_json::Value) -> Result<Material, crate::LoadError> {
        let document = serde_json::json!({
            "asset": { "version": "2.0" },
            "extensionsUsed": [
                "KHR_materials_unlit",
                "KHR_materials_emissive_strength",
                "KHR_texture_transform",
                "VRMC_materials_hdr_emissiveMultiplier",
                "VRMC_materials_mtoon"
            ],
            "images": [
                { "uri": "first.png" },
                { "uri": "second.png" }
            ],
            "textures": [
                { "source": 0 },
                { "source": 1 }
            ],
            "materials": [material]
        });
        let bytes = serde_json::to_vec(&document).expect("test glTF JSON must serialize");
        let gltf = gltf::Gltf::from_slice(&bytes).expect("test glTF JSON must parse");
        load_materials(&gltf.document).map(|mut materials| materials.remove(0))
    }

    #[test]
    fn shading_shift_texture_preserves_khr_texture_transform() {
        let info: mtoon_spec::ShadingShiftTextureInfo = serde_json::from_value(serde_json::json!({
            "index": 0,
            "texCoord": 1,
            "extensions": {
                "KHR_texture_transform": {
                    "offset": [0.25, 0.5],
                    "rotation": 0.75,
                    "scale": [2.0, 3.0],
                    "texCoord": 2
                }
            }
        }))
        .expect("the texture fixture must deserialize");

        let texture = shading_shift_texture(&info).expect("the UV transform must be valid");

        assert_eq!(texture.tex_coord(), 2);
        assert_eq!(texture.transform().offset, [0.25, 0.5]);
        assert_eq!(texture.transform().rotation, 0.75);
        assert_eq!(texture.transform().scale, [2.0, 3.0]);
    }

    #[test]
    fn loads_unlit_and_common_pbr_textures() {
        let material = load_test_material(serde_json::json!({
            "pbrMetallicRoughness": {
                "metallicRoughnessTexture": {
                    "index": 0,
                    "texCoord": 1,
                    "extensions": {
                        "KHR_texture_transform": {
                            "offset": [0.25, 0.5],
                            "texCoord": 2
                        }
                    }
                }
            },
            "occlusionTexture": {
                "index": 1,
                "texCoord": 1,
                "strength": 0.4,
                "extensions": {
                    "KHR_texture_transform": {
                        "scale": [2.0, 3.0]
                    }
                }
            },
            "extensions": {
                "KHR_materials_unlit": {}
            }
        }))
        .expect("the material must load");

        assert!(material.unlit());
        assert_eq!(material.shading_model(), MaterialShadingModel::Unlit);

        let metallic_roughness = material
            .metallic_roughness_texture()
            .expect("metallic-roughness texture must be retained");
        assert_eq!(metallic_roughness.texture_id().index(), 0);
        assert_eq!(metallic_roughness.tex_coord(), 2);
        assert_eq!(metallic_roughness.transform().offset, [0.25, 0.5]);

        let occlusion = material
            .occlusion_texture()
            .expect("occlusion texture must be retained");
        assert_eq!(occlusion.texture.texture_id().index(), 1);
        assert_eq!(occlusion.texture.tex_coord(), 1);
        assert_eq!(occlusion.texture.transform().scale, [2.0, 3.0]);
        assert_eq!(occlusion.strength, 0.4);
    }

    #[test]
    fn khr_emissive_strength_takes_precedence_over_the_archived_multiplier() {
        let material = load_test_material(serde_json::json!({
            "emissiveFactor": [0.25, 0.5, 1.0],
            "extensions": {
                "KHR_materials_emissive_strength": {
                    "emissiveStrength": 4.0
                },
                "VRMC_materials_hdr_emissiveMultiplier": {
                    "emissiveMultiplier": 10.0
                }
            }
        }))
        .expect("the material must load");

        assert_eq!(material.emissive_strength(), 4.0);
        assert_eq!(material.effective_emissive_factor(), [1.0, 2.0, 4.0]);
        assert_eq!(
            material.emissive_strength_source(),
            EmissiveStrengthSource::KhrMaterialsEmissiveStrength
        );
        assert_eq!(material.legacy_emissive_multiplier(), Some(10.0));
    }

    #[test]
    fn archived_emissive_multiplier_is_used_as_a_fallback() {
        let material = load_test_material(serde_json::json!({
            "emissiveFactor": [0.25, 0.5, 1.0],
            "extensions": {
                "VRMC_materials_hdr_emissiveMultiplier": {
                    "emissiveMultiplier": 2.0
                }
            }
        }))
        .expect("the archived material extension must load");

        assert_eq!(material.emissive_strength(), 2.0);
        assert_eq!(material.effective_emissive_factor(), [0.5, 1.0, 2.0]);
        assert_eq!(
            material.emissive_strength_source(),
            EmissiveStrengthSource::VrmcMaterialsHdrEmissiveMultiplier
        );
    }

    #[test]
    fn mtoon_takes_precedence_over_unlit_without_losing_the_unlit_flag() {
        let material = load_test_material(serde_json::json!({
            "extensions": {
                "KHR_materials_unlit": {},
                "VRMC_materials_mtoon": {
                    "specVersion": "1.0"
                }
            }
        }))
        .expect("the material must load");

        assert!(material.unlit());
        assert!(material.mtoon().is_some());
        assert_eq!(material.shading_model(), MaterialShadingModel::MToon);
    }

    #[test]
    fn rejects_negative_emissive_strength_values() {
        for extension in [
            serde_json::json!({
                "KHR_materials_emissive_strength": { "emissiveStrength": -1.0 }
            }),
            serde_json::json!({
                "VRMC_materials_hdr_emissiveMultiplier": { "emissiveMultiplier": -1.0 }
            }),
        ] {
            let result = load_test_material(serde_json::json!({ "extensions": extension }));
            assert!(
                result.is_err(),
                "negative emissive strength must be rejected"
            );
        }
    }
}