Skip to main content

concinnity_core/components/
material.rs

1// Surface-material schema.
2
3use crate::ecs::ShaderHandle;
4use crate::ecs::TextureHandle;
5use crate::ecs::asset_id::AssetId;
6use crate::ecs::de_opt_shader_handle;
7use crate::ecs::de_opt_texture_handle;
8
9/// A Material bundles the surface parameters that control how a [Prop](#prop) is
10/// lit and shaded.
11///
12/// Reference it from a [Prop](#prop)'s `material` field. The `material` field takes
13/// precedence over the older `texture` field.
14///
15/// ```rust
16/// # use concinnity_core::components::Material;
17/// Material {
18///     roughness: 0.85,
19///     metallic: 0.0,
20///     ..Default::default()
21/// };
22/// ```
23#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
24#[serde(default)]
25pub struct Material {
26    /// Asset identity; injected via `inject_name`. Not part of `args`.
27    #[serde(skip)]
28    pub asset_id: AssetId,
29    /// The [Texture](#texture) asset used as the base colour (albedo) map.
30    #[serde(deserialize_with = "de_opt_texture_handle")]
31    pub albedo: Option<TextureHandle>,
32    /// The [Texture](#texture) asset used as a tangent-space normal map.
33    #[serde(deserialize_with = "de_opt_texture_handle")]
34    pub normal_map: Option<TextureHandle>,
35    /// The [Texture](#texture) asset used as an emissive map. Multiplied by
36    /// `emissive_factor` to drive the glow; when omitted, only the scalar
37    /// `emissive_factor` is used. Pair a textured emissive with an
38    /// `emissive_factor` above 1 to make the bright parts bloom.
39    #[serde(deserialize_with = "de_opt_texture_handle")]
40    pub emissive_map: Option<TextureHandle>,
41    /// The [Texture](#texture) asset used as a packed surface map: green =
42    /// roughness, blue = metalness. When present it overrides the scalar
43    /// `roughness` and `metallic` per-texel; when omitted those scalars are
44    /// used. The red channel is reserved and not read as ambient occlusion:
45    /// packed maps in the wild (glTF metallic-roughness, FBX specular maps)
46    /// leave red empty, so treating it as occlusion would darken indirect
47    /// light to black. Ambient occlusion comes from the screen-space pass.
48    #[serde(deserialize_with = "de_opt_texture_handle")]
49    pub orm_map: Option<TextureHandle>,
50    /// Perceptual roughness in [0, 1]. 0 = mirror, 1 = fully diffuse.
51    /// Controls the width of the specular highlight.
52    pub roughness: f32,
53    /// Metallic factor in [0, 1]. 0 = dielectric (plastic/stone), 1 = metal.
54    /// Metallic surfaces tint their reflections with the albedo colour and show
55    /// almost no diffuse; dielectrics keep a neutral, dim reflection.
56    pub metallic: f32,
57    /// Linear-space RGB multiplier applied to the albedo sample. Useful for
58    /// tinting a shared texture without a separate asset (e.g. coloured brick).
59    pub tint: [f32; 3],
60    /// Additive emission colour in linear space. Non-zero values make the
61    /// surface appear to glow independently of the scene lighting.
62    pub emissive_factor: [f32; 3],
63    /// Alpha-cutout threshold in [0, 1]. When non-zero, a texel whose `albedo`
64    /// alpha falls below it is discarded outright, punching a hole in the
65    /// surface: this is how foliage, chain-link, and decal cards are drawn as
66    /// one opaque quad. 0 (the default) disables the test and keeps every texel.
67    /// Cutout is not glass: the surface still renders in the opaque pass, so
68    /// leave `transparent` and `see_through` off.
69    pub alpha_cutoff: f32,
70    /// Surface opacity in [0, 1]. 1 = fully opaque (the default). Only
71    /// meaningful when `transparent` is set: it drives how much of the scene
72    /// behind the surface shows through the glass.
73    pub opacity: f32,
74    /// When true, the surface is a translucent dielectric (glass): it renders
75    /// in the engine's transparent pass instead of the opaque pass, refracting
76    /// and reflecting the scene rather than writing solid colour + depth. The
77    /// importer sets this for materials it detects as glass; authored materials
78    /// can opt in directly. Defaults to false (opaque).
79    pub transparent: bool,
80    /// When true, the glass is rendered as genuinely see-through: the scene
81    /// behind it shows through with a sharp per-pixel reflection (requires a
82    /// ray-tracing-capable GPU). When false (the default), a `transparent`
83    /// surface still renders as low-roughness reflective glass that hides
84    /// whatever is behind it. See-through only looks right when the space behind
85    /// the glass is actually modelled, so it is opt-in per material. Setting it
86    /// implies `transparent`.
87    pub see_through: bool,
88    /// The [Shader](#shader) asset that shades surfaces using this material.
89    /// When omitted, the world's default shader is used. Referencing a shader
90    /// from a material ties that shader's lifetime to the material's: a shader
91    /// referenced only by scene-exclusive materials loads and unloads with the
92    /// scene.
93    #[serde(deserialize_with = "de_opt_shader_handle")]
94    pub shader: Option<ShaderHandle>,
95}
96
97impl Default for Material {
98    fn default() -> Self {
99        Self {
100            asset_id: AssetId::default(),
101            albedo: None,
102            normal_map: None,
103            emissive_map: None,
104            orm_map: None,
105            roughness: 0.8,
106            metallic: 0.0,
107            tint: [1.0, 1.0, 1.0],
108            emissive_factor: [0.0, 0.0, 0.0],
109            alpha_cutoff: 0.0,
110            opacity: 1.0,
111            transparent: false,
112            see_through: false,
113            shader: None,
114        }
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121
122    #[test]
123    fn a_blank_material_is_an_opaque_untextured_dielectric() {
124        let m = Material::default();
125        assert_eq!(m.roughness, 0.8);
126        assert_eq!(m.metallic, 0.0);
127        assert_eq!(m.tint, [1.0, 1.0, 1.0]);
128        assert_eq!(m.emissive_factor, [0.0, 0.0, 0.0]);
129        assert_eq!(m.opacity, 1.0);
130        assert!(!m.transparent);
131        assert!(!m.see_through);
132        // Zero alpha cutoff means "no cutout", not "discard everything".
133        assert_eq!(m.alpha_cutoff, 0.0);
134        for map in [&m.albedo, &m.normal_map, &m.emissive_map, &m.orm_map] {
135            assert!(map.is_none());
136        }
137        // No shader means the engine's own main-pass program draws it.
138        assert!(m.shader.is_none());
139    }
140
141    #[test]
142    fn every_texture_slot_resolves_through_its_own_reference() {
143        crate::test_support::install_resolvers();
144        let m: Material = serde_json::from_str(
145            r#"{"albedo":"tex_a","normal_map":"tex_nm","emissive_map":"tex_em",
146                "orm_map":"tex_orm","shader":"water_shader"}"#,
147        )
148        .unwrap();
149        assert_eq!(m.albedo, Some(TextureHandle(5)));
150        assert_eq!(m.normal_map, Some(TextureHandle(6)));
151        assert_eq!(m.emissive_map, Some(TextureHandle(6)));
152        assert_eq!(m.orm_map, Some(TextureHandle(7)));
153        assert_eq!(m.shader, Some(ShaderHandle(12)));
154    }
155
156    #[test]
157    fn a_glass_material_round_trips_through_postcard() {
158        let m: Material = serde_json::from_str(
159            r#"{"roughness":0.05,"metallic":1,"tint":[0.8,0.9,1],"emissive_factor":[2,2,2],
160                "alpha_cutoff":0.5,"opacity":0.3,"transparent":true,"see_through":true}"#,
161        )
162        .unwrap();
163        let bytes = postcard::to_allocvec(&m).unwrap();
164        let back: Material = postcard::from_bytes(&bytes).unwrap();
165        assert_eq!(back.roughness, 0.05);
166        assert_eq!(back.metallic, 1.0);
167        assert_eq!(back.tint, [0.8, 0.9, 1.0]);
168        assert_eq!(back.emissive_factor, [2.0, 2.0, 2.0]);
169        assert_eq!(back.alpha_cutoff, 0.5);
170        assert_eq!(back.opacity, 0.3);
171        assert!(back.transparent);
172        assert!(back.see_through);
173        assert_eq!(back.asset_id, AssetId::default());
174    }
175}