Skip to main content

vrm_runtime/
material.rs

1use glam::Vec3;
2use serde::Deserialize;
3use vrm_spec::vrmc_materials_mtoon_1_0 as mtoon_spec;
4
5use crate::{ImageId, TextureId};
6
7/// glTF alpha composition mode.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
9pub enum AlphaMode {
10    /// Draws fully opaque without alpha testing or blending.
11    #[default]
12    Opaque,
13    /// Discards fragments below [`Material::alpha_cutoff`].
14    Mask,
15    /// Uses alpha blending for translucent fragments.
16    Blend,
17}
18
19/// How MToon outline width is interpreted.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
21pub enum OutlineWidthMode {
22    /// Disables the MToon outline.
23    #[default]
24    None,
25    /// Interprets outline width in world-space meters.
26    WorldCoordinates,
27    /// Interprets outline width as a ratio of the screen height.
28    ScreenCoordinates,
29}
30
31impl From<mtoon_spec::OutlineWidthMode> for OutlineWidthMode {
32    fn from(mode: mtoon_spec::OutlineWidthMode) -> Self {
33        match mode {
34            mtoon_spec::OutlineWidthMode::None => Self::None,
35            mtoon_spec::OutlineWidthMode::WorldCoordinates => Self::WorldCoordinates,
36            mtoon_spec::OutlineWidthMode::ScreenCoordinates => Self::ScreenCoordinates,
37        }
38    }
39}
40
41/// UV transform attached to an individual texture reference.
42#[derive(Debug, Clone, Copy, PartialEq)]
43pub struct TextureTransform {
44    /// UV translation applied after scale and rotation.
45    pub offset: [f32; 2],
46    /// Counter-clockwise rotation in radians.
47    pub rotation: f32,
48    /// Per-axis UV scale.
49    pub scale: [f32; 2],
50}
51
52impl Default for TextureTransform {
53    fn default() -> Self {
54        Self {
55            offset: [0.0, 0.0],
56            rotation: 0.0,
57            scale: [1.0, 1.0],
58        }
59    }
60}
61
62/// A texture reference with its UV set and local transform.
63#[derive(Debug, Clone, Copy, PartialEq)]
64pub struct TextureInfo {
65    texture_id: TextureId,
66    tex_coord: u32,
67    transform: TextureTransform,
68}
69
70impl TextureInfo {
71    /// Creates a reference to `texture_id` using UV set 0 and the identity transform.
72    pub const fn new(texture_id: TextureId) -> Self {
73        Self {
74            texture_id,
75            tex_coord: 0,
76            transform: TextureTransform {
77                offset: [0.0, 0.0],
78                rotation: 0.0,
79                scale: [1.0, 1.0],
80            },
81        }
82    }
83
84    /// Selects the UV set sampled by this texture reference.
85    pub const fn with_tex_coord(mut self, tex_coord: u32) -> Self {
86        self.tex_coord = tex_coord;
87        self
88    }
89
90    /// Sets the local UV transform applied before sampling.
91    pub const fn with_transform(mut self, transform: TextureTransform) -> Self {
92        self.transform = transform;
93        self
94    }
95
96    /// Returns the referenced texture identifier.
97    pub fn texture_id(&self) -> TextureId {
98        self.texture_id
99    }
100
101    /// Returns the selected UV set.
102    pub fn tex_coord(&self) -> u32 {
103        self.tex_coord
104    }
105
106    /// Returns the local UV transform.
107    pub fn transform(&self) -> TextureTransform {
108        self.transform
109    }
110
111    fn from_gltf(info: gltf::texture::Info<'_>) -> Self {
112        let transform = info
113            .texture_transform()
114            .map(|transform| TextureTransform {
115                offset: transform.offset(),
116                rotation: transform.rotation(),
117                scale: transform.scale(),
118            })
119            .unwrap_or_default();
120        let tex_coord = info
121            .texture_transform()
122            .and_then(|transform| transform.tex_coord())
123            .unwrap_or_else(|| info.tex_coord());
124        Self {
125            texture_id: TextureId::from_index(info.texture().index()),
126            tex_coord,
127            transform,
128        }
129    }
130
131    fn from_json(info: &gltf::json::texture::Info) -> Self {
132        let transform = info
133            .extensions
134            .as_ref()
135            .and_then(|extensions| extensions.texture_transform.as_ref());
136        Self {
137            texture_id: TextureId::from_index(info.index.value()),
138            tex_coord: transform
139                .and_then(|transform| transform.tex_coord)
140                .unwrap_or(info.tex_coord),
141            transform: transform
142                .map(|transform| TextureTransform {
143                    offset: transform.offset.0,
144                    rotation: transform.rotation.0,
145                    scale: transform.scale.0,
146                })
147                .unwrap_or_default(),
148        }
149    }
150}
151
152/// A normal map reference and its scale multiplier.
153#[derive(Debug, Clone, Copy, PartialEq)]
154pub struct NormalTextureInfo {
155    /// The referenced normal-map texture, UV set, and transform.
156    pub texture: TextureInfo,
157    /// Multiplier applied to the tangent-space X and Y components.
158    pub scale: f32,
159}
160
161impl NormalTextureInfo {
162    /// Creates a normal-map reference with the glTF default scale of one.
163    pub const fn new(texture: TextureInfo) -> Self {
164        Self {
165            texture,
166            scale: 1.0,
167        }
168    }
169
170    /// Sets the normal-map scale multiplier.
171    pub const fn with_scale(mut self, scale: f32) -> Self {
172        self.scale = scale;
173        self
174    }
175}
176
177/// An occlusion map reference and its strength multiplier.
178#[derive(Debug, Clone, Copy, PartialEq)]
179pub struct OcclusionTextureInfo {
180    /// The referenced occlusion texture, UV set, and transform.
181    pub texture: TextureInfo,
182    /// Occlusion influence in the inclusive range from zero to one.
183    pub strength: f32,
184}
185
186impl OcclusionTextureInfo {
187    /// Creates an occlusion-map reference with the glTF default strength of one.
188    pub const fn new(texture: TextureInfo) -> Self {
189        Self {
190            texture,
191            strength: 1.0,
192        }
193    }
194
195    /// Sets the occlusion strength multiplier.
196    pub const fn with_strength(mut self, strength: f32) -> Self {
197        self.strength = strength;
198        self
199    }
200}
201
202/// The material model that a renderer should evaluate.
203#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
204pub enum MaterialShadingModel {
205    /// The core glTF metallic-roughness model.
206    #[default]
207    PbrMetallicRoughness,
208    /// The `KHR_materials_unlit` model.
209    Unlit,
210    /// The `VRMC_materials_mtoon` model.
211    MToon,
212}
213
214/// The extension that supplied the effective emissive multiplier.
215#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
216pub enum EmissiveStrengthSource {
217    /// Neither emissive-strength extension was present, so the multiplier is one.
218    #[default]
219    Default,
220    /// `KHR_materials_emissive_strength` supplied the multiplier.
221    KhrMaterialsEmissiveStrength,
222    /// The archived `VRMC_materials_hdr_emissiveMultiplier` extension supplied it.
223    VrmcMaterialsHdrEmissiveMultiplier,
224}
225
226/// Magnification filter of a texture sampler.
227#[derive(Debug, Clone, Copy, PartialEq, Eq)]
228pub enum MagFilter {
229    /// Selects the nearest texel.
230    Nearest,
231    /// Linearly interpolates adjacent texels.
232    Linear,
233}
234
235/// Minification filter of a texture sampler.
236#[derive(Debug, Clone, Copy, PartialEq, Eq)]
237pub enum MinFilter {
238    /// Selects the nearest texel without mipmapping.
239    Nearest,
240    /// Linearly interpolates texels without mipmapping.
241    Linear,
242    /// Selects the nearest texel from the nearest mip level.
243    NearestMipmapNearest,
244    /// Linearly interpolates texels from the nearest mip level.
245    LinearMipmapNearest,
246    /// Selects nearest texels and blends between mip levels.
247    NearestMipmapLinear,
248    /// Linearly interpolates texels and blends between mip levels.
249    LinearMipmapLinear,
250}
251
252/// Texture coordinate wrapping behavior.
253#[derive(Debug, Clone, Copy, PartialEq, Eq)]
254pub enum WrapMode {
255    /// Clamps texture coordinates to edge texels.
256    ClampToEdge,
257    /// Repeats the texture while mirroring every other interval.
258    MirroredRepeat,
259    /// Repeats the texture at every integer boundary.
260    Repeat,
261}
262
263/// Renderer-independent texture sampler data.
264#[derive(Debug, Clone, Copy, PartialEq, Eq)]
265pub struct TextureSampler {
266    /// Optional magnification filter; `None` uses the glTF default.
267    pub mag_filter: Option<MagFilter>,
268    /// Optional minification filter; `None` uses the glTF default.
269    pub min_filter: Option<MinFilter>,
270    /// Horizontal texture-coordinate wrapping mode.
271    pub wrap_s: WrapMode,
272    /// Vertical texture-coordinate wrapping mode.
273    pub wrap_t: WrapMode,
274}
275
276impl Default for TextureSampler {
277    fn default() -> Self {
278        Self {
279            mag_filter: None,
280            min_filter: None,
281            wrap_s: WrapMode::Repeat,
282            wrap_t: WrapMode::Repeat,
283        }
284    }
285}
286
287/// A glTF texture resolving a sampler and image separately.
288#[derive(Debug, Clone)]
289pub struct AvatarTexture {
290    image_id: ImageId,
291    sampler: TextureSampler,
292}
293
294impl AvatarTexture {
295    /// Creates a texture that samples `image_id` with the glTF sampler defaults.
296    pub fn new(image_id: ImageId) -> Self {
297        Self {
298            image_id,
299            sampler: TextureSampler::default(),
300        }
301    }
302
303    /// Replaces the texture sampler.
304    pub const fn with_sampler(mut self, sampler: TextureSampler) -> Self {
305        self.sampler = sampler;
306        self
307    }
308
309    /// Returns the image sampled by this texture.
310    pub fn image_id(&self) -> ImageId {
311        self.image_id
312    }
313
314    /// Returns the renderer-independent sampler state.
315    pub fn sampler(&self) -> TextureSampler {
316        self.sampler
317    }
318}
319
320/// Common glTF material data with an optional MToon extension.
321#[derive(Debug, Clone)]
322pub struct Material {
323    /// Linear RGBA multiplier for the base color.
324    pub base_color_factor: [f32; 4],
325    /// Metallic multiplier used by the glTF PBR model.
326    pub metallic_factor: f32,
327    /// Roughness multiplier used by the glTF PBR model.
328    pub roughness_factor: f32,
329    /// Linear RGB emissive color before the HDR strength multiplier.
330    pub emissive_factor: [f32; 3],
331    base_color_texture: Option<TextureInfo>,
332    metallic_roughness_texture: Option<TextureInfo>,
333    normal_texture: Option<NormalTextureInfo>,
334    occlusion_texture: Option<OcclusionTextureInfo>,
335    emissive_texture: Option<TextureInfo>,
336    unlit: bool,
337    emissive_strength: f32,
338    emissive_strength_source: EmissiveStrengthSource,
339    legacy_emissive_multiplier: Option<f32>,
340    /// Alpha composition mode used by the material.
341    pub alpha_mode: AlphaMode,
342    /// Alpha-test threshold used when [`Self::alpha_mode`] is [`AlphaMode::Mask`].
343    pub alpha_cutoff: f32,
344    double_sided: bool,
345    mtoon: Option<MToonMaterial>,
346}
347
348impl Default for Material {
349    fn default() -> Self {
350        Self {
351            base_color_factor: [1.0; 4],
352            metallic_factor: 1.0,
353            roughness_factor: 1.0,
354            emissive_factor: [0.0; 3],
355            base_color_texture: None,
356            metallic_roughness_texture: None,
357            normal_texture: None,
358            occlusion_texture: None,
359            emissive_texture: None,
360            unlit: false,
361            emissive_strength: 1.0,
362            emissive_strength_source: EmissiveStrengthSource::Default,
363            legacy_emissive_multiplier: None,
364            alpha_mode: AlphaMode::Opaque,
365            alpha_cutoff: 0.5,
366            double_sided: false,
367            mtoon: None,
368        }
369    }
370}
371
372impl Material {
373    /// Creates a glTF metallic-roughness material with specification defaults.
374    pub fn new() -> Self {
375        Self::default()
376    }
377
378    /// Sets the base-color factor shared by the supported shading models.
379    pub const fn with_base_color_factor(mut self, factor: [f32; 4]) -> Self {
380        self.base_color_factor = factor;
381        self
382    }
383
384    /// Sets the metallic factor of the core glTF material model.
385    pub const fn with_metallic_factor(mut self, factor: f32) -> Self {
386        self.metallic_factor = factor;
387        self
388    }
389
390    /// Sets the roughness factor of the core glTF material model.
391    pub const fn with_roughness_factor(mut self, factor: f32) -> Self {
392        self.roughness_factor = factor;
393        self
394    }
395
396    /// Sets the emissive color before applying [`Self::emissive_strength`].
397    pub const fn with_emissive_factor(mut self, factor: [f32; 3]) -> Self {
398        self.emissive_factor = factor;
399        self
400    }
401
402    /// Sets the base-color texture.
403    pub const fn with_base_color_texture(mut self, texture: TextureInfo) -> Self {
404        self.base_color_texture = Some(texture);
405        self
406    }
407
408    /// Sets the texture whose green and blue channels provide roughness and metalness.
409    pub const fn with_metallic_roughness_texture(mut self, texture: TextureInfo) -> Self {
410        self.metallic_roughness_texture = Some(texture);
411        self
412    }
413
414    /// Sets the tangent-space normal map.
415    pub const fn with_normal_texture(mut self, texture: NormalTextureInfo) -> Self {
416        self.normal_texture = Some(texture);
417        self
418    }
419
420    /// Sets the red-channel occlusion map.
421    pub const fn with_occlusion_texture(mut self, texture: OcclusionTextureInfo) -> Self {
422        self.occlusion_texture = Some(texture);
423        self
424    }
425
426    /// Sets the emissive texture.
427    pub const fn with_emissive_texture(mut self, texture: TextureInfo) -> Self {
428        self.emissive_texture = Some(texture);
429        self
430    }
431
432    /// Enables or disables the `KHR_materials_unlit` shading model.
433    pub const fn with_unlit(mut self, unlit: bool) -> Self {
434        self.unlit = unlit;
435        self
436    }
437
438    /// Sets the `KHR_materials_emissive_strength` multiplier.
439    pub const fn with_emissive_strength(mut self, strength: f32) -> Self {
440        self.emissive_strength = strength;
441        self.emissive_strength_source = EmissiveStrengthSource::KhrMaterialsEmissiveStrength;
442        self.legacy_emissive_multiplier = None;
443        self
444    }
445
446    /// Sets the alpha composition mode.
447    pub const fn with_alpha_mode(mut self, alpha_mode: AlphaMode) -> Self {
448        self.alpha_mode = alpha_mode;
449        self
450    }
451
452    /// Sets the cutoff used by [`AlphaMode::Mask`].
453    pub const fn with_alpha_cutoff(mut self, alpha_cutoff: f32) -> Self {
454        self.alpha_cutoff = alpha_cutoff;
455        self
456    }
457
458    /// Enables or disables rendering both sides of each triangle.
459    pub const fn with_double_sided(mut self, double_sided: bool) -> Self {
460        self.double_sided = double_sided;
461        self
462    }
463
464    /// Adds an MToon model, which takes precedence over Unlit and PBR rendering.
465    pub fn with_mtoon(mut self, mtoon: MToonMaterial) -> Self {
466        self.mtoon = Some(mtoon);
467        self
468    }
469
470    /// Returns the base-color texture used by every supported material model.
471    pub fn base_color_texture(&self) -> Option<&TextureInfo> {
472        self.base_color_texture.as_ref()
473    }
474
475    /// Returns the texture whose green and blue channels contain roughness and metalness.
476    pub fn metallic_roughness_texture(&self) -> Option<&TextureInfo> {
477        self.metallic_roughness_texture.as_ref()
478    }
479
480    /// Returns the tangent-space normal map and its scale.
481    pub fn normal_texture(&self) -> Option<&NormalTextureInfo> {
482        self.normal_texture.as_ref()
483    }
484
485    /// Returns the red-channel occlusion map and its strength.
486    pub fn occlusion_texture(&self) -> Option<&OcclusionTextureInfo> {
487        self.occlusion_texture.as_ref()
488    }
489
490    /// Returns the emissive texture.
491    pub fn emissive_texture(&self) -> Option<&TextureInfo> {
492        self.emissive_texture.as_ref()
493    }
494
495    /// Returns whether `KHR_materials_unlit` was declared.
496    ///
497    /// This remains `true` when MToon is also present. Use [`Self::shading_model`]
498    /// when selecting a renderer because MToon takes precedence over Unlit.
499    pub fn unlit(&self) -> bool {
500        self.unlit
501    }
502
503    /// Returns the selected emissive multiplier, defaulting to one.
504    ///
505    /// `KHR_materials_emissive_strength` takes precedence over the archived VRM
506    /// multiplier when both extensions are present.
507    pub fn emissive_strength(&self) -> f32 {
508        self.emissive_strength
509    }
510
511    /// Returns the extension that supplied [`Self::emissive_strength`].
512    pub fn emissive_strength_source(&self) -> EmissiveStrengthSource {
513        self.emissive_strength_source
514    }
515
516    /// Returns the archived VRM emissive multiplier when it was declared.
517    ///
518    /// The value is retained even when the modern KHR extension overrides it so
519    /// callers can emit a deprecation or precedence diagnostic.
520    pub fn legacy_emissive_multiplier(&self) -> Option<f32> {
521        self.legacy_emissive_multiplier
522    }
523
524    /// Returns `emissive_factor` after applying the selected HDR multiplier.
525    pub fn effective_emissive_factor(&self) -> [f32; 3] {
526        self.emissive_factor
527            .map(|component| component * self.emissive_strength)
528    }
529
530    /// Returns the material model that takes precedence for rendering.
531    pub fn shading_model(&self) -> MaterialShadingModel {
532        if self.mtoon.is_some() {
533            MaterialShadingModel::MToon
534        } else if self.unlit {
535            MaterialShadingModel::Unlit
536        } else {
537            MaterialShadingModel::PbrMetallicRoughness
538        }
539    }
540
541    /// Reports whether back-face culling must be disabled.
542    pub fn double_sided(&self) -> bool {
543        self.double_sided
544    }
545
546    /// Returns the MToon extension parameters, if present.
547    pub fn mtoon(&self) -> Option<&MToonMaterial> {
548        self.mtoon.as_ref()
549    }
550
551    fn load(
552        material: &gltf::Material<'_>,
553        mtoon: Option<&mtoon_spec::VrmcMaterialsMtoonSchema>,
554        texture_count: usize,
555    ) -> Result<Self, crate::LoadError> {
556        let pbr = material.pbr_metallic_roughness();
557        let material_index = material.index().unwrap_or(0);
558        let legacy_emissive_multiplier = load_legacy_emissive_multiplier(material, material_index)?;
559        let khr_emissive_strength = material.emissive_strength();
560        if let Some(value) = khr_emissive_strength {
561            validate_emissive_strength(
562                value,
563                material_index,
564                "KHR_materials_emissive_strength",
565                "emissiveStrength",
566            )?;
567        }
568        let (emissive_strength, emissive_strength_source) =
569            if let Some(value) = khr_emissive_strength {
570                (value, EmissiveStrengthSource::KhrMaterialsEmissiveStrength)
571            } else if let Some(value) = legacy_emissive_multiplier {
572                (
573                    value,
574                    EmissiveStrengthSource::VrmcMaterialsHdrEmissiveMultiplier,
575                )
576            } else {
577                (1.0, EmissiveStrengthSource::Default)
578            };
579
580        let mtoon = mtoon
581            .map(MToonMaterial::load)
582            .transpose()
583            .map_err(crate::LoadError::InvalidVrm)?;
584        let loaded = Self {
585            base_color_factor: pbr.base_color_factor(),
586            metallic_factor: pbr.metallic_factor(),
587            roughness_factor: pbr.roughness_factor(),
588            emissive_factor: material.emissive_factor(),
589            base_color_texture: pbr.base_color_texture().map(TextureInfo::from_gltf),
590            metallic_roughness_texture: pbr
591                .metallic_roughness_texture()
592                .map(TextureInfo::from_gltf),
593            normal_texture: material.normal_texture().map(|info| {
594                let (transform, transformed_tex_coord) =
595                    extension_transform(info.extension_value("KHR_texture_transform"));
596                NormalTextureInfo {
597                    texture: TextureInfo {
598                        texture_id: TextureId::from_index(info.texture().index()),
599                        tex_coord: transformed_tex_coord.unwrap_or_else(|| info.tex_coord()),
600                        transform,
601                    },
602                    scale: info.scale(),
603                }
604            }),
605            occlusion_texture: material.occlusion_texture().map(|info| {
606                let (transform, transformed_tex_coord) =
607                    extension_transform(info.extension_value("KHR_texture_transform"));
608                OcclusionTextureInfo {
609                    texture: TextureInfo {
610                        texture_id: TextureId::from_index(info.texture().index()),
611                        tex_coord: transformed_tex_coord.unwrap_or_else(|| info.tex_coord()),
612                        transform,
613                    },
614                    strength: info.strength(),
615                }
616            }),
617            emissive_texture: material.emissive_texture().map(TextureInfo::from_gltf),
618            unlit: material.unlit(),
619            emissive_strength,
620            emissive_strength_source,
621            legacy_emissive_multiplier,
622            alpha_mode: match material.alpha_mode() {
623                gltf::material::AlphaMode::Opaque => AlphaMode::Opaque,
624                gltf::material::AlphaMode::Mask => AlphaMode::Mask,
625                gltf::material::AlphaMode::Blend => AlphaMode::Blend,
626            },
627            alpha_cutoff: material.alpha_cutoff().unwrap_or(0.5),
628            double_sided: material.double_sided(),
629            mtoon,
630        };
631        loaded
632            .validate_programmatic(material_index, texture_count)
633            .map_err(crate::LoadError::InvalidVrm)?;
634        Ok(loaded)
635    }
636
637    pub(crate) fn validate_programmatic(
638        &self,
639        material_index: usize,
640        texture_count: usize,
641    ) -> Result<(), String> {
642        let label = format!("material {material_index}");
643        if !unit_slice(&self.base_color_factor)
644            || !unit_value(self.metallic_factor)
645            || !unit_value(self.roughness_factor)
646            || !unit_slice(&self.emissive_factor)
647        {
648            return Err(format!(
649                "{label} color, metallic, roughness, and emissive factors must be finite and within 0..=1"
650            ));
651        }
652        if !self.emissive_strength.is_finite() || self.emissive_strength < 0.0 {
653            return Err(format!(
654                "{label} emissive strength must be finite and non-negative"
655            ));
656        }
657        if !self.alpha_cutoff.is_finite() || self.alpha_cutoff < 0.0 {
658            return Err(format!(
659                "{label} alpha cutoff must be finite and non-negative"
660            ));
661        }
662
663        for (name, texture) in [
664            ("base color", self.base_color_texture.as_ref()),
665            (
666                "metallic-roughness",
667                self.metallic_roughness_texture.as_ref(),
668            ),
669            (
670                "normal",
671                self.normal_texture.as_ref().map(|value| &value.texture),
672            ),
673            (
674                "occlusion",
675                self.occlusion_texture.as_ref().map(|value| &value.texture),
676            ),
677            ("emissive", self.emissive_texture.as_ref()),
678        ] {
679            validate_programmatic_texture(texture, texture_count, &label, name)?;
680        }
681        if self
682            .normal_texture
683            .as_ref()
684            .is_some_and(|texture| !texture.scale.is_finite())
685        {
686            return Err(format!("{label} normal texture scale must be finite"));
687        }
688        if self.occlusion_texture.as_ref().is_some_and(|texture| {
689            !texture.strength.is_finite() || !(0.0..=1.0).contains(&texture.strength)
690        }) {
691            return Err(format!(
692                "{label} occlusion texture strength must be finite and within 0..=1"
693            ));
694        }
695
696        if let Some(mtoon) = &self.mtoon {
697            mtoon.validate_programmatic(&label, texture_count)?;
698        }
699        Ok(())
700    }
701}
702
703fn validate_programmatic_texture(
704    texture: Option<&TextureInfo>,
705    texture_count: usize,
706    material_label: &str,
707    texture_name: &str,
708) -> Result<(), String> {
709    let Some(texture) = texture else {
710        return Ok(());
711    };
712    if texture.texture_id.index() >= texture_count {
713        return Err(format!(
714            "{material_label} {texture_name} texture references a missing texture"
715        ));
716    }
717    let transform = texture.transform;
718    if !transform.rotation.is_finite()
719        || transform.offset.iter().any(|value| !value.is_finite())
720        || transform.scale.iter().any(|value| !value.is_finite())
721    {
722        return Err(format!(
723            "{material_label} {texture_name} texture has a non-finite UV transform"
724        ));
725    }
726    Ok(())
727}
728
729fn unit_value(value: f32) -> bool {
730    value.is_finite() && (0.0..=1.0).contains(&value)
731}
732
733fn unit_slice(values: &[f32]) -> bool {
734    values.iter().copied().all(unit_value)
735}
736
737const VRMC_MATERIALS_HDR_EMISSIVE_MULTIPLIER: &str = "VRMC_materials_hdr_emissiveMultiplier";
738
739#[derive(Deserialize)]
740#[serde(rename_all = "camelCase")]
741struct LegacyHdrEmissiveMultiplier {
742    emissive_multiplier: f32,
743}
744
745fn load_legacy_emissive_multiplier(
746    material: &gltf::Material<'_>,
747    material_index: usize,
748) -> Result<Option<f32>, crate::LoadError> {
749    let Some(value) = material.extension_value(VRMC_MATERIALS_HDR_EMISSIVE_MULTIPLIER) else {
750        return Ok(None);
751    };
752    let extension = serde_json::from_value::<LegacyHdrEmissiveMultiplier>(value.to_owned())
753        .map_err(|source| crate::LoadError::InvalidExtension {
754            extension: VRMC_MATERIALS_HDR_EMISSIVE_MULTIPLIER,
755            location: format!(
756                "/materials/{material_index}/extensions/{VRMC_MATERIALS_HDR_EMISSIVE_MULTIPLIER}"
757            ),
758            source,
759        })?;
760    validate_emissive_strength(
761        extension.emissive_multiplier,
762        material_index,
763        VRMC_MATERIALS_HDR_EMISSIVE_MULTIPLIER,
764        "emissiveMultiplier",
765    )?;
766    Ok(Some(extension.emissive_multiplier))
767}
768
769fn validate_emissive_strength(
770    value: f32,
771    material_index: usize,
772    extension: &str,
773    property: &str,
774) -> Result<(), crate::LoadError> {
775    if value.is_finite() && value >= 0.0 {
776        return Ok(());
777    }
778    Err(crate::LoadError::InvalidVrm(format!(
779        "/materials/{material_index}/extensions/{extension}/{property} must be finite and non-negative"
780    )))
781}
782
783/// Parameters defined by `VRMC_materials_mtoon` only.
784#[derive(Debug, Clone)]
785pub struct MToonMaterial {
786    /// Enables depth writes for transparent materials.
787    pub transparent_with_z_write: bool,
788    /// Offset in the specification-defined MToon render queue range.
789    pub render_queue_offset_number: i32,
790    /// Linear RGB shadow-side color multiplier.
791    pub shade_color: Vec3,
792    /// Optional texture multiplied into [`Self::shade_color`].
793    pub shade_multiply_texture: Option<TextureInfo>,
794    /// Shifts the boundary between lit and shaded regions.
795    pub shading_shift_factor: f32,
796    /// Optional texture that varies the shading shift.
797    pub shading_shift_texture: Option<TextureInfo>,
798    /// Multiplier applied to the shading-shift texture value.
799    pub shading_shift_texture_scale: f32,
800    /// Controls the softness of the lit-to-shade transition.
801    pub shading_toony_factor: f32,
802    /// Controls how strongly global illumination affects shading.
803    pub gi_equalization_factor: f32,
804    /// Linear RGB multiplier for the matcap contribution.
805    pub matcap_factor: Vec3,
806    /// Optional sphere-mapped matcap texture.
807    pub matcap_texture: Option<TextureInfo>,
808    /// Linear RGB color of the procedural rim-light contribution.
809    pub parametric_rim_color_factor: Vec3,
810    /// Fresnel exponent of the procedural rim light.
811    pub parametric_rim_fresnel_power_factor: f32,
812    /// Additive lift applied before evaluating the rim-light Fresnel term.
813    pub parametric_rim_lift_factor: f32,
814    /// Optional texture multiplied into the rim-light contribution.
815    pub rim_multiply_texture: Option<TextureInfo>,
816    /// Mix factor between direct and indirect rim lighting.
817    pub rim_lighting_mix_factor: f32,
818    /// Coordinate system used to interpret outline width.
819    pub outline_width_mode: OutlineWidthMode,
820    /// Base outline width in the units selected by [`Self::outline_width_mode`].
821    pub outline_width_factor: f32,
822    /// Optional texture multiplied into the outline width.
823    pub outline_width_multiply_texture: Option<TextureInfo>,
824    /// Linear RGB outline color.
825    pub outline_color_factor: Vec3,
826    /// Mix factor between unlit and lit outline color.
827    pub outline_lighting_mix_factor: f32,
828    /// Optional mask controlling which pixels receive UV animation.
829    pub uv_animation_mask_texture: Option<TextureInfo>,
830    /// Horizontal UV scroll speed in UV units per second.
831    pub uv_animation_scroll_x_speed_factor: f32,
832    /// Vertical UV scroll speed in UV units per second.
833    pub uv_animation_scroll_y_speed_factor: f32,
834    /// Counter-clockwise UV rotation speed in radians per second.
835    pub uv_animation_rotation_speed_factor: f32,
836}
837
838impl Default for MToonMaterial {
839    fn default() -> Self {
840        Self {
841            transparent_with_z_write: false,
842            render_queue_offset_number: 0,
843            shade_color: Vec3::ONE,
844            shade_multiply_texture: None,
845            shading_shift_factor: 0.0,
846            shading_shift_texture: None,
847            shading_shift_texture_scale: 1.0,
848            shading_toony_factor: 0.9,
849            gi_equalization_factor: 0.9,
850            matcap_factor: Vec3::ONE,
851            matcap_texture: None,
852            parametric_rim_color_factor: Vec3::ZERO,
853            parametric_rim_fresnel_power_factor: 5.0,
854            parametric_rim_lift_factor: 0.0,
855            rim_multiply_texture: None,
856            rim_lighting_mix_factor: 1.0,
857            outline_width_mode: OutlineWidthMode::None,
858            outline_width_factor: 0.0,
859            outline_width_multiply_texture: None,
860            outline_color_factor: Vec3::ZERO,
861            outline_lighting_mix_factor: 1.0,
862            uv_animation_mask_texture: None,
863            uv_animation_scroll_x_speed_factor: 0.0,
864            uv_animation_scroll_y_speed_factor: 0.0,
865            uv_animation_rotation_speed_factor: 0.0,
866        }
867    }
868}
869
870impl MToonMaterial {
871    /// Creates an MToon configuration using the VRM 1.0 specification defaults.
872    pub fn new() -> Self {
873        Self::default()
874    }
875
876    fn load(schema: &mtoon_spec::VrmcMaterialsMtoonSchema) -> Result<Self, String> {
877        let render_queue_offset_number =
878            i32::try_from(schema.render_queue_offset_number.unwrap_or(0))
879                .map_err(|_| "MToon render queue offset is not representable as i32".to_string())?;
880        Ok(Self {
881            transparent_with_z_write: schema.transparent_with_z_write.unwrap_or(false),
882            render_queue_offset_number,
883            shade_color: color(schema.shade_color_factor, Vec3::ONE),
884            shade_multiply_texture: schema
885                .shade_multiply_texture
886                .as_ref()
887                .map(TextureInfo::from_json),
888            shading_shift_factor: schema.shading_shift_factor.unwrap_or(0.0) as f32,
889            shading_shift_texture: schema
890                .shading_shift_texture
891                .as_ref()
892                .map(shading_shift_texture)
893                .transpose()?,
894            shading_shift_texture_scale: schema
895                .shading_shift_texture
896                .as_ref()
897                .and_then(|texture| texture.scale)
898                .unwrap_or(1.0) as f32,
899            shading_toony_factor: schema.shading_toony_factor.unwrap_or(0.9) as f32,
900            gi_equalization_factor: schema.gi_equalization_factor.unwrap_or(0.9) as f32,
901            matcap_factor: color(schema.matcap_factor, Vec3::ONE),
902            matcap_texture: schema.matcap_texture.as_ref().map(TextureInfo::from_json),
903            parametric_rim_color_factor: color(schema.parametric_rim_color_factor, Vec3::ZERO),
904            parametric_rim_fresnel_power_factor: schema
905                .parametric_rim_fresnel_power_factor
906                .unwrap_or(5.0) as f32,
907            parametric_rim_lift_factor: schema.parametric_rim_lift_factor.unwrap_or(0.0) as f32,
908            rim_multiply_texture: schema
909                .rim_multiply_texture
910                .as_ref()
911                .map(TextureInfo::from_json),
912            rim_lighting_mix_factor: schema.rim_lighting_mix_factor.unwrap_or(1.0) as f32,
913            outline_width_mode: schema
914                .outline_width_mode
915                .map(Into::into)
916                .unwrap_or_default(),
917            outline_width_factor: schema.outline_width_factor.unwrap_or(0.0) as f32,
918            outline_width_multiply_texture: schema
919                .outline_width_multiply_texture
920                .as_ref()
921                .map(TextureInfo::from_json),
922            outline_color_factor: color(schema.outline_color_factor, Vec3::ZERO),
923            outline_lighting_mix_factor: schema.outline_lighting_mix_factor.unwrap_or(1.0) as f32,
924            uv_animation_mask_texture: schema
925                .uv_animation_mask_texture
926                .as_ref()
927                .map(TextureInfo::from_json),
928            uv_animation_scroll_x_speed_factor: schema
929                .uv_animation_scroll_x_speed_factor
930                .unwrap_or(0.0) as f32,
931            uv_animation_scroll_y_speed_factor: schema
932                .uv_animation_scroll_y_speed_factor
933                .unwrap_or(0.0) as f32,
934            uv_animation_rotation_speed_factor: schema
935                .uv_animation_rotation_speed_factor
936                .unwrap_or(0.0) as f32,
937        })
938    }
939
940    fn validate_programmatic(
941        &self,
942        material_label: &str,
943        texture_count: usize,
944    ) -> Result<(), String> {
945        if !(-9..=9).contains(&self.render_queue_offset_number) {
946            return Err(format!(
947                "{material_label} MToon render queue offset must be within -9..=9"
948            ));
949        }
950        if !unit_slice(&self.shade_color.to_array())
951            || !unit_slice(&self.matcap_factor.to_array())
952            || !unit_slice(&self.parametric_rim_color_factor.to_array())
953            || !unit_slice(&self.outline_color_factor.to_array())
954        {
955            return Err(format!(
956                "{material_label} MToon color factors must be finite and within 0..=1"
957            ));
958        }
959        if !unit_value(self.shading_toony_factor)
960            || !unit_value(self.gi_equalization_factor)
961            || !unit_value(self.rim_lighting_mix_factor)
962            || !unit_value(self.outline_lighting_mix_factor)
963        {
964            return Err(format!(
965                "{material_label} MToon mix factors must be finite and within 0..=1"
966            ));
967        }
968        if !self.parametric_rim_fresnel_power_factor.is_finite()
969            || self.parametric_rim_fresnel_power_factor < 0.0
970            || !self.outline_width_factor.is_finite()
971            || self.outline_width_factor < 0.0
972        {
973            return Err(format!(
974                "{material_label} MToon rim power and outline width must be finite and non-negative"
975            ));
976        }
977        if [
978            self.shading_shift_factor,
979            self.shading_shift_texture_scale,
980            self.parametric_rim_lift_factor,
981            self.uv_animation_scroll_x_speed_factor,
982            self.uv_animation_scroll_y_speed_factor,
983            self.uv_animation_rotation_speed_factor,
984        ]
985        .iter()
986        .any(|value| !value.is_finite())
987        {
988            return Err(format!(
989                "{material_label} MToon scalar parameters must be finite"
990            ));
991        }
992
993        for (name, texture) in [
994            ("shade multiply", self.shade_multiply_texture.as_ref()),
995            ("shading shift", self.shading_shift_texture.as_ref()),
996            ("matcap", self.matcap_texture.as_ref()),
997            ("rim multiply", self.rim_multiply_texture.as_ref()),
998            (
999                "outline width multiply",
1000                self.outline_width_multiply_texture.as_ref(),
1001            ),
1002            ("UV animation mask", self.uv_animation_mask_texture.as_ref()),
1003        ] {
1004            validate_programmatic_texture(texture, texture_count, material_label, name)?;
1005        }
1006        Ok(())
1007    }
1008}
1009
1010fn color(value: Option<[f64; 3]>, default: Vec3) -> Vec3 {
1011    value
1012        .map(|value| Vec3::new(value[0] as f32, value[1] as f32, value[2] as f32))
1013        .unwrap_or(default)
1014}
1015
1016#[derive(Deserialize)]
1017#[serde(rename_all = "camelCase")]
1018struct RawTextureTransform {
1019    #[serde(default)]
1020    offset: Option<[f32; 2]>,
1021    #[serde(default)]
1022    rotation: Option<f32>,
1023    #[serde(default)]
1024    scale: Option<[f32; 2]>,
1025    #[serde(default)]
1026    tex_coord: Option<u32>,
1027}
1028
1029pub(crate) fn extension_transform(
1030    value: Option<&serde_json::Value>,
1031) -> (TextureTransform, Option<u32>) {
1032    let Some(transform) =
1033        value.and_then(|value| serde_json::from_value::<RawTextureTransform>(value.clone()).ok())
1034    else {
1035        return (TextureTransform::default(), None);
1036    };
1037    (
1038        TextureTransform {
1039            offset: transform.offset.unwrap_or([0.0, 0.0]),
1040            rotation: transform.rotation.unwrap_or(0.0),
1041            scale: transform.scale.unwrap_or([1.0, 1.0]),
1042        },
1043        transform.tex_coord,
1044    )
1045}
1046
1047fn shading_shift_texture(
1048    info: &mtoon_spec::ShadingShiftTextureInfo,
1049) -> Result<TextureInfo, String> {
1050    let extension_value = info
1051        .extensions
1052        .as_ref()
1053        .and_then(|extensions| extensions.get("KHR_texture_transform"))
1054        .map(|extension| {
1055            serde_json::Value::Object(
1056                extension
1057                    .iter()
1058                    .filter_map(|(key, value)| value.clone().map(|value| (key.clone(), value)))
1059                    .collect(),
1060            )
1061        });
1062    let (transform, transformed_tex_coord) = match extension_value {
1063        Some(value) => {
1064            let transform = serde_json::from_value::<RawTextureTransform>(value)
1065                .map_err(|error| format!("invalid MToon shading-shift UV transform: {error}"))?;
1066            (
1067                TextureTransform {
1068                    offset: transform.offset.unwrap_or([0.0, 0.0]),
1069                    rotation: transform.rotation.unwrap_or(0.0),
1070                    scale: transform.scale.unwrap_or([1.0, 1.0]),
1071                },
1072                transform.tex_coord,
1073            )
1074        }
1075        None => (TextureTransform::default(), None),
1076    };
1077    Ok(TextureInfo {
1078        texture_id: TextureId::from_index(info.index.value()),
1079        tex_coord: transformed_tex_coord.unwrap_or_else(|| {
1080            info.tex_coord
1081                .map(|value| value.value() as u32)
1082                .unwrap_or(0)
1083        }),
1084        transform,
1085    })
1086}
1087
1088fn map_mag_filter(filter: gltf::texture::MagFilter) -> MagFilter {
1089    match filter {
1090        gltf::texture::MagFilter::Nearest => MagFilter::Nearest,
1091        gltf::texture::MagFilter::Linear => MagFilter::Linear,
1092    }
1093}
1094
1095fn map_min_filter(filter: gltf::texture::MinFilter) -> MinFilter {
1096    match filter {
1097        gltf::texture::MinFilter::Nearest => MinFilter::Nearest,
1098        gltf::texture::MinFilter::Linear => MinFilter::Linear,
1099        gltf::texture::MinFilter::NearestMipmapNearest => MinFilter::NearestMipmapNearest,
1100        gltf::texture::MinFilter::LinearMipmapNearest => MinFilter::LinearMipmapNearest,
1101        gltf::texture::MinFilter::NearestMipmapLinear => MinFilter::NearestMipmapLinear,
1102        gltf::texture::MinFilter::LinearMipmapLinear => MinFilter::LinearMipmapLinear,
1103    }
1104}
1105
1106fn map_wrap_mode(mode: gltf::texture::WrappingMode) -> WrapMode {
1107    match mode {
1108        gltf::texture::WrappingMode::ClampToEdge => WrapMode::ClampToEdge,
1109        gltf::texture::WrappingMode::MirroredRepeat => WrapMode::MirroredRepeat,
1110        gltf::texture::WrappingMode::Repeat => WrapMode::Repeat,
1111    }
1112}
1113
1114pub(crate) fn load_textures(doc: &gltf::Document) -> Vec<AvatarTexture> {
1115    doc.textures()
1116        .map(|texture| {
1117            let sampler = texture.sampler();
1118            AvatarTexture {
1119                image_id: ImageId::from_index(texture.source().index()),
1120                sampler: TextureSampler {
1121                    mag_filter: sampler.mag_filter().map(map_mag_filter),
1122                    min_filter: sampler.min_filter().map(map_min_filter),
1123                    wrap_s: map_wrap_mode(sampler.wrap_s()),
1124                    wrap_t: map_wrap_mode(sampler.wrap_t()),
1125                },
1126            }
1127        })
1128        .collect()
1129}
1130
1131pub(crate) fn load_materials(doc: &gltf::Document) -> Result<Vec<Material>, crate::LoadError> {
1132    use mtoon_spec::VRMC_MATERIALS_MTOON;
1133
1134    doc.materials()
1135        .map(|material| {
1136            let mtoon = match material.extension_value(VRMC_MATERIALS_MTOON) {
1137                Some(value) => {
1138                    let schema = serde_json::from_value::<mtoon_spec::VrmcMaterialsMtoonSchema>(
1139                        value.to_owned(),
1140                    )
1141                    .map_err(|source| crate::LoadError::InvalidExtension {
1142                        extension: VRMC_MATERIALS_MTOON,
1143                        location: format!("/materials/{}", material.index().unwrap_or(0)),
1144                        source,
1145                    })?;
1146                    if schema.spec_version != "1.0" {
1147                        return Err(crate::LoadError::InvalidVrm(format!(
1148                            "/materials/{}/extensions/{VRMC_MATERIALS_MTOON}/specVersion must be `1.0`",
1149                            material.index().unwrap_or(0)
1150                        )));
1151                    }
1152                    Some(schema)
1153                }
1154                None => None,
1155            };
1156            Material::load(&material, mtoon.as_ref(), doc.textures().count())
1157        })
1158        .collect()
1159}
1160
1161#[cfg(test)]
1162mod tests {
1163    use super::*;
1164
1165    fn load_test_material(material: serde_json::Value) -> Result<Material, crate::LoadError> {
1166        let document = serde_json::json!({
1167            "asset": { "version": "2.0" },
1168            "extensionsUsed": [
1169                "KHR_materials_unlit",
1170                "KHR_materials_emissive_strength",
1171                "KHR_texture_transform",
1172                "VRMC_materials_hdr_emissiveMultiplier",
1173                "VRMC_materials_mtoon"
1174            ],
1175            "images": [
1176                { "uri": "first.png" },
1177                { "uri": "second.png" }
1178            ],
1179            "textures": [
1180                { "source": 0 },
1181                { "source": 1 }
1182            ],
1183            "materials": [material]
1184        });
1185        let bytes = serde_json::to_vec(&document).expect("test glTF JSON must serialize");
1186        let gltf = gltf::Gltf::from_slice(&bytes).expect("test glTF JSON must parse");
1187        load_materials(&gltf.document).map(|mut materials| materials.remove(0))
1188    }
1189
1190    #[test]
1191    fn shading_shift_texture_preserves_khr_texture_transform() {
1192        let info: mtoon_spec::ShadingShiftTextureInfo = serde_json::from_value(serde_json::json!({
1193            "index": 0,
1194            "texCoord": 1,
1195            "extensions": {
1196                "KHR_texture_transform": {
1197                    "offset": [0.25, 0.5],
1198                    "rotation": 0.75,
1199                    "scale": [2.0, 3.0],
1200                    "texCoord": 2
1201                }
1202            }
1203        }))
1204        .expect("the texture fixture must deserialize");
1205
1206        let texture = shading_shift_texture(&info).expect("the UV transform must be valid");
1207
1208        assert_eq!(texture.tex_coord(), 2);
1209        assert_eq!(texture.transform().offset, [0.25, 0.5]);
1210        assert_eq!(texture.transform().rotation, 0.75);
1211        assert_eq!(texture.transform().scale, [2.0, 3.0]);
1212    }
1213
1214    #[test]
1215    fn loads_unlit_and_common_pbr_textures() {
1216        let material = load_test_material(serde_json::json!({
1217            "pbrMetallicRoughness": {
1218                "metallicRoughnessTexture": {
1219                    "index": 0,
1220                    "texCoord": 1,
1221                    "extensions": {
1222                        "KHR_texture_transform": {
1223                            "offset": [0.25, 0.5],
1224                            "texCoord": 2
1225                        }
1226                    }
1227                }
1228            },
1229            "occlusionTexture": {
1230                "index": 1,
1231                "texCoord": 1,
1232                "strength": 0.4,
1233                "extensions": {
1234                    "KHR_texture_transform": {
1235                        "scale": [2.0, 3.0]
1236                    }
1237                }
1238            },
1239            "extensions": {
1240                "KHR_materials_unlit": {}
1241            }
1242        }))
1243        .expect("the material must load");
1244
1245        assert!(material.unlit());
1246        assert_eq!(material.shading_model(), MaterialShadingModel::Unlit);
1247
1248        let metallic_roughness = material
1249            .metallic_roughness_texture()
1250            .expect("metallic-roughness texture must be retained");
1251        assert_eq!(metallic_roughness.texture_id().index(), 0);
1252        assert_eq!(metallic_roughness.tex_coord(), 2);
1253        assert_eq!(metallic_roughness.transform().offset, [0.25, 0.5]);
1254
1255        let occlusion = material
1256            .occlusion_texture()
1257            .expect("occlusion texture must be retained");
1258        assert_eq!(occlusion.texture.texture_id().index(), 1);
1259        assert_eq!(occlusion.texture.tex_coord(), 1);
1260        assert_eq!(occlusion.texture.transform().scale, [2.0, 3.0]);
1261        assert_eq!(occlusion.strength, 0.4);
1262    }
1263
1264    #[test]
1265    fn khr_emissive_strength_takes_precedence_over_the_archived_multiplier() {
1266        let material = load_test_material(serde_json::json!({
1267            "emissiveFactor": [0.25, 0.5, 1.0],
1268            "extensions": {
1269                "KHR_materials_emissive_strength": {
1270                    "emissiveStrength": 4.0
1271                },
1272                "VRMC_materials_hdr_emissiveMultiplier": {
1273                    "emissiveMultiplier": 10.0
1274                }
1275            }
1276        }))
1277        .expect("the material must load");
1278
1279        assert_eq!(material.emissive_strength(), 4.0);
1280        assert_eq!(material.effective_emissive_factor(), [1.0, 2.0, 4.0]);
1281        assert_eq!(
1282            material.emissive_strength_source(),
1283            EmissiveStrengthSource::KhrMaterialsEmissiveStrength
1284        );
1285        assert_eq!(material.legacy_emissive_multiplier(), Some(10.0));
1286    }
1287
1288    #[test]
1289    fn archived_emissive_multiplier_is_used_as_a_fallback() {
1290        let material = load_test_material(serde_json::json!({
1291            "emissiveFactor": [0.25, 0.5, 1.0],
1292            "extensions": {
1293                "VRMC_materials_hdr_emissiveMultiplier": {
1294                    "emissiveMultiplier": 2.0
1295                }
1296            }
1297        }))
1298        .expect("the archived material extension must load");
1299
1300        assert_eq!(material.emissive_strength(), 2.0);
1301        assert_eq!(material.effective_emissive_factor(), [0.5, 1.0, 2.0]);
1302        assert_eq!(
1303            material.emissive_strength_source(),
1304            EmissiveStrengthSource::VrmcMaterialsHdrEmissiveMultiplier
1305        );
1306    }
1307
1308    #[test]
1309    fn mtoon_takes_precedence_over_unlit_without_losing_the_unlit_flag() {
1310        let material = load_test_material(serde_json::json!({
1311            "extensions": {
1312                "KHR_materials_unlit": {},
1313                "VRMC_materials_mtoon": {
1314                    "specVersion": "1.0"
1315                }
1316            }
1317        }))
1318        .expect("the material must load");
1319
1320        assert!(material.unlit());
1321        assert!(material.mtoon().is_some());
1322        assert_eq!(material.shading_model(), MaterialShadingModel::MToon);
1323    }
1324
1325    #[test]
1326    fn rejects_negative_emissive_strength_values() {
1327        for extension in [
1328            serde_json::json!({
1329                "KHR_materials_emissive_strength": { "emissiveStrength": -1.0 }
1330            }),
1331            serde_json::json!({
1332                "VRMC_materials_hdr_emissiveMultiplier": { "emissiveMultiplier": -1.0 }
1333            }),
1334        ] {
1335            let result = load_test_material(serde_json::json!({ "extensions": extension }));
1336            assert!(
1337                result.is_err(),
1338                "negative emissive strength must be rejected"
1339            );
1340        }
1341    }
1342}