The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
//! Descriptors scene code passes to the engine (materials, lights, camera, environment; see world.rs and the
//! binding in packages/scene/src/engine.ts) and the render presets. Texture / object references are engine handles.
use serde::Deserialize;
pub type Vec3 = [f32; 3];
#[derive(Deserialize, Debug, Clone)]
pub struct Shader {
/// `fn mf_<id>(i: MatIn, m: Material, base: MatOut) -> MatOut { ... }`
pub code: String,
#[serde(default)]
pub helpers: String,
}
/// A model's material function on its file's materials whose name starts with `prefix` (`GLTFModel.functions`).
#[derive(Deserialize, Debug, Clone, PartialEq)]
pub struct ModelFunction {
pub prefix: String,
pub shader: ShaderRef,
}
/// A material's binding to a material function: 32 parameter floats (8 vec4) and up to 8 textures.
#[derive(Deserialize, Debug, Clone, PartialEq)]
pub struct ShaderRef {
/// Material function name.
pub id: String,
pub params: Vec<f32>,
pub textures: Vec<Option<u32>>,
}
#[derive(Deserialize, Debug, Clone)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum Light {
#[serde(rename_all = "camelCase")]
Directional { color: Vec3, cast_shadow: bool, intensity: f32, angular_diameter: f32, #[serde(default = "one")] volumetric_scattering: f32, #[serde(default = "one")] specular_scale: f32 },
#[serde(rename_all = "camelCase")]
Point { color: Vec3, cast_shadow: bool, intensity: f32, radius: f32, range: f32, #[serde(default = "one")] volumetric_scattering: f32, #[serde(default = "one")] specular_scale: f32 },
#[serde(rename_all = "camelCase")]
Spot { color: Vec3, cast_shadow: bool, intensity: f32, radius: f32, range: f32, angle: f32, penumbra: f32, #[serde(default = "one")] volumetric_scattering: f32, #[serde(default = "one")] specular_scale: f32 },
/// Luminance (nits), one-sided Lambertian rectangle; analytic (lighting only) unless `card` rendering is wanted.
#[serde(rename_all = "camelCase")]
Rect {
color: Vec3,
cast_shadow: bool,
intensity: f32,
width: f32,
height: f32,
#[serde(default)]
range: f32,
#[serde(default = "ninety")]
barn_door_angle: f32,
#[serde(default = "one")]
volumetric_scattering: f32,
#[serde(default = "one")]
specular_scale: f32,
/// Visible emissive card (default, three.js-scene semantics) or a pure light (UE RectLight).
#[serde(default = "yes")]
visible: bool,
},
}
fn yes() -> bool {
true
}
fn ninety() -> f32 {
90.0
}
#[derive(Deserialize, Debug, Clone, PartialEq)]
#[serde(tag = "mode", rename_all = "camelCase")]
pub enum Exposure {
Manual { ev100: f32 },
#[serde(rename_all = "camelCase")]
Auto { compensation: f32, min_ev100: f32, max_ev100: f32 },
}
impl Exposure {
/// The EV100 a scene is taken to be shown at before a frame says: the manual value, or auto exposure's brightest.
/// The kernel's firefly clamp is relative to it (`NativePreset::firefly_clamp`).
pub fn ev_guess(&self) -> f32 {
match self {
Exposure::Manual { ev100 } => *ev100,
Exposure::Auto { max_ev100, .. } => *max_ev100,
}
}
/// The exposure a view starts at: manual, 2^-EV100; auto, a first guess (the histogram takes over from frame 1).
pub fn start(&self) -> f32 {
match self {
Exposure::Manual { ev100 } => 2f32.powf(-ev100),
Exposure::Auto { compensation, max_ev100, .. } => 2f32.powf(*compensation) / 2f32.powf(*max_ev100),
}
}
}
#[derive(Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Dof {
pub focus_distance: f32,
pub f_stop: f32,
pub sensor_width: f32,
}
/// Pose of an animated model: clip (by name) sampled at `time` s, then the nodes the game poses itself (`nodes`).
/// Without a clip the nodes not named stay as the file has them.
#[derive(Deserialize, Debug, Clone, PartialEq)]
pub struct Animation {
#[serde(default)]
pub clip: String,
#[serde(default)]
pub time: f32,
#[serde(default = "yes")]
pub r#loop: bool,
/// Local transforms of nodes by name, over the clip's: 4 numbers (rotation, quaternion xyzw) or 7 (translation xyz,
/// then the rotation). A skeleton posed by the game: aim, look, procedural steps, ragdolls.
#[serde(default)]
pub nodes: std::collections::BTreeMap<String, Vec<f32>>,
}
#[derive(Deserialize, Debug, Clone)]
pub struct Camera {
pub fov: f32,
#[allow(dead_code)]
pub near: f32,
#[allow(dead_code)]
pub far: f32,
pub exposure: Exposure,
pub dof: Option<Dof>,
}
#[derive(Deserialize, Debug, Clone)]
pub struct Environment {
pub sky: Sky,
pub fog: Option<Fog>,
/// three.js `scene.background`: what camera rays that miss see (radiance, linear rgb), lighting nothing.
#[serde(default)]
pub background: Option<Vec3>,
/// Global surface wetness 0..1 (material functions' `i.wetness`).
#[serde(default)]
pub wetness: f32,
/// Rain intensity 0..1 (material functions' `i.rain`: ripples on wet surfaces).
#[serde(default)]
pub rain: f32,
/// Cloud cover 0..1 of an atmosphere sky (`sky::bake_atmosphere_tables`: an overcast dome, the sun dimmed), changed
/// in place.
#[serde(default, rename = "cloudCover")]
pub cloud_cover: f32,
}
/// Exponential height fog (UE ExponentialHeightFog): extinction `density * exp(-heightFalloff * (y - height))`.
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Fog {
pub density: f32,
pub height_falloff: f32,
#[serde(default)]
pub height: f32,
/// Ambient inscattering radiance (linear rgb x intensity, nits).
pub color: Vec3,
pub intensity: Option<f32>,
#[serde(default)]
pub start_distance: f32,
pub max_opacity: Option<f32>,
pub volumetric: Option<Volumetric>,
}
/// Single scattering of lights and emissive surfaces in the fog along camera rays (halos, light shafts).
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Volumetric {
/// Scattering albedo (0..1).
pub scattering: f32,
/// Henyey-Greenstein phase anisotropy (-1..1).
#[serde(default)]
pub anisotropy: f32,
/// Density multiplier inside the volumetric range (UE VolumetricFogExtinctionScale relative to the height fog).
#[serde(default = "one")]
pub extinction_scale: f32,
/// Scattering tint.
pub albedo: Option<Vec3>,
/// Range of the lit volumetric fog from the camera, m (beyond: height fog only). 0 = unlimited.
#[serde(default)]
pub distance: f32,
}
#[derive(Deserialize, Debug, Clone, PartialEq)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum Sky {
/// `dynamic`: the sun moves while the scene runs (time of day). The live view then bakes the sky at
/// `sky::DYNAMIC_SKY` on a worker thread as the sun moves, instead of rebuilding the scene; offline renders bake it
/// at that size too, so both see the same sky. `glow`: night-sky radiance (nits) added above the horizon.
#[serde(rename_all = "camelCase")]
Atmosphere {
sun: Option<u32>,
ground_albedo: Vec3,
rayleigh_scale: f32,
mie_scale: f32,
mie_anisotropy: f32,
sky_light_intensity: f32,
#[serde(default)]
dynamic: bool,
#[serde(default)]
glow: Option<Vec3>,
/// The glow's light dome: radiance (nits, RGB) at the horizon and the elevation (radians) it falls to 1/e by.
#[serde(default)]
horizon_glow: Option<[f32; 4]>,
/// Aerial perspective: the atmosphere's haze on the surfaces it lies in front of, at this multiple of its own
/// density (0 = off; pathtrace.wgsl `aerial_tr`).
#[serde(default)]
aerial: f32,
/// The viewer's altitude above the ground (m) on a planet whose ground is the scene's globe (`SkyAtmosphere`
/// `altitude`): the sky is baked from there, its horizon dipped (`sky::Horizon::Planet`), and the aerial
/// perspective runs over the sphere below the camera. Changing it re-bakes in place past a threshold
/// (live/edits.rs `move_altitude`). None: a flat world, the sky baked from the camera's height when built.
#[serde(default)]
altitude: Option<f32>,
},
#[serde(rename_all = "camelCase")]
Color { color: Vec3, intensity: f32, sky_light_intensity: f32 },
#[serde(rename_all = "camelCase")]
Hdri { texture: u32, intensity: f32, rotation: f32, sky_light_intensity: f32 },
/// Analytic night / overcast dome: zenith-horizon-ground gradient, horizon (light-pollution) glow, clouds.
#[serde(rename_all = "camelCase")]
Gradient { zenith: Vec3, horizon: Vec3, ground: Vec3, intensity: f32, horizon_exponent: Option<f32>, glow: Option<SkyGlow>, clouds: Option<SkyClouds>, sky_light_intensity: f32 },
}
#[derive(Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SkyGlow {
pub color: Vec3,
/// Relative to `intensity`.
pub intensity: f32,
/// Elevation falloff (radians to 1/e).
#[serde(default)]
pub height: f32,
/// UE band: (1 - |sin e| * width)^power when set.
pub width: Option<f32>,
pub power: Option<f32>,
}
#[derive(Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SkyClouds {
/// 0..1 sky fraction.
pub coverage: f32,
/// Radiance of the cloud base, relative to `intensity` (night clouds are lit from below by the city).
pub color: Vec3,
/// Angular size of cloud features (larger = bigger clouds).
#[serde(default = "one")]
pub scale: f32,
#[serde(default)]
pub seed: f32,
/// Tileable cloud mask (R): UE-style projection, smoothstep(threshold), sky * gain + color.
pub map: Option<u32>,
pub threshold: Option<[f32; 2]>,
pub gain: Option<f32>,
pub projection: Option<f32>,
pub bias: Option<f32>,
pub fade: Option<f32>,
}
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Material {
#[allow(dead_code)]
pub name: String,
pub color: Vec3,
pub opacity: f32,
pub metalness: f32,
pub roughness: f32,
pub emissive: Vec3,
pub emissive_intensity: f32,
pub map: Option<u32>,
pub normal_map: Option<u32>,
pub normal_scale: Option<[f32; 2]>,
pub roughness_map: Option<u32>,
pub metalness_map: Option<u32>,
pub ao_map: Option<u32>,
pub emissive_map: Option<u32>,
pub specular_intensity: Option<f32>,
pub clearcoat: Option<f32>,
pub clearcoat_roughness: Option<f32>,
pub transmission: Option<f32>,
/// Red channel scales `transmission` (glTF transmissionTexture).
#[serde(default)]
pub transmission_map: Option<u32>,
pub ior: Option<f32>,
pub double_sided: bool,
/// Alpha cutout threshold on base-colour alpha x opacity (None = opaque).
pub alpha_test: Option<f32>,
/// Blended by opacity: particles with it go through the translucency pass (gpu.rs `Translucent`).
#[serde(default)]
pub transparent: bool,
pub shader: Option<ShaderRef>,
/// three.js MeshBasicMaterial: shows color x map to camera rays, lit by nothing, lighting nothing (F_UNLIT).
#[serde(default)]
pub unlit: bool,
/// three.js `vertexColors`: the color is multiplied by the geometry's vertex colours (F_VCOLOR).
#[serde(default)]
pub vertex_colors: bool,
}
// ------------------------------------------------------------------------------------------------
// Presets (presets/*.json)
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Preset {
pub name: String,
pub post: PostPreset,
pub native: NativePreset,
}
/// The post chain's settings (`post` of a preset; post.rs says what each does). Their names and meanings follow
/// Unreal's Post Process Volume settings as its documentation describes them, so that a scene's look can be compared
/// with the same settings there. The presets also carry a `tonemapper` block (Unreal's Film slope / toe / shoulder /
/// clips) for the comparison scripts in ue5/: the renderer's tone curve (`post::ToneCurve`) is fitted to the look
/// those values give and reads none of them.
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct PostPreset {
pub color_grading: ColorGrading,
pub bloom: Bloom,
/// Vignette (0 = off): natural cos^4 falloff toward the corners (`post::vignette`).
pub vignette: f32,
pub auto_exposure: AutoExposure,
/// Film grain (0..1; 0 = off): zero-mean luminance noise, strongest in the mid-tones, new each frame.
#[serde(default)]
pub film_grain: f32,
/// Chromatic aberration (0..5; 0 = off): red and blue apart, growing from the centre.
#[serde(default)]
pub chromatic_aberration: f32,
/// Local exposure: contrast of the large-scale luminance about middle grey.
#[serde(default)]
pub local_exposure: LocalExposure,
/// Motion blur (amount, max, target FPS). The presets switch it off: stills and temporal benchmarks compare
/// unblurred frames.
#[serde(default)]
pub motion_blur: MotionBlur,
}
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase", default)]
pub struct MotionBlur {
/// The shutter as a fraction of the frame time (0 = off).
pub amount: f32,
/// Longest blur, percent of the view width.
pub max: f32,
/// Blur length as if the frames came at this rate (0: at the rate they come).
pub target_fps: f32,
}
impl Default for MotionBlur {
fn default() -> Self {
MotionBlur { amount: 0.5, max: 5.0, target_fps: 30.0 }
}
}
/// Local exposure (`post::local_exposure_factor`): all three of the first at 1 = off.
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase", default)]
pub struct LocalExposure {
/// Scale of the base layer's distance above / below middle grey (< 1 compresses highlights / lifts shadows).
pub highlight_contrast: f32,
pub shadow_contrast: f32,
/// Scale of the detail layer (> 1 boosts local detail).
pub detail_strength: f32,
/// The base layer: the edge-aware blur of log luminance, blended by this much with a wide plain blur.
pub blurred_luminance_blend: f32,
/// The wide blur's size, percent of the view width (a bloom stage's measure: `post::BloomPlan`).
pub blurred_luminance_kernel: f32,
}
impl Default for LocalExposure {
fn default() -> Self {
LocalExposure { highlight_contrast: 1.0, shadow_contrast: 1.0, detail_strength: 1.0, blurred_luminance_blend: 0.6, blurred_luminance_kernel: 50.0 }
}
}
/// Colour grading, on scene-linear colour before the tone curve (`post::Tonemapper`).
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ColorGrading {
/// Gamut expansion (0 = none, 1 = the presets' look): bright saturated colours are pushed beyond sRGB's gamut
/// before the tone curve.
#[serde(default = "one")]
pub expand_gamut: f32,
/// How much of the Academy's blue-light-artifact fix the tone curve works under (0 .. 1): bright blues
/// desaturate instead of turning violet.
#[serde(default = "blue")]
pub blue_correction: f32,
/// White balance: the scene illuminant (K) that renders as white, and its green-magenta tint.
#[serde(default = "d65")]
pub white_temp: f32,
#[serde(default)]
pub white_tint: f32,
/// Saturation and contrast of the whole picture, gain of its shadows and of its highlights: scalar or RGB,
/// 1 = none.
#[serde(default = "one3")]
pub saturation: Rgb,
#[serde(default = "one3")]
pub contrast: Rgb,
#[serde(default = "one3")]
pub shadows_gain: Rgb,
#[serde(default = "one3")]
pub highlights_gain: Rgb,
}
/// A scalar or RGB grading value.
#[derive(Deserialize, Debug, Clone, Copy)]
#[serde(from = "RgbIn")]
pub struct Rgb(pub [f32; 3]);
#[derive(Deserialize)]
#[serde(untagged)]
enum RgbIn {
S(f32),
V([f32; 3]),
}
impl From<RgbIn> for Rgb {
fn from(v: RgbIn) -> Self {
match v {
RgbIn::S(s) => Rgb([s; 3]),
RgbIn::V(v) => Rgb(v),
}
}
}
fn one3() -> Rgb {
Rgb([1.0; 3])
}
fn d65() -> f32 {
6500.0
}
fn blue() -> f32 {
0.6
}
/// Bloom (`post::BloomPlan`): a sum of Gaussian blurs of the picture, added to it.
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Bloom {
/// Scale of the whole glow (0 = off).
pub intensity: f32,
/// Exposed luminance from which a pixel blooms, fading in over one unit above it (< 0: everything blooms).
pub threshold: f32,
/// The stages' sizes (percent of the view width, times `size_scale`) and weights: up to six.
pub size_scale: f32,
pub sizes: Vec<f32>,
pub tints: Vec<f32>,
}
/// Auto exposure's metering (`post::exposure_scale`).
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct AutoExposure {
/// The percentiles of the luminance histogram between which the average is taken.
pub low_percent: f32,
pub high_percent: f32,
/// The histogram's range, log2 luminance (nits). The presets use -10 .. 20, the extended range Unreal's
/// documentation describes (there in EV100): a range of -8 .. 4 saturates in daylight (a 3000-nit sky would pin
/// the exposure at its top); scenes ported from a project with that range set it explicitly.
pub histogram_log_min: f32,
pub histogram_log_max: f32,
/// Adaptation speed toward brighter / darker scenes, EV per second (real-time only).
#[serde(default = "three")]
pub speed_up: f32,
#[serde(default = "one")]
pub speed_down: f32,
}
fn three() -> f32 {
3.0
}
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct NativePreset {
pub spp: u32,
pub max_bounces: u32,
pub denoise: bool,
pub clamp_indirect: f32,
pub russian_roulette_depth: u32,
#[serde(default = "one")]
pub energy_compensation: f32,
}
fn one() -> f32 {
1.0
}
impl NativePreset {
/// The kernel's firefly clamp on indirect paths (`Params::misc[0]`): relative to the exposure, so that it is the
/// same in every scene.
pub fn firefly_clamp(&self, exposure: &Exposure) -> f32 {
self.clamp_indirect * 2f32.powf(exposure.ev_guess())
}
}
pub fn merge_json(a: &mut serde_json::Value, b: &serde_json::Value) {
match (a, b) {
(serde_json::Value::Object(a), serde_json::Value::Object(b)) => {
for (k, v) in b {
merge_json(a.entry(k.clone()).or_insert(serde_json::Value::Null), v);
}
}
(a, b) => *a = b.clone(),
}
}