oxihuman-viewer 0.2.1

wgpu/WebGPU rendering adapter for OxiHuman
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
// Copyright (C) 2026 COOLJAPAN OU (Team KitaSan)
// SPDX-License-Identifier: Apache-2.0

//! Background / environment rendering: gradient, solid colour, checkerboard, and procedural sky cubemap.

// ── Enums / Structs ──────────────────────────────────────────────────────────

/// Supported background rendering modes.
#[allow(dead_code)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BackgroundType {
    /// Flat single colour.
    SolidColor,
    /// Top-to-bottom gradient.
    VerticalGradient,
    /// Left-to-right gradient.
    HorizontalGradient,
    /// Checkerboard pattern (useful for transparency preview).
    Checkerboard,
    /// Procedural sky cubemap environment.
    Cubemap,
}

/// Configuration for background rendering.
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct BackgroundConfig {
    /// Which background mode is active.
    pub bg_type: BackgroundType,
    /// Primary / top / fill colour (linear RGBA).
    pub top_color: [f32; 4],
    /// Secondary / bottom colour (linear RGBA).
    pub bottom_color: [f32; 4],
    /// Size of each checker square in pixels.
    pub checker_size: u32,
}

/// A sampled background colour at a UV coordinate.
#[allow(dead_code)]
#[derive(Debug, Clone, PartialEq)]
pub struct BackgroundSample {
    /// Sampled RGBA colour (linear, [0, 1]).
    pub color: [f32; 4],
    /// U coordinate that was sampled.
    pub u: f32,
    /// V coordinate that was sampled.
    pub v: f32,
}

// ── Constructors ─────────────────────────────────────────────────────────────

/// Create a default background config (dark grey solid colour).
#[allow(dead_code)]
pub fn default_background_config() -> BackgroundConfig {
    BackgroundConfig {
        bg_type: BackgroundType::SolidColor,
        top_color: [0.15, 0.15, 0.18, 1.0],
        bottom_color: [0.05, 0.05, 0.07, 1.0],
        checker_size: 16,
    }
}

/// Create a new background config with the given type.
#[allow(dead_code)]
pub fn new_background_config(bg_type: BackgroundType) -> BackgroundConfig {
    BackgroundConfig {
        bg_type,
        ..default_background_config()
    }
}

// ── Sampling ─────────────────────────────────────────────────────────────────

/// Sample the background colour at normalised UV coordinates `(u, v)` in [0, 1].
///
/// * `u` = horizontal (0 = left, 1 = right)
/// * `v` = vertical   (0 = top,  1 = bottom)
#[allow(dead_code)]
pub fn sample_background(config: &BackgroundConfig, u: f32, v: f32) -> BackgroundSample {
    let color = match config.bg_type {
        BackgroundType::SolidColor => config.top_color,
        BackgroundType::VerticalGradient => {
            gradient_color(&config.top_color, &config.bottom_color, v)
        }
        BackgroundType::HorizontalGradient => {
            gradient_color(&config.top_color, &config.bottom_color, u)
        }
        BackgroundType::Checkerboard => checkerboard_color(config, u, v),
        BackgroundType::Cubemap => sample_cubemap(config, u, v),
    };
    BackgroundSample { color, u, v }
}

/// Linearly interpolate between two RGBA colours by `t` in [0, 1].
#[allow(dead_code)]
pub fn gradient_color(a: &[f32; 4], b: &[f32; 4], t: f32) -> [f32; 4] {
    let t = t.clamp(0.0, 1.0);
    [
        a[0] + (b[0] - a[0]) * t,
        a[1] + (b[1] - a[1]) * t,
        a[2] + (b[2] - a[2]) * t,
        a[3] + (b[3] - a[3]) * t,
    ]
}

/// Compute a checkerboard colour at `(u, v)` using the config's checker size
/// and top/bottom colours.
#[allow(dead_code)]
pub fn checkerboard_color(config: &BackgroundConfig, u: f32, v: f32) -> [f32; 4] {
    let size = config.checker_size.max(1) as f32;
    // Scale UV into pixel-grid space (assume a virtual 1024-pixel canvas)
    let px = (u * 1024.0) / size;
    let py = (v * 1024.0) / size;
    let checker = ((px as i32) + (py as i32)) % 2 == 0;
    if checker {
        config.top_color
    } else {
        config.bottom_color
    }
}

/// Convert equirectangular UV (u: longitude 0..1, v: latitude 0=top..1=bottom)
/// into a unit direction vector (y-up).
fn uv_to_direction(u: f32, v: f32) -> [f32; 3] {
    let az = u * std::f32::consts::TAU;
    let el = (0.5 - v) * std::f32::consts::PI; // v=0 -> +pi/2 (up); v=1 -> -pi/2 (down)
    let ce = el.cos();
    [ce * az.sin(), el.sin(), ce * az.cos()]
}

/// Standard OpenGL cube-face selection. Returns (face 0..5, s, t) with s,t in [0,1].
/// Faces: 0:+X 1:-X 2:+Y 3:-Y 4:+Z 5:-Z
#[allow(dead_code)]
fn direction_to_face_uv(d: [f32; 3]) -> (usize, f32, f32) {
    let ax = d[0].abs();
    let ay = d[1].abs();
    let az = d[2].abs();
    let (face, sc, tc, ma) = if ax >= ay && ax >= az {
        if d[0] > 0.0 {
            (0usize, -d[2], -d[1], ax)
        } else {
            (1, d[2], -d[1], ax)
        }
    } else if ay >= az {
        if d[1] > 0.0 {
            (2, d[0], d[2], ay)
        } else {
            (3, d[0], -d[2], ay)
        }
    } else if d[2] > 0.0 {
        (4, d[0], -d[1], az)
    } else {
        (5, -d[0], -d[1], az)
    };
    let inv = if ma.abs() < 1e-12 { 0.0 } else { 1.0 / ma };
    let s = 0.5 * (sc * inv + 1.0);
    let t = 0.5 * (tc * inv + 1.0);
    (face, s.clamp(0.0, 1.0), t.clamp(0.0, 1.0))
}

/// Sample a procedural sky cubemap environment along the direction for UV (u, v).
/// Combines an elevation gradient (nadir=bottom_color -> zenith=top_color with a
/// smoothstep horizon), a horizon haze band, and a directional sun highlight.
/// This is a genuine direction-dependent environment lookup (not a flat colour).
#[allow(dead_code)]
pub fn sample_cubemap(config: &BackgroundConfig, u: f32, v: f32) -> [f32; 4] {
    let d = uv_to_direction(u, v);
    let elev = d[1].clamp(-1.0, 1.0);

    // Smoothstep elevation blend: bottom_color (nadir) -> top_color (zenith).
    let mut tt = 0.5 * (elev + 1.0);
    tt = tt * tt * (3.0 - 2.0 * tt);
    let mut col = gradient_color(&config.bottom_color, &config.top_color, tt);

    // Horizon haze: brighten a band around elev = 0.
    let haze = (1.0 - (elev.abs() * 3.0).min(1.0)) * 0.12;
    for c in col.iter_mut().take(3) {
        *c = (*c + haze).clamp(0.0, 1.0);
    }

    // Directional sun highlight.
    let sun_dir = {
        let s = [0.3f32, 0.6, 0.2];
        let l = (s[0] * s[0] + s[1] * s[1] + s[2] * s[2]).sqrt();
        [s[0] / l, s[1] / l, s[2] / l]
    };
    let ndl = (d[0] * sun_dir[0] + d[1] * sun_dir[1] + d[2] * sun_dir[2]).max(0.0);
    let sun = ndl.powf(64.0) * 0.8;
    for c in col.iter_mut().take(3) {
        *c = (*c + sun).clamp(0.0, 1.0);
    }

    col[3] = config.top_color[3];
    col
}

// ── Setters ──────────────────────────────────────────────────────────────────

/// Set the background type.
#[allow(dead_code)]
pub fn set_background_type(config: &mut BackgroundConfig, bg_type: BackgroundType) {
    config.bg_type = bg_type;
}

/// Set the top / primary colour.
#[allow(dead_code)]
pub fn set_top_color(config: &mut BackgroundConfig, color: [f32; 4]) {
    config.top_color = color;
}

/// Set the bottom / secondary colour.
#[allow(dead_code)]
pub fn set_bottom_color(config: &mut BackgroundConfig, color: [f32; 4]) {
    config.bottom_color = color;
}

/// Set the checkerboard square size (in pixels).
#[allow(dead_code)]
pub fn set_checker_size(config: &mut BackgroundConfig, size: u32) {
    config.checker_size = size.max(1);
}

// ── Query / utility ──────────────────────────────────────────────────────────

/// Return a human-readable name for the background type.
#[allow(dead_code)]
pub fn background_type_name(bg_type: BackgroundType) -> &'static str {
    match bg_type {
        BackgroundType::SolidColor => "Solid Color",
        BackgroundType::VerticalGradient => "Vertical Gradient",
        BackgroundType::HorizontalGradient => "Horizontal Gradient",
        BackgroundType::Checkerboard => "Checkerboard",
        BackgroundType::Cubemap => "Cubemap",
    }
}

/// Return `true` if the background type produces a pattern that varies across
/// the viewport (i.e. is not a single flat colour).
#[allow(dead_code)]
pub fn is_dynamic_background(bg_type: BackgroundType) -> bool {
    !matches!(bg_type, BackgroundType::SolidColor)
}

/// Serialise a background config to a JSON string.
#[allow(dead_code)]
pub fn background_to_json(config: &BackgroundConfig) -> String {
    format!(
        concat!(
            "{{\n",
            "  \"type\": \"{}\",\n",
            "  \"top_color\": [{:.6}, {:.6}, {:.6}, {:.6}],\n",
            "  \"bottom_color\": [{:.6}, {:.6}, {:.6}, {:.6}],\n",
            "  \"checker_size\": {}\n",
            "}}"
        ),
        background_type_name(config.bg_type),
        config.top_color[0],
        config.top_color[1],
        config.top_color[2],
        config.top_color[3],
        config.bottom_color[0],
        config.bottom_color[1],
        config.bottom_color[2],
        config.bottom_color[3],
        config.checker_size,
    )
}

/// Generate a flat pixel grid of background samples.
///
/// Returns a `Vec<BackgroundSample>` with `width * height` entries in row-major
/// order (top-left to bottom-right).
#[allow(dead_code)]
pub fn background_pixel_grid(
    config: &BackgroundConfig,
    width: u32,
    height: u32,
) -> Vec<BackgroundSample> {
    let w = width.max(1);
    let h = height.max(1);
    let mut out = Vec::with_capacity((w * h) as usize);
    for row in 0..h {
        let v = if h > 1 {
            row as f32 / (h - 1) as f32
        } else {
            0.0
        };
        for col in 0..w {
            let u = if w > 1 {
                col as f32 / (w - 1) as f32
            } else {
                0.0
            };
            out.push(sample_background(config, u, v));
        }
    }
    out
}

// ── Tests ────────────────────────────────────────────────────────────────────

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

    #[test]
    fn default_config_is_solid() {
        let cfg = default_background_config();
        assert_eq!(cfg.bg_type, BackgroundType::SolidColor);
    }

    #[test]
    fn new_background_config_sets_type() {
        let cfg = new_background_config(BackgroundType::Checkerboard);
        assert_eq!(cfg.bg_type, BackgroundType::Checkerboard);
    }

    #[test]
    fn sample_solid_returns_top_color() {
        let cfg = default_background_config();
        let s = sample_background(&cfg, 0.5, 0.5);
        assert_eq!(s.color, cfg.top_color);
    }

    #[test]
    fn gradient_color_at_zero() {
        let a = [1.0, 0.0, 0.0, 1.0];
        let b = [0.0, 1.0, 0.0, 1.0];
        let c = gradient_color(&a, &b, 0.0);
        assert!((c[0] - 1.0).abs() < 1e-6);
        assert!((c[1] - 0.0).abs() < 1e-6);
    }

    #[test]
    fn gradient_color_at_one() {
        let a = [1.0, 0.0, 0.0, 1.0];
        let b = [0.0, 1.0, 0.0, 1.0];
        let c = gradient_color(&a, &b, 1.0);
        assert!((c[0] - 0.0).abs() < 1e-6);
        assert!((c[1] - 1.0).abs() < 1e-6);
    }

    #[test]
    fn gradient_color_midpoint() {
        let a = [0.0, 0.0, 0.0, 1.0];
        let b = [1.0, 1.0, 1.0, 1.0];
        let c = gradient_color(&a, &b, 0.5);
        assert!((c[0] - 0.5).abs() < 1e-6);
    }

    #[test]
    fn vertical_gradient_top_is_top_color() {
        let mut cfg = default_background_config();
        set_background_type(&mut cfg, BackgroundType::VerticalGradient);
        set_top_color(&mut cfg, [1.0, 0.0, 0.0, 1.0]);
        set_bottom_color(&mut cfg, [0.0, 0.0, 1.0, 1.0]);
        let s = sample_background(&cfg, 0.5, 0.0);
        assert!((s.color[0] - 1.0).abs() < 1e-6);
    }

    #[test]
    fn horizontal_gradient_varies_by_u() {
        let mut cfg = new_background_config(BackgroundType::HorizontalGradient);
        cfg.top_color = [0.0, 0.0, 0.0, 1.0];
        cfg.bottom_color = [1.0, 1.0, 1.0, 1.0];
        let left = sample_background(&cfg, 0.0, 0.5);
        let right = sample_background(&cfg, 1.0, 0.5);
        assert!((left.color[0] - 0.0).abs() < 1e-6);
        assert!((right.color[0] - 1.0).abs() < 1e-6);
    }

    #[test]
    fn checkerboard_alternates() {
        let mut cfg = new_background_config(BackgroundType::Checkerboard);
        cfg.top_color = [1.0, 1.0, 1.0, 1.0];
        cfg.bottom_color = [0.0, 0.0, 0.0, 1.0];
        cfg.checker_size = 16;
        let s1 = sample_background(&cfg, 0.0, 0.0);
        let s2 = sample_background(&cfg, 16.0 / 1024.0, 0.0);
        // They should differ (one white, one black)
        assert_ne!(s1.color, s2.color);
    }

    #[test]
    fn set_checker_size_clamps_min() {
        let mut cfg = default_background_config();
        set_checker_size(&mut cfg, 0);
        assert_eq!(cfg.checker_size, 1);
    }

    #[test]
    fn background_type_name_all_variants() {
        assert_eq!(
            background_type_name(BackgroundType::SolidColor),
            "Solid Color"
        );
        assert_eq!(
            background_type_name(BackgroundType::VerticalGradient),
            "Vertical Gradient"
        );
        assert_eq!(
            background_type_name(BackgroundType::HorizontalGradient),
            "Horizontal Gradient"
        );
        assert_eq!(
            background_type_name(BackgroundType::Checkerboard),
            "Checkerboard"
        );
        assert_eq!(background_type_name(BackgroundType::Cubemap), "Cubemap");
    }

    #[test]
    fn is_dynamic_background_correct() {
        assert!(!is_dynamic_background(BackgroundType::SolidColor));
        assert!(is_dynamic_background(BackgroundType::VerticalGradient));
        assert!(is_dynamic_background(BackgroundType::HorizontalGradient));
        assert!(is_dynamic_background(BackgroundType::Checkerboard));
        assert!(is_dynamic_background(BackgroundType::Cubemap));
    }

    #[test]
    fn background_to_json_contains_type() {
        let cfg = default_background_config();
        let json = background_to_json(&cfg);
        assert!(json.contains("Solid Color"));
        assert!(json.contains("top_color"));
        assert!(json.contains("bottom_color"));
    }

    #[test]
    fn background_pixel_grid_correct_count() {
        let cfg = default_background_config();
        let grid = background_pixel_grid(&cfg, 4, 3);
        assert_eq!(grid.len(), 12);
    }

    #[test]
    fn background_pixel_grid_single_pixel() {
        let cfg = default_background_config();
        let grid = background_pixel_grid(&cfg, 1, 1);
        assert_eq!(grid.len(), 1);
    }

    #[test]
    fn cubemap_is_direction_dependent() {
        let cfg = new_background_config(BackgroundType::Cubemap);
        let up = sample_background(&cfg, 0.5, 0.0);   // looking up
        let down = sample_background(&cfg, 0.5, 1.0); // looking down
        // Zenith and nadir must differ -> genuine environment, not a flat colour.
        assert_ne!(up.color, down.color);
        // Zenith should be near top_color, nadir near bottom_color (blue channel).
        assert!((up.color[2] - cfg.top_color[2]).abs() < 0.06);
        assert!((down.color[2] - cfg.bottom_color[2]).abs() < 0.06);
    }

    #[test]
    fn direction_to_face_uv_axes() {
        // +X direction selects face 0, centre of the face.
        let (face, s, t) = direction_to_face_uv([1.0, 0.0, 0.0]);
        assert_eq!(face, 0);
        assert!((s - 0.5).abs() < 1e-6 && (t - 0.5).abs() < 1e-6);
        // +Y selects face 2, -Z selects face 5.
        assert_eq!(direction_to_face_uv([0.0, 1.0, 0.0]).0, 2);
        assert_eq!(direction_to_face_uv([0.0, 0.0, -1.0]).0, 5);
    }
}