threers 0.0.2

Drop-in three.js replacement for Rust and WebAssembly (wgpu) — THREE.* API, scene graph, PBR, post-fx, mesh BVH, CSG, headless render, and native media codecs
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
//! Materials. Mirrors three.js's `Material` family, including
//! [`ShaderMaterial`] for custom WGSL fragments.

mod basic;
mod depth;
mod lambert;
mod line;
mod matcap;
mod normal_mat;
mod phong;
mod physical;
mod points_mat;
mod shader_material;
mod sprite_mat;
mod standard;
mod toon;

pub use basic::BasicMaterial;
pub use depth::DepthMaterial;
pub use lambert::LambertMaterial;
pub use line::LineBasicMaterial;
pub use matcap::MatcapMaterial;
pub use normal_mat::NormalMaterial;
pub use phong::PhongMaterial;
pub use physical::PhysicalMaterial;
pub use points_mat::PointsMaterial;
pub use shader_material::ShaderMaterial;
pub use sprite_mat::SpriteMaterial;
pub use standard::StandardMaterial;
pub use toon::ToonMaterial;

use crate::math::{Color, Vector2};
use crate::textures::Texture;
use std::sync::Arc;

/// How a transparent [`PhysicalMaterial`] is composited. Ordinary alpha blending
/// re-sorts overlapping layers per-object and shimmers on rotation for complex
/// surfaces; the other two modes fix that.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TransparencyMode {
    /// Back-to-front alpha blending (default; order-dependent).
    #[default]
    Blend,
    /// **Single-layer glass** via a depth prepass: only the nearest surface
    /// blends, so a bumpy translucent mesh is flicker-free
    /// while rotating. You see the front shell + whatever is behind it.
    Glass,
    /// **Weighted-blended order-independent transparency** (McGuire): all layers
    /// accumulate order-independently, so even the far wall shows through the
    /// near wall with no flicker.
    Oit,
    /// **Screen-space refraction glass** (Blender/EEVEE-style): the opaque scene
    /// is captured to a mipped color buffer + depth, then the glass surface
    /// refracts it via Snell's law (with dispersion, total internal reflection,
    /// roughness→mip blur) and reflects it via screen-space ray-marching with an
    /// environment-probe fallback. The most physically-convincing mode; requires
    /// an environment for the reflection/refraction fallback to read well.
    Refract,
}

#[derive(Debug, Clone)]
pub enum Material {
    Basic(BasicMaterial),
    Lambert(LambertMaterial),
    Phong(PhongMaterial),
    Standard(StandardMaterial),
    Physical(PhysicalMaterial),
    Normal(NormalMaterial),
    Depth(DepthMaterial),
    Toon(ToonMaterial),
    Matcap(MatcapMaterial),
    Line(LineBasicMaterial),
    Points(PointsMaterial),
    Sprite(SpriteMaterial),
    Distance(DistanceMaterial),
    Sky(SkyMaterial),
    Mirror(MirrorMaterial),
    /// User-defined custom-shader material (extensibility escape hatch).
    Shader(ShaderMaterial),
}

/// Mirror material — drives the Reflector / Refractor / Water shader path
/// which projectively samples a render-target texture using a per-frame
/// texture matrix supplied from JS. The texture matrix encodes
/// `scaleBias * virtualCamProj * virtualCamView` so that fragment-side
/// `texture_matrix * world_pos` lands in [0,1] UV space.
#[derive(Debug, Clone)]
pub struct MirrorMaterial {
    pub color: Color,
    pub map: Option<Arc<Texture>>,
    pub texture_matrix: [f32; 16],
    pub side: u32,
}
impl Default for MirrorMaterial {
    fn default() -> Self {
        Self {
            color: Color::WHITE,
            map: None,
            texture_matrix: [
                1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
            ],
            side: 0,
        }
    }
}

/// Sky shader material. Drives the Preetham atmospheric scattering shader.
/// Mirrors three.js's `Sky` from `examples/jsm/objects/Sky.js`.
#[derive(Debug, Clone, Copy)]
pub struct SkyMaterial {
    pub sun_position: crate::math::Vector3,
    pub turbidity: f32,
    pub rayleigh: f32,
    pub mie_coefficient: f32,
    pub mie_directional_g: f32,
}
impl Default for SkyMaterial {
    fn default() -> Self {
        Self {
            sun_position: crate::math::Vector3::new(0.0, 1.0, 0.0),
            turbidity: 10.0,
            rayleigh: 3.0,
            mie_coefficient: 0.005,
            mie_directional_g: 0.7,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum MaterialKind {
    Basic = 0,
    Lambert = 1,
    Phong = 2,
    Standard = 3,
    Physical = 4,
    Normal = 5,
    Depth = 6,
    Toon = 7,
    Matcap = 8,
    Line = 9,
    Points = 10,
    Sprite = 11,
    Distance = 12,
    Sky = 13,
    Mirror = 14,
    Shader = 15,
}

#[derive(Debug, Clone)]
pub struct DistanceMaterial {
    pub reference_position: crate::math::Vector3,
    pub near_distance: f32,
    pub far_distance: f32,
}
impl Default for DistanceMaterial {
    fn default() -> Self {
        Self {
            reference_position: crate::math::Vector3::ZERO,
            near_distance: 1.0,
            far_distance: 1000.0,
        }
    }
}
impl DistanceMaterial {
    pub fn new(reference_position: crate::math::Vector3, near: f32, far: f32) -> Self {
        Self {
            reference_position,
            near_distance: near.max(0.0),
            far_distance: far.max(near + 0.001),
        }
    }
}

#[derive(Default, Clone)]
pub struct MaterialTextureSlots {
    pub map: Option<Arc<Texture>>,
    pub normal_map: Option<Arc<Texture>>,
    pub roughness_map: Option<Arc<Texture>>,
    pub metalness_map: Option<Arc<Texture>>,
    pub ao_map: Option<Arc<Texture>>,
    pub emissive_map: Option<Arc<Texture>>,
    pub matcap_map: Option<Arc<Texture>>,
}

impl Material {
    pub fn color(&self) -> Color {
        match self {
            Material::Basic(m) => m.color,
            Material::Lambert(m) => m.color,
            Material::Phong(m) => m.color,
            Material::Standard(m) => m.color,
            Material::Physical(m) => m.color,
            Material::Normal(_) => Color::WHITE,
            Material::Depth(_) => Color::WHITE,
            Material::Toon(m) => m.color,
            Material::Matcap(m) => m.color,
            Material::Line(m) => m.color,
            Material::Points(m) => m.color,
            Material::Sprite(m) => m.color,
            Material::Distance(_) => Color::WHITE,
            Material::Sky(_) => Color::WHITE,
            Material::Mirror(m) => m.color,
            Material::Shader(_) => Color::WHITE,
        }
    }

    pub fn wireframe(&self) -> bool {
        match self {
            Material::Basic(m) => m.wireframe,
            Material::Lambert(m) => m.wireframe,
            Material::Phong(m) => m.wireframe,
            Material::Standard(m) => m.wireframe,
            Material::Physical(m) => m.wireframe,
            Material::Normal(m) => m.wireframe,
            Material::Depth(m) => m.wireframe,
            Material::Toon(m) => m.wireframe,
            Material::Matcap(m) => m.wireframe,
            _ => false,
        }
    }

    pub fn transparent(&self) -> bool {
        match self {
            Material::Basic(m) => m.transparent,
            // Transmissive glass needs the alpha pipeline even at opacity 1.0.
            Material::Physical(m) => m.opacity < 1.0 || m.transmission > 0.0,
            Material::Shader(m) => m.transparent || m.opacity < 1.0,
            // Other materials: treat opacity < 1 as transparent by default,
            // matching three.js's behavior when only opacity is set.
            _ => self.opacity() < 1.0,
        }
    }

    /// Which transparency technique a *transparent* material uses. Only
    /// `PhysicalMaterial` can opt out of plain alpha blending (into single-layer
    /// glass or order-independent transparency); everything else is `Blend`.
    pub fn transparency_mode(&self) -> TransparencyMode {
        match self {
            Material::Physical(m) => m.transparency,
            _ => TransparencyMode::Blend,
        }
    }

    pub fn opacity(&self) -> f32 {
        match self {
            Material::Basic(m) => m.opacity,
            Material::Lambert(m) => m.opacity,
            Material::Phong(m) => m.opacity,
            Material::Standard(m) => m.opacity,
            Material::Physical(m) => m.opacity,
            Material::Normal(m) => m.opacity,
            Material::Depth(m) => m.opacity,
            Material::Toon(m) => m.opacity,
            Material::Matcap(m) => m.opacity,
            Material::Line(m) => m.opacity,
            Material::Points(m) => m.opacity,
            Material::Sprite(m) => m.opacity,
            Material::Distance(_) => 1.0,
            Material::Sky(_) => 1.0,
            Material::Mirror(_) => 1.0,
            Material::Shader(m) => m.opacity,
        }
    }

    pub fn alpha_test(&self) -> f32 {
        match self {
            Material::Basic(m) => m.alpha_test,
            _ => 0.0,
        }
    }

    pub fn shadow_only(&self) -> bool {
        match self {
            Material::Basic(m) => m.shadow_only,
            _ => false,
        }
    }

    pub fn emissive(&self) -> Color {
        match self {
            Material::Lambert(m) => m.emissive,
            Material::Phong(m) => m.emissive,
            Material::Standard(m) => Color::new(
                m.emissive.r * m.emissive_intensity,
                m.emissive.g * m.emissive_intensity,
                m.emissive.b * m.emissive_intensity,
            ),
            Material::Physical(m) => Color::new(
                m.emissive.r * m.emissive_intensity,
                m.emissive.g * m.emissive_intensity,
                m.emissive.b * m.emissive_intensity,
            ),
            Material::Toon(m) => m.emissive,
            _ => Color::BLACK,
        }
    }

    pub fn specular(&self) -> Color {
        match self {
            Material::Phong(m) => m.specular,
            _ => Color::BLACK,
        }
    }

    /// Material's render side. `0` = FrontSide (default), `1` = BackSide,
    /// `2` = DoubleSide. Threaded from JS via `WebMaterial.setSide`.
    pub fn side(&self) -> u32 {
        match self {
            Material::Basic(m) => m.side,
            Material::Lambert(m) => m.side,
            Material::Phong(m) => m.side,
            Material::Standard(m) => m.side,
            Material::Physical(m) => m.side,
            Material::Toon(m) => m.side,
            Material::Matcap(_) => 0,
            Material::Normal(_) => 0,
            Material::Depth(_) => 0,
            Material::Distance(_) => 0,
            Material::Line(_) => 0,
            Material::Points(_) => 0,
            Material::Sprite(_) => 0,
            Material::Sky(_) => 1, // Sky uses BackSide → no-cull pipeline.
            Material::Mirror(m) => m.side,
            Material::Shader(m) => m.side,
        }
    }

    pub fn shininess(&self) -> f32 {
        match self {
            Material::Phong(m) => m.shininess,
            _ => 0.0,
        }
    }

    pub fn roughness(&self) -> f32 {
        match self {
            Material::Standard(m) => m.roughness,
            Material::Physical(m) => m.roughness,
            _ => 1.0,
        }
    }

    pub fn metalness(&self) -> f32 {
        match self {
            Material::Standard(m) => m.metalness,
            Material::Physical(m) => m.metalness,
            _ => 0.0,
        }
    }

    pub fn ao_intensity(&self) -> f32 {
        match self {
            Material::Standard(m) => m.ao_intensity,
            Material::Physical(m) => m.ao_intensity,
            _ => 1.0,
        }
    }

    pub fn normal_scale(&self) -> Vector2 {
        match self {
            Material::Standard(m) => m.normal_scale,
            Material::Physical(m) => m.normal_scale,
            _ => Vector2::ONE,
        }
    }

    pub fn depth_range(&self) -> (f32, f32) {
        match self {
            Material::Depth(m) => (m.near, m.far),
            _ => (0.0, 0.0),
        }
    }

    pub fn toon_steps(&self) -> u32 {
        match self {
            Material::Toon(m) => m.steps,
            _ => 0,
        }
    }

    pub fn point_size(&self) -> f32 {
        match self {
            Material::Points(m) => m.size,
            _ => 1.0,
        }
    }

    pub fn point_size_attenuation(&self) -> bool {
        match self {
            Material::Points(m) => m.size_attenuation,
            _ => false,
        }
    }

    pub fn kind(&self) -> MaterialKind {
        match self {
            Material::Basic(_) => MaterialKind::Basic,
            Material::Lambert(_) => MaterialKind::Lambert,
            Material::Phong(_) => MaterialKind::Phong,
            Material::Standard(_) => MaterialKind::Standard,
            Material::Physical(_) => MaterialKind::Physical,
            Material::Normal(_) => MaterialKind::Normal,
            Material::Depth(_) => MaterialKind::Depth,
            Material::Toon(_) => MaterialKind::Toon,
            Material::Matcap(_) => MaterialKind::Matcap,
            Material::Line(_) => MaterialKind::Line,
            Material::Points(_) => MaterialKind::Points,
            Material::Sprite(_) => MaterialKind::Sprite,
            Material::Distance(_) => MaterialKind::Distance,
            Material::Sky(_) => MaterialKind::Sky,
            Material::Mirror(_) => MaterialKind::Mirror,
            Material::Shader(_) => MaterialKind::Shader,
        }
    }

    pub fn texture_slots(&self) -> MaterialTextureSlots {
        match self {
            Material::Standard(m) => MaterialTextureSlots {
                map: m.map.clone(),
                normal_map: m.normal_map.clone(),
                roughness_map: m.roughness_map.clone(),
                metalness_map: m.metalness_map.clone(),
                ao_map: m.ao_map.clone(),
                emissive_map: m.emissive_map.clone(),
                matcap_map: None,
            },
            Material::Physical(m) => MaterialTextureSlots {
                map: m.map.clone(),
                normal_map: m.normal_map.clone(),
                roughness_map: m.roughness_map.clone(),
                metalness_map: m.metalness_map.clone(),
                ao_map: m.ao_map.clone(),
                emissive_map: m.emissive_map.clone(),
                matcap_map: None,
            },
            Material::Matcap(m) => MaterialTextureSlots {
                matcap_map: m.matcap.clone(),
                ..Default::default()
            },
            Material::Sprite(m) => MaterialTextureSlots {
                map: m.map.clone(),
                ..Default::default()
            },
            Material::Basic(m) => MaterialTextureSlots {
                map: m.map.clone(),
                ..Default::default()
            },
            Material::Mirror(m) => MaterialTextureSlots {
                map: m.map.clone(),
                ..Default::default()
            },
            _ => MaterialTextureSlots::default(),
        }
    }
}

impl From<BasicMaterial> for Material {
    fn from(m: BasicMaterial) -> Self {
        Material::Basic(m)
    }
}
impl From<LambertMaterial> for Material {
    fn from(m: LambertMaterial) -> Self {
        Material::Lambert(m)
    }
}
impl From<PhongMaterial> for Material {
    fn from(m: PhongMaterial) -> Self {
        Material::Phong(m)
    }
}
impl From<StandardMaterial> for Material {
    fn from(m: StandardMaterial) -> Self {
        Material::Standard(m)
    }
}
impl From<PhysicalMaterial> for Material {
    fn from(m: PhysicalMaterial) -> Self {
        Material::Physical(m)
    }
}
impl From<NormalMaterial> for Material {
    fn from(m: NormalMaterial) -> Self {
        Material::Normal(m)
    }
}
impl From<DepthMaterial> for Material {
    fn from(m: DepthMaterial) -> Self {
        Material::Depth(m)
    }
}
impl From<ToonMaterial> for Material {
    fn from(m: ToonMaterial) -> Self {
        Material::Toon(m)
    }
}
impl From<MatcapMaterial> for Material {
    fn from(m: MatcapMaterial) -> Self {
        Material::Matcap(m)
    }
}
impl From<LineBasicMaterial> for Material {
    fn from(m: LineBasicMaterial) -> Self {
        Material::Line(m)
    }
}
impl From<PointsMaterial> for Material {
    fn from(m: PointsMaterial) -> Self {
        Material::Points(m)
    }
}
impl From<SpriteMaterial> for Material {
    fn from(m: SpriteMaterial) -> Self {
        Material::Sprite(m)
    }
}
impl From<DistanceMaterial> for Material {
    fn from(m: DistanceMaterial) -> Self {
        Material::Distance(m)
    }
}
impl From<SkyMaterial> for Material {
    fn from(m: SkyMaterial) -> Self {
        Material::Sky(m)
    }
}
impl From<MirrorMaterial> for Material {
    fn from(m: MirrorMaterial) -> Self {
        Material::Mirror(m)
    }
}
impl From<ShaderMaterial> for Material {
    fn from(m: ShaderMaterial) -> Self {
        Material::Shader(m)
    }
}