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
//! The engine's scene: objects, geometry, materials, textures, lights, environment, created and edited by scene code
//! through the engine API (the binding in packages/scene/src/engine.ts, installed into the embedded JS runtime by
//! script.rs). There is no scene document in between: the binding calls these operations directly.
//!
//! Every operation records what it changed. Parameter changes (node power, light colour / intensity, material
//! parameters, wetness / rain / fog, the camera) are applied by `LiveCore::commit` to the GPU tables in place;
//! anything else (objects added / removed / moved / hidden, geometry, textures, material functions, sky) rebuilds the
//! GPU scene from the world.
use crate::desc;
use anyhow::{anyhow, Result};
use glam::{Mat4, Quat, Vec3};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::sync::Arc;
/// Triangle mesh data as the scene code built it (three.js conventions: UV v up).
#[derive(Clone, Debug, Default)]
pub struct Geometry {
pub positions: Vec<f32>,
pub normals: Vec<f32>,
pub uvs: Vec<f32>,
pub indices: Vec<u32>,
/// (first index, index count, material index) per group: a mesh with several materials (`Kind::Mesh::materials`)
/// draws each group's triangles with its material; none: one material for all.
pub groups: Vec<[u32; 3]>,
/// Vertex colours (three.js's `color` attribute: linear RGB per vertex), or none. A material with `vertexColors`
/// multiplies its colour by them (F_VCOLOR).
pub colors: Vec<f32>,
}
/// How stateful particles collide: a plane at `plane` (y, m), the voxel occupancy grid; a bounce keeps `restitution` of
/// the speed along the surface's normal and loses `friction` of it across.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ParticleCollide {
pub plane: Option<f32>,
pub voxels: bool,
pub restitution: f32,
pub friction: f32,
}
/// A world-aligned occupancy grid of the voxel engine's objects (a cell occupied if any voxel in it is): one bit a cell,
/// 32 cells along x a word, rows x then z then y; the word ranges changed since it was last uploaded.
#[derive(Clone, Debug, Default)]
pub struct Occupancy {
pub origin: [f32; 3],
pub cell: f32,
pub dims: [u32; 3],
pub words: Vec<u32>,
pub dirty: Vec<(usize, usize)>,
}
impl Occupancy {
/// Words per row (x).
pub fn row_words(&self) -> usize {
(self.dims[0] as usize).div_ceil(32)
}
}
/// A density grid (`DensityGrid` in packages/scene; ROADMAP § 6 step 5b): `dims` cells over a box `VolumeMesh`, four
/// numbers a cell (field A: what the volume function reads with `vgrid`), given by the game (`data`, x fastest, then y,
/// then z; None: zeros) and, with a grid program, changed every frame on the GPU (renderer/shaders/grid_sim.wgsl; a
/// second field B of four numbers is the program's own, e.g. a velocity).
#[derive(Clone, Debug)]
pub struct DensityGrid {
pub dims: [u32; 3],
pub data: Option<Arc<Vec<f32>>>,
/// The grid program (by name) and its 32 parameter floats.
pub program: Option<(String, Vec<f32>)>,
/// A number of its own for the grid as it was made: another when it is made again with another size or another
/// program. What a program has simulated in it is carried across a rebuild while this stays (gpu.rs `carry_grids`).
pub made: u32,
}
/// A grid's most cells per axis (pathtrace.wgsl `vgrid` packs them in 10 bits each) and in all (8 bytes a cell and
/// field: 67 MB, four times that with a program); a scene's grids together: twice that, at most 2048 layers along z
/// (they are stacked in one 3D texture).
pub const GRID_MAX_AXIS: u32 = 512;
pub const GRID_MAX_CELLS: u64 = 1 << 23;
pub const GRID_MAX_SCENE_CELLS: u64 = 1 << 24;
pub const GRID_MAX_LAYERS: u32 = 2048;
/// Sources a grid takes a frame (grid_sim.wgsl `sources`: three vec4 each).
pub const GRID_MAX_SOURCES: usize = 64;
/// Procedural geometry (`ProceduralGeometry` in packages/scene): object-space AABBs (min xyz, max xyz each) that the
/// geometry function `function` (pathtrace.wgsl `gf_<name>`) intersects, and the game's own data it reads (`i.data`):
/// passed by the scene code, or an asset file the scene build reads (src/procasset.rs).
#[derive(Clone, Debug)]
pub struct ProcGeometry {
pub function: String,
pub source: ProcSource,
}
#[derive(Clone, Debug)]
pub enum ProcSource {
Inline(Arc<crate::procasset::ProcBlob>),
/// Path relative to the asset root.
Asset(String),
}
/// AABBs a procedural geometry may have: the hit's primitive index has 23 bits (pathtrace.wgsl `PROC_BIT`).
pub const PROC_MAX_BOXES: usize = (1 << 23) - 1;
#[derive(Clone, Debug, PartialEq)]
pub enum TextureSource {
/// Path relative to the asset root.
File(String),
/// Encoded image (PNG / JPEG) the scene code carries (e.g. an embedded atlas).
Encoded(Arc<Vec<u8>>),
/// RGBA8 pixels generated by the scene code.
Pixels { width: u32, height: u32, rgba: Arc<Vec<u8>> },
/// RGBA8 pixels the app replaces while the scene runs, under a name (`LiveCore::write_stream`: a screen, a
/// camera, a video). `rgba` is the picture until the first one arrives. Its place in the texture pages is its
/// name and size, so new pixels rebuild nothing.
Stream { name: String, width: u32, height: u32, rgba: Arc<Vec<u8>> },
}
#[derive(Clone, Debug, PartialEq)]
pub struct Texture {
pub source: TextureSource,
pub srgb: bool,
pub wrap: bool,
pub repeat: [f32; 2],
pub offset: [f32; 2],
}
#[derive(Clone, Debug)]
pub enum Kind {
Group,
/// `own_blas` (scene code's `dynamicGeometry`): a mesh of its own, so replacing its geometry, creating or removing
/// it is applied in place (live/edits.rs `edit_geometry`) instead of rebuilding the scene; otherwise an instance
/// of the mesh every object of its geometry shares.
/// `materials`: one per geometry group (three.js's material array; empty: `material` for every triangle).
Mesh { geometry: u32, material: u32, own_blas: bool, materials: Vec<u32> },
/// glTF asset (path relative to the asset root), optionally only some of its nodes (by name).
/// `functions`: material functions on its materials, by name prefix (`GLTFModel.functions`).
Model { uri: String, nodes: Option<Vec<String>>, animation: Option<desc::Animation>, functions: Vec<desc::ModelFunction> },
Light(desc::Light),
Camera(desc::Camera),
/// `count` particles: each a quad that the particle function `emitter` (with `params`, 8 vec4) places every frame
/// on the GPU, drawn with `material`.
/// `emitter_area` (m², 0 = none): a particle's nominal area for light sampling (scene.rs, pathtrace.wgsl emit_mis).
Particles { count: u32, emitter: String, params: Vec<f32>, material: u32, emitter_area: f32 },
/// Stateful GPU particles (`GpuParticles`; ROADMAP § 6 step 5a): up to `capacity`, emitted and updated on the GPU by
/// the particle program `program` (with `params`, 8 vec4), `rate` a second from the node and as the game spawns
/// them (`World::particle_spawns`), collided (`collide`), drawn with `material` as `Particles` are.
GpuParticles { capacity: u32, program: String, params: Vec<f32>, material: u32, emitter_area: f32, rate: f32, collide: ParticleCollide },
/// A bounded participating medium (`VolumeMesh`): the unit box / sphere (shape 0 / 1) under the node's transform,
/// its volume function and 32 parameter floats, majorant (1/m) and HG anisotropy.
/// `homogeneous`: constant coefficients in the function's first parameters (albedo rgb + extinction, emission
/// rgb), so the live kernel can use them without the function (pathtrace.wgsl `media_homogeneous`).
/// `animated`: it changes with time (the live view keeps a short history of the pixels it fills).
/// `grid`: its density grid (`World::grids`; box volumes), which the volume function reads with `vgrid`.
Volume { function: String, params: Vec<f32>, shape: u32, majorant: f32, g: f32, homogeneous: bool, animated: bool, grid: Option<u32> },
/// Procedural geometry (`ProceduralMesh`) under the node's transform, shaded with `materials[k]` for the k its
/// geometry function returns. Always instanced: a move rewrites its transform, never a rebuild.
Procedural { geometry: u32, materials: Vec<u32> },
/// Copies of one geometry (scene code's `InstancedMesh`): triangle geometry `geometry` drawn with `materials[0]`,
/// or procedural geometry (`procedural`) with `materials` as a `Procedural` has them. `capacity` instances, whose
/// transforms (relative to the node), colours and per-instance data are its `World::instanced` table; one BLAS for
/// all, one TLAS instance each, so the table changes in place (live/edits.rs `update_instanced`), never a rebuild.
Instanced { geometry: u32, procedural: bool, materials: Vec<u32>, capacity: u32 },
}
/// The instances of an `Instanced` object (`World::set_instances`, checked there): the first `count` of its
/// `capacity` are drawn. Matrices are column-major 4 x 4 (three.js `instanceMatrix`), relative to the node; colours
/// (three.js `instanceColor`, linear rgb) multiply the material's base colour; per-instance data replaces the node's
/// `customData`.
#[derive(Clone, Debug, Default)]
pub struct InstanceTable {
pub count: u32,
pub matrices: Arc<Vec<f32>>,
pub colors: Option<Arc<Vec<f32>>>,
pub custom: Option<Arc<Vec<f32>>>,
}
impl InstanceTable {
pub fn matrix(&self, i: usize) -> Mat4 {
self.matrices.get(i * 16..i * 16 + 16).map_or(Mat4::ZERO, Mat4::from_cols_slice)
}
pub fn color(&self, i: usize) -> [f32; 3] {
self.colors.as_ref().and_then(|c| c.get(i * 3..i * 3 + 3)).map_or([1.0; 3], |c| [c[0], c[1], c[2]])
}
pub fn custom(&self, i: usize, node: [f32; 4]) -> [f32; 4] {
self.custom.as_ref().and_then(|c| c.get(i * 4..i * 4 + 4)).map_or(node, |c| [c[0], c[1], c[2], c[3]])
}
}
#[derive(Clone, Debug)]
pub struct Object {
/// The scene code's id / name for it (picking reports it, gameplay events use it).
pub name: String,
pub parent: Option<u32>,
pub kind: Kind,
pub position: Vec3,
pub rotation: Quat,
pub scale: Vec3,
pub visible: bool,
pub cast_shadow: bool,
/// UE material "Power": scales everything the object emits (meshes, models, its light).
pub power: f32,
/// Per-instance data (UE PerInstanceCustomData): any four numbers scene code gives the object, read by material
/// functions as `i.custom` (particle functions write one per particle).
pub custom: [f32; 4],
/// UE Mobility "Movable": scripts move it (and everything under it) without rebuilding the scene: its instances'
/// transforms. Set by scene code, or by the first move.
pub movable: bool,
/// A rigid body drives it (renderer/src/physics.rs): movable, and a mesh among them is placed as an instance of its
/// own BLAS, so a move is its TLAS transform and no triangle.
pub driven: bool,
/// Wind sway (`windSway` in packages/scene): the renderer leans the object about its origin with scene time.
pub sway: Option<Sway>,
/// The sway's current rotation (identity without one), applied after the object's own rotation.
pub sway_rot: Quat,
}
impl Object {
pub fn local(&self) -> Mat4 {
Mat4::from_scale_rotation_translation(self.scale, self.sway_rot * self.rotation, self.position)
}
}
/// Rigid wind sway of a plant (ROADMAP § 5 item 6.5; `windSway` in packages/scene/src/effects.ts, which has the same
/// function as `windAngle`; keep in sync). The object leans downwind about its origin, around the horizontal axis across
/// the wind, by angle(t) = A (0.6 + 0.4 sin(w t + p) + 0.2 sin(2.7 w t + 2 p)) radians: a mean lean of 0.6 A with a
/// sway and a faster flutter on it, A = strength / (1 + stiffness), w = 2 pi frequency sqrt(1 + stiffness) (stiffer
/// plants lean less and sway faster). The phase p is given, or a hash of the object's world position (x, z), so a row
/// of plants does not sway in step.
#[derive(Clone, Copy, Debug, PartialEq, serde::Deserialize)]
pub struct Sway {
/// Where the wind blows, radians in the ground plane: (cos, sin) in (x, z).
pub direction: f32,
pub strength: f32,
/// Hz.
pub frequency: f32,
pub stiffness: f32,
#[serde(default)]
pub phase: Option<f32>,
}
impl Sway {
pub fn angle(&self, t: f32, phase: f32) -> f32 {
let k = 1.0 + self.stiffness.max(0.0);
let a = self.strength / k;
let w = std::f32::consts::TAU * self.frequency * k.sqrt();
a * (0.6 + 0.4 * (w * t + phase).sin() + 0.2 * (2.7 * w * t + 2.0 * phase).sin())
}
/// The lean at scene time t: up turns toward the wind's direction.
pub fn rotation(&self, t: f32, phase: f32) -> Quat {
let (s, c) = self.direction.sin_cos();
Quat::from_axis_angle(Vec3::new(s, 0.0, -c), self.angle(t, phase))
}
}
/// A sway phase from a world position: the same hash as `windPhase` in packages/scene.
pub fn sway_phase(p: Vec3) -> f32 {
let h = ((p.x * 12.9898 + p.z * 78.233).sin() * 43758.547).fract().abs();
std::f32::consts::TAU * h
}
#[derive(Clone, Debug)]
pub struct Settings {
pub name: String,
pub preset: String,
pub overrides: Option<serde_json::Value>,
pub width: u32,
pub height: u32,
/// Scene clock for stills, s.
pub time: f32,
pub camera: Option<u32>,
}
impl Default for Settings {
fn default() -> Settings {
Settings { name: "scene".into(), preset: "cinematic".into(), overrides: None, width: 1280, height: 720, time: 0.0, camera: None }
}
}
/// What changed since the last commit.
#[derive(Default, Debug, Clone)]
pub struct Changes {
pub structural: bool,
/// Objects shown or hidden by their own `visible` whose build can take it in place (live/edits.rs `commit`): particle
/// systems that are not light-sampled (gpu.rs `set_particles_hidden`), volumes (their medium: `set_medium_hidden`)
/// and lights without a card (their table entry goes black). A rebuild where the build left the object out.
pub shown: HashSet<u32>,
pub materials: HashSet<u32>,
/// Textures that were replaced by another (`World::set_texture`): the materials that name one are made again.
pub textures: HashSet<u32>,
/// A material function came or changed (`World::set_shader`): the kernel's code.
pub functions: bool,
/// A volume function came or changed (`World::set_volume_fn`): the kernel's code.
pub volume_functions: bool,
/// A volume came, went, was set again, or moved for the first time: the media table is made again from the world.
pub media: bool,
/// Objects whose light parameters changed.
pub lights: HashSet<u32>,
pub powers: HashSet<u32>,
/// Objects whose per-instance data changed.
pub customs: HashSet<u32>,
pub environment: bool,
pub camera: bool,
/// The atmosphere's sun moved (time of day): the live view rewrites its light and re-bakes the sky in place.
pub sun: bool,
/// Another sky (its kind or its parameters): baked and put in place (live/edits.rs `apply_sky`). With `environment`.
pub sky: bool,
/// Files whose last model left the world in this batch (`World::models`): the live view retires their materials
/// and frees the textures nothing names any more (live/edits.rs `retire_models`), unless one came back.
pub gone_models: HashSet<String>,
/// A planet's viewer altitude, the sky otherwise the same (`desc::Sky::Atmosphere::altitude`): re-baked in place
/// past a step (live/edits.rs `move_altitude`). With `environment`.
pub altitude: bool,
/// The scene camera's depth of field or exposure changed: the view's state, taken again in place (live/edits.rs
/// `apply_view`). Not `camera`: a view its host moved stays where it is.
pub view: bool,
/// The preset, its overrides or the scene's name changed: what a view takes from them is taken again in place
/// (`apply_view`).
pub settings: bool,
/// Models whose animation pose changed.
pub poses: HashSet<u32>,
/// Movable objects that moved: everything under them is re-transformed in place.
pub moved: HashSet<u32>,
/// Objects made movable by their first move (that move rebuilds once).
pub promoted: Vec<String>,
/// Still meshes, or groups, that moved for the first time (and are movable from now on): the renderer moves their
/// instances in place where it can (live/edits.rs `start_moving`), and rebuilds where it cannot.
pub started: HashSet<u32>,
/// Objects created (or re-created) in this batch: the rebuild builds them where they are, so setting their
/// transform is not a move.
pub created: HashSet<u32>,
/// Geometry edits the live view can apply in place (live/edits.rs `edit_geometry`), when nothing else is structural:
/// geometries replaced, objects created (or re-created with other geometry or materials) and objects removed,
/// whose objects carry their own BLAS (procedural meshes, `own_blas` meshes). The live view falls back to a
/// rebuild for what it cannot apply.
pub geometries: HashSet<u32>,
pub added: BTreeSet<u32>,
pub removed: BTreeSet<u32>,
/// Instanced objects whose instances changed (table, node transform, power, customData): rewritten in place
/// (live/edits.rs `update_instanced`).
pub instanced: HashSet<u32>,
/// Density grids created in this batch (their volume objects may not exist yet: `World::set_grid` keeps them).
pub grids_new: BTreeSet<u32>,
/// Materials created in this batch that bring no texture and no material function: the live view adds them in
/// place (live/edits.rs `add_materials`; a rebuild for one it cannot take), so an object added while the game runs may
/// come with a material of its own.
pub new_materials: BTreeSet<u32>,
}
impl Changes {
pub fn any(&self) -> bool {
self.structural || !self.shown.is_empty() || !self.new_materials.is_empty() || !self.materials.is_empty() || !self.textures.is_empty() || self.functions || self.volume_functions || self.media || !self.lights.is_empty() || !self.powers.is_empty() || !self.customs.is_empty() || self.environment || self.altitude || self.camera || self.sun || self.view || self.settings || !self.poses.is_empty() || !self.moved.is_empty() || !self.instanced.is_empty() || self.edits()
}
/// Geometry edits are pending (`geometries`, `added`, `removed`).
pub fn edits(&self) -> bool {
!self.geometries.is_empty() || !self.added.is_empty() || !self.removed.is_empty()
}
}
/// An object kind that is an instance of its geometry (one TLAS instance per object): its edits apply in place.
/// (`Kind::Mesh::own_blas`, scene code's `dynamicGeometry`, says that the scene edits it: the build keeps room for that.)
pub fn edits_in_place(k: &Kind) -> bool {
matches!(k, Kind::Procedural { .. } | Kind::Mesh { .. })
}
#[derive(Clone)]
pub struct World {
pub objects: BTreeMap<u32, Object>,
/// How many objects each object is the parent of (`remove` skips the scan for children of a childless one: a
/// streamed city removes thousands of objects a frame among tens of thousands). Kept by `set_object` and `remove`.
kids: HashMap<u32, u32>,
/// How many objects are models of each file (`scene::model_key`: the file and its material functions). Kept by
/// `set_object` and `remove`; a key's last model gone is `Changes::gone_models`, whose materials the live view
/// retires (live/edits.rs `retire_models`).
pub models: HashMap<String, u32>,
pub geometries: HashMap<u32, Arc<Geometry>>,
pub textures: HashMap<u32, Texture>,
pub materials: HashMap<u32, desc::Material>,
/// Material functions by name: (WGSL code, helpers).
pub shaders: BTreeMap<String, (String, String)>,
/// Particle functions by name: (WGSL code, helpers).
pub particle_fns: BTreeMap<String, (String, String)>,
/// Particle programs by name: (emit code, update code, helpers) (gpu_particles.wgsl `pe_` / `pu_<name>`).
pub particle_programs: BTreeMap<String, (String, String, String)>,
/// Particles the game spawned since the live view last took them (`GpuParticles.spawn`): per node, (x, y, z, -, r,
/// g, b, a) per particle.
pub particle_spawns: BTreeMap<u32, Vec<f32>>,
/// The voxel engine's occupancy grid (`collide.voxels`; renderer/src/voxel.rs) and the word ranges changed since the
/// live view last uploaded it.
pub voxel_occupancy: Option<Arc<std::sync::RwLock<Occupancy>>>,
/// Density grids by id (`Kind::Volume::grid`), the ones whose data changed since the live view last uploaded them,
/// grid programs by name: (WGSL code, helpers) (grid_sim.wgsl `gp_<name>`), and the sources the game gave since the
/// live view last took them: per volume object, (x, y, z, radius, a rgba, b rgba) each.
pub grids: HashMap<u32, DensityGrid>,
pub grid_dirty: BTreeSet<u32>,
/// The last `DensityGrid::made` given.
pub grids_made: u32,
pub grid_programs: BTreeMap<String, (String, String)>,
pub grid_sources: BTreeMap<u32, Vec<f32>>,
/// Volume functions by name: (WGSL code, helpers) (pathtrace.wgsl `vf_<name>`).
pub volume_fns: BTreeMap<String, (String, String)>,
/// Geometry functions by name: (WGSL code, helpers) (pathtrace.wgsl `gf_<name>`).
pub geometry_fns: BTreeMap<String, (String, String)>,
pub proc_geometries: HashMap<u32, Arc<ProcGeometry>>,
/// The instances of each `Kind::Instanced` object.
pub instanced: HashMap<u32, InstanceTable>,
pub environment: desc::Environment,
pub settings: Settings,
pub changes: Changes,
}
impl Default for World {
fn default() -> World {
World {
objects: BTreeMap::new(),
kids: HashMap::new(),
models: HashMap::new(),
geometries: HashMap::new(),
textures: HashMap::new(),
materials: HashMap::new(),
shaders: BTreeMap::new(),
particle_fns: BTreeMap::new(),
particle_programs: BTreeMap::new(),
particle_spawns: BTreeMap::new(),
voxel_occupancy: None,
grids: HashMap::new(),
grid_dirty: BTreeSet::new(),
grids_made: 0,
grid_programs: BTreeMap::new(),
grid_sources: BTreeMap::new(),
volume_fns: BTreeMap::new(),
geometry_fns: BTreeMap::new(),
proc_geometries: HashMap::new(),
instanced: HashMap::new(),
environment: desc::Environment { sky: desc::Sky::Color { color: [0.0; 3], intensity: 0.0, sky_light_intensity: 1.0 }, fog: None, background: None, wetness: 0.0, rain: 0.0, cloud_cover: 0.0 },
settings: Settings::default(),
changes: Changes { structural: true, ..Default::default() },
}
}
}
/// The textures a material names: its maps and its function's.
pub fn material_texture_ids(m: &desc::Material) -> impl Iterator<Item = u32> + '_ {
[m.map, m.normal_map, m.roughness_map, m.metalness_map, m.ao_map, m.emissive_map, m.transmission_map].into_iter().flatten().chain(m.shader.iter().flat_map(|s| s.textures.iter().flatten().copied()))
}
/// The size of a rect light's card, if it has one (`visible`).
fn card_size(l: &desc::Light) -> Option<(u32, u32)> {
match l {
desc::Light::Rect { width, height, visible: true, .. } => Some((width.to_bits(), height.to_bits())),
_ => None,
}
}
fn light_class(l: &desc::Light) -> (u8, bool, bool) {
match l {
desc::Light::Directional { cast_shadow, .. } => (0, *cast_shadow, false),
desc::Light::Point { cast_shadow, .. } => (1, *cast_shadow, false),
desc::Light::Spot { cast_shadow, .. } => (2, *cast_shadow, false),
desc::Light::Rect { cast_shadow, visible, .. } => (3, *cast_shadow, *visible),
}
}
/// Asset paths are relative to the asset root and stay inside it (game code is untrusted on render nodes), or name a
/// file of the game's store (`user:<store path>`, which stays inside the store: files.rs `asset_path`).
pub(crate) fn check_uri(uri: &str) -> Result<()> {
if let Some(rel) = uri.strip_prefix(crate::files::USER_SCHEME) {
return crate::files::check_store_path(rel).map_err(|e| anyhow!("asset path \"{uri}\": {e}"));
}
let p = std::path::Path::new(uri);
let inside = !uri.is_empty() && !uri.contains(':') && p.components().all(|c| matches!(c, std::path::Component::Normal(_)));
if !inside {
anyhow::bail!("asset path \"{uri}\" must be relative to the asset root, without '..'");
}
Ok(())
}
/// The scene must be rebuilt (THREERT_EDIT_LOG=1 says where it was decided).
fn mark_structural(c: &mut Changes, line: u32) {
if !c.structural && std::env::var("THREERT_EDIT_LOG").is_ok_and(|v| v == "1") {
eprintln!("world: structural at world.rs:{line}");
}
c.structural = true;
}
impl World {
// ------------------------------------------------------------------------------------------ engine API
pub fn set_geometry(&mut self, id: u32, g: Geometry) -> Result<()> {
if g.positions.len() % 3 != 0 || g.indices.len() % 3 != 0 {
return Err(anyhow!("geometry {id}: positions / indices must come in triples"));
}
let n = g.positions.len() / 3;
if g.normals.len() != n * 3 || g.uvs.len() != n * 2 || !(g.colors.is_empty() || g.colors.len() == n * 3) || g.indices.iter().any(|&i| i as usize >= n) {
return Err(anyhow!("geometry {id}: attribute sizes or indices out of range"));
}
if g.groups.iter().any(|&[start, count, _]| start % 3 != 0 || count % 3 != 0 || start as u64 + count as u64 > g.indices.len() as u64) {
return Err(anyhow!("geometry {id}: groups must be whole triangles within the indices"));
}
// (What the kernel's traversals are built from: docs/RUNTIME.md "What the kernel trusts".)
if g.positions.iter().any(|v| !v.is_finite()) {
return Err(anyhow!("geometry {id}: a position is not finite"));
}
// A geometry meshes use is replaced in place (their instances' mesh: live/edits.rs `edit_geometry`); one an
// instanced object uses rebuilds. A new id no object uses yet: nothing to look for (the scan over every object
// cost ~40 µs a geometry at 10 k objects).
let new = self.geometries.insert(id, Arc::new(g)).is_none();
if !self.changes.structural {
if !new && self.objects.values().any(|o| matches!(o.kind, Kind::Instanced { geometry, procedural: false, .. } if geometry == id)) {
mark_structural(&mut self.changes, line!());
} else {
self.changes.geometries.insert(id);
}
}
Ok(())
}
/// Procedural geometry from the scene code's boxes and data (checked here) or an asset file (its path checked here,
/// its contents when the scene is built).
pub fn set_proc_geometry(&mut self, id: u32, function: String, boxes: Vec<f32>, data: Vec<u32>) -> Result<()> {
let blob = crate::procasset::ProcBlob::new(boxes, data).map_err(|e| anyhow!("procedural geometry {id}: {e}"))?;
self.proc_geometries.insert(id, Arc::new(ProcGeometry { function, source: ProcSource::Inline(Arc::new(blob)) }));
self.changes.geometries.insert(id);
Ok(())
}
pub fn set_proc_asset(&mut self, id: u32, function: String, uri: String) -> Result<()> {
check_uri(&uri)?;
self.proc_geometries.insert(id, Arc::new(ProcGeometry { function, source: ProcSource::Asset(uri) }));
self.changes.geometries.insert(id);
Ok(())
}
/// Whether an object of kind `k` is a light that is an entry of the kernel's light table and nothing else: not a
/// rect light with a card (its card is triangles), not the atmosphere's sun (the sky's bake has it).
fn table_light(&self, id: u32, k: &Kind) -> bool {
let sun = matches!(self.environment.sky, desc::Sky::Atmosphere { sun: Some(s), .. } if s == id);
matches!(k, Kind::Light(l) if !sun && !matches!(l, desc::Light::Rect { visible: true, .. }))
}
/// Creates or replaces a texture. A new one is placed in the texture pages when a material first names it; one
/// that changed (its pixels, its wrap, its repeat or offset) has its materials made again, in place
/// (`Changes::textures`). The same texture set again changes nothing.
pub fn set_texture(&mut self, id: u32, t: Texture) -> Result<()> {
if let TextureSource::File(uri) = &t.source {
check_uri(uri)?;
}
match self.textures.get(&id) {
Some(old) if *old == t => return Ok(()),
Some(_) => {
self.changes.textures.insert(id);
}
None => {}
}
self.textures.insert(id, t);
Ok(())
}
/// Creates or replaces a material function. In place (`Changes::functions`): the scene's kernel is made with it
/// while the frames go on, and a material of it is drawn as it is without a function until then.
pub fn set_shader(&mut self, name: &str, code: String, helpers: String) {
if self.shaders.get(name).is_some_and(|(c, h)| *c == code && *h == helpers) {
return;
}
self.shaders.insert(name.to_string(), (code, helpers));
self.changes.functions = true;
}
pub fn set_material(&mut self, id: u32, m: desc::Material) {
match self.materials.get(&id) {
// Its parameters, its textures (a texture the scene has not is placed in the pages then) and its function,
// in place. `transparent` moves particles between the scene and the translucency pass, `vertexColors`
// decides which triangles carry colours: a rebuild.
Some(old) if old.transparent == m.transparent && old.vertex_colors == m.vertex_colors => {
self.changes.materials.insert(id);
}
// A new one that is not a particle's: in place, its textures and its function with it.
None if !m.transparent && !m.vertex_colors => {
self.changes.new_materials.insert(id);
}
_ => {
if std::env::var("THREERT_EDIT_LOG").is_ok_and(|v| v == "1") {
eprintln!("world: structural: material {id} is a particle's or has vertex colours, new or changed");
}
mark_structural(&mut self.changes, line!())
}
}
self.materials.insert(id, m);
}
/// Creates or replaces an object (its kind, parent, name; transform / visibility / power keep their values).
pub fn set_object(&mut self, id: u32, name: String, parent: Option<u32>, mut kind: Kind, cast_shadow: bool, movable: bool) -> Result<()> {
if let Kind::Model { uri, .. } = &kind {
check_uri(uri)?;
}
// Delta tracking steps by -ln(1 - u) / majorant (pathtrace.wgsl `media_track`, `media_tr`): an infinite one never
// steps, and the walk through the volume would not end.
if let Kind::Volume { majorant, .. } = &kind {
if !(majorant.is_finite() && *majorant > 0.0) {
return Err(anyhow!("object {name}: a volume's majorant must be a finite number > 0 (1/m), not {majorant}"));
}
}
// A mesh given another geometry is one the scene edits from now on (the build keeps room for that); it stays so.
if let (Some(Kind::Mesh { geometry: old, own_blas: was, .. }), Kind::Mesh { geometry, own_blas, .. }) = (self.objects.get(&id).map(|o| &o.kind), &mut kind) {
if *was || (*old != *geometry && !self.changes.created.contains(&id)) {
*own_blas = true;
}
}
// A mesh is placed in place: a new one, or one re-created with the same kind of object, parent and shadow flag
// (scene code swapping its geometry or materials). So is procedural geometry with no movable ancestor. Anything
// else rebuilds.
// (Movable as the build sees it: the object or any ancestor, `movable`.)
let static_parent = parent.is_none_or(|p| !self.objects.contains_key(&p) || !self.movable(p));
let mesh = matches!(kind, Kind::Mesh { .. });
// A new instanced mesh or model is placed in place too (ROADMAP § 6 step 5; live/edits.rs `edit_geometry`
// says when it cannot); changing one still rebuilds, but for an instanced mesh's materials (`rematerialed`).
let placed_new = !self.objects.contains_key(&id) && matches!(kind, Kind::Instanced { procedural: false, .. } | Kind::Model { .. });
let fresh = (edits_in_place(&kind) || placed_new)
&& (mesh || (!movable && static_parent))
&& match self.objects.get(&id) {
None => true,
Some(o) => (mesh || !self.movable(id)) && o.parent == parent && o.cast_shadow == cast_shadow && std::mem::discriminant(&o.kind) == std::mem::discriminant(&kind) && edits_in_place(&o.kind),
};
// An instanced mesh given other materials (the same geometry and capacity, the same parent and shadow flag): its
// copies' rows say them, in place (live/edits.rs `update_instanced`).
let rematerialed = match (self.objects.get(&id), &kind) {
(Some(o), Kind::Instanced { geometry, procedural: false, capacity, .. }) => {
matches!(&o.kind, Kind::Instanced { geometry: g, procedural: false, capacity: c, .. } if g == geometry && c == capacity) && o.parent == parent && o.cast_shadow == cast_shadow && (o.movable || !movable)
}
_ => false,
};
match &kind {
Kind::Instanced { capacity, .. } => {
if self.instanced.get(&id).is_some_and(|t| t.matrices.len() != *capacity as usize * 16) {
self.instanced.remove(&id);
}
}
_ => {
self.instanced.remove(&id);
}
}
// A light that is the light table's alone, new or set again as one under the same parent: its entry, in
// place. A new group draws nothing.
let relit = self.table_light(id, &kind) && self.objects.get(&id).is_none_or(|o| self.table_light(id, &o.kind) && o.parent == parent);
let grouped = matches!(kind, Kind::Group) && !self.objects.contains_key(&id);
// A camera, new or set again as one under the same parent: nothing is built from it; the view takes it if
// it is the scene's.
let filmed = matches!(kind, Kind::Camera(_)) && self.objects.get(&id).is_none_or(|o| matches!(o.kind, Kind::Camera(_)) && o.parent == parent);
// A volume, new or set again as one under the same parent: an entry of the media table, in place.
let misted = matches!(kind, Kind::Volume { .. }) && self.objects.get(&id).is_none_or(|o| matches!(o.kind, Kind::Volume { .. }) && o.parent == parent);
let was_parent = self.objects.get(&id).map(|o| o.parent);
if was_parent != Some(parent) {
if let Some(Some(p)) = was_parent {
if let Some(n) = self.kids.get_mut(&p) {
*n = n.saturating_sub(1);
}
}
if let Some(p) = parent {
*self.kids.entry(p).or_default() += 1;
}
}
let o = match self.take_object(id) {
Some(o) => Object { name, parent, kind, cast_shadow, movable: movable || o.movable, ..o },
None => Object { name, parent, kind, position: Vec3::ZERO, rotation: Quat::IDENTITY, scale: Vec3::ONE, visible: true, cast_shadow, power: 1.0, custom: [0.0; 4], movable, driven: false, sway: None, sway_rot: Quat::IDENTITY },
};
if let Kind::Model { uri, functions, .. } = &o.kind {
*self.models.entry(crate::scene::model_key(uri, functions)).or_default() += 1;
}
self.objects.insert(id, o);
if fresh {
self.changes.added.insert(id);
} else if rematerialed {
self.changes.instanced.insert(id);
} else if relit {
self.changes.lights.insert(id);
} else if grouped {
} else if filmed {
self.changes.camera |= self.settings.camera == Some(id);
} else if misted {
self.changes.media = true;
} else {
if std::env::var("THREERT_EDIT_LOG").is_ok_and(|v| v == "1") {
let o = &self.objects[&id];
eprintln!("world: structural: object {} ({:?}) set again or not placeable in place (movable {}, parent {:?})", o.name, std::mem::discriminant(&o.kind), o.movable, o.parent);
}
mark_structural(&mut self.changes, line!());
}
self.changes.created.insert(id);
Ok(())
}
pub fn set_transform(&mut self, id: u32, position: Vec3, rotation: Quat, scale: Vec3) -> Result<()> {
let o = self.objects.get_mut(&id).ok_or_else(|| anyhow!("unknown object {id}"))?;
if o.position == position && o.rotation == rotation && o.scale == scale {
return Ok(());
}
(o.position, o.rotation, o.scale) = (position, rotation, scale);
self.note_move(id);
Ok(())
}
/// A rigid body drives object `id` from now on: it is movable, built as an instance where it can be (a rebuild,
/// once; none for an object this batch adds in place, which is placed as one: live/edits.rs `edit_geometry`).
pub fn set_driven(&mut self, id: u32) -> Result<()> {
let o = self.objects.get_mut(&id).ok_or_else(|| anyhow!("unknown object {id}"))?;
if !o.driven {
o.driven = true;
o.movable = true;
if !self.changes.added.contains(&id) {
mark_structural(&mut self.changes, line!());
}
}
Ok(())
}
/// A rigid body's object at its new position and rotation (in its parent's space): `set_transform` with the scale
/// kept, and for a driven mesh without the questions a move of any object asks (a world of bodies moves thousands a
/// frame). False if there is no such object.
pub fn place_driven(&mut self, id: u32, position: Vec3, rotation: Quat) -> bool {
let Some(o) = self.objects.get_mut(&id) else { return false };
if o.position == position && o.rotation == rotation {
return true;
}
(o.position, o.rotation) = (position, rotation);
// (A driven mesh is movable and is not the camera: its move is a move. One added in this batch is placed where
// it is then, as `note_move` has it.)
if o.driven && matches!(o.kind, Kind::Mesh { .. }) {
if !self.changes.added.contains(&id) {
self.changes.moved.insert(id);
}
} else {
self.note_move(id);
}
true
}
/// Wind sway for an object (None: none, the object back at rest).
pub fn set_sway(&mut self, id: u32, sway: Option<Sway>) -> Result<()> {
let o = self.objects.get_mut(&id).ok_or_else(|| anyhow!("unknown object {id}"))?;
if o.sway == sway {
return Ok(());
}
o.sway = sway;
if sway.is_none() && o.sway_rot != Quat::IDENTITY {
o.sway_rot = Quat::IDENTITY;
self.note_move(id);
}
Ok(())
}
/// Leans every swaying object for scene time t (`Sway`). Returns whether any moved.
pub fn apply_sway(&mut self, t: f32) -> bool {
let ids: Vec<u32> = self.objects.iter().filter(|(_, o)| o.sway.is_some()).map(|(k, _)| *k).collect();
let mut moved = false;
for id in ids {
let (sway, parent, position) = {
let o = &self.objects[&id];
(o.sway.unwrap(), o.parent, o.position)
};
let phase = sway.phase.unwrap_or_else(|| sway_phase(parent.map_or(Mat4::IDENTITY, |p| self.world_matrix(p)).transform_point3(position)));
let r = sway.rotation(t, phase);
let o = self.objects.get_mut(&id).unwrap();
if o.sway_rot != r {
o.sway_rot = r;
self.note_move(id);
moved = true;
}
}
moved
}
/// Records that an object's transform changed: in place where it can be, otherwise a rebuild.
fn note_move(&mut self, id: u32) {
// An object added in place in this batch is placed where it is then (live/edits.rs `edit_geometry`).
if self.changes.added.contains(&id) {
return;
}
let is_camera = self.settings.camera == Some(id);
let o = &self.objects[&id];
let posed = matches!(o.kind, Kind::Model { animation: Some(_), .. });
let light = matches!(&o.kind, Kind::Light(l) if !matches!(l, desc::Light::Rect { visible: true, .. }));
let procedural = matches!(o.kind, Kind::Procedural { .. });
let instanced = matches!(o.kind, Kind::Instanced { .. });
let sun = matches!(self.environment.sky, desc::Sky::Atmosphere { sun: Some(s), .. } if s == id);
// In place: the camera (it only moves the view), movable objects and posed models (re-transformed / re-skinned,
// like UE Movable meshes), lights (their table entry). The sun rebakes the sky. (`leaf` scans every object: asked
// only where it decides, not for movable objects, which a frame moves by the thousand.)
if is_camera && self.leaf(id) {
self.changes.camera = true;
} else if self.movable(id) {
self.changes.moved.insert(id);
} else if procedural && self.leaf(id) {
// Procedural geometry is always an instance: its record and TLAS transform move (`LiveCore::move_procs`).
self.changes.moved.insert(id);
} else if instanced && self.leaf(id) {
// So are an instanced object's instances (`LiveCore::update_instanced`).
self.changes.instanced.insert(id);
} else if posed && self.leaf(id) {
// A posed model moves in place however it is drawn: an instance of its mesh by its transform, world-space
// triangles by being skinned again where it stands (the renderer's to tell: live/edits.rs `commit`).
self.changes.moved.insert(id);
} else if light && !sun && self.leaf(id) {
self.changes.lights.insert(id);
} else if sun && self.leaf(id) {
// The atmosphere's sun (time of day): its light rewritten and the sky re-baked in place (live/edits.rs `move_sun`).
self.changes.sun = true;
} else if matches!(o.kind, Kind::Camera(_)) && self.leaf(id) {
// (A camera that is not the scene's: nothing is built from it.)
} else if matches!(o.kind, Kind::Volume { .. }) && self.leaf(id) {
// A volume is its entry of the media table: placed again.
self.changes.media = true;
} else {
// Fixed geometry moved: from now on it is movable. A mesh, a still model, or a group, is its instances' to move
// (`Changes::started`); anything else rebuilds once, to set its triangles apart.
let held = matches!(o.kind, Kind::Mesh { .. } | Kind::Model { animation: None, .. } | Kind::Group) && !sun && !is_camera && !self.changes.created.contains(&id);
if !sun && !is_camera && !self.changes.created.contains(&id) {
let o = self.objects.get_mut(&id).unwrap();
o.movable = true;
if !held {
self.changes.promoted.push(o.name.clone());
}
}
if held {
self.changes.moved.insert(id);
self.changes.started.insert(id);
} else {
mark_structural(&mut self.changes, line!());
}
}
}
/// No object has it as its parent.
fn leaf(&self, id: u32) -> bool {
self.objects.values().all(|c| c.parent != Some(id))
}
/// Movable: the object or one of its ancestors is.
pub fn movable(&self, id: u32) -> bool {
let mut cur = Some(id);
while let Some(o) = cur.and_then(|i| self.objects.get(&i)) {
if o.movable {
return true;
}
cur = o.parent;
}
false
}
/// Parent -> children, built once for many subtree walks (`subtree_with`).
pub fn children(&self) -> std::collections::HashMap<u32, Vec<u32>> {
let mut c: std::collections::HashMap<u32, Vec<u32>> = std::collections::HashMap::new();
for (&i, o) in &self.objects {
if let Some(p) = o.parent {
c.entry(p).or_default().push(i);
}
}
c
}
/// `id` and everything under it, through a `children` index: O(subtree), where `subtree` scans every object (a
/// commit moving hundreds of nodes spent ~4.8 ms of a 36 ms frame there: docs/ROADMAP.md § 0, the crowd scene).
pub fn subtree_with(&self, id: u32, children: &std::collections::HashMap<u32, Vec<u32>>) -> Vec<u32> {
if !self.objects.contains_key(&id) {
return vec![];
}
let mut out = vec![id];
let mut i = 0;
while i < out.len() {
if let Some(k) = children.get(&out[i]) {
out.extend_from_slice(k);
}
i += 1;
}
out
}
/// The object and everything under it.
pub fn subtree(&self, id: u32) -> Vec<u32> {
let under = |mut i: u32| loop {
if i == id {
return true;
}
match self.objects.get(&i).and_then(|o| o.parent) {
Some(p) => i = p,
None => return false,
}
};
self.objects.keys().copied().filter(|&i| under(i)).collect()
}
pub fn set_visible(&mut self, id: u32, visible: bool) -> Result<()> {
let o = self.objects.get_mut(&id).ok_or_else(|| anyhow!("unknown object {id}"))?;
if o.visible != visible {
o.visible = visible;
// In place: what keeps its slot in the build while hidden (`hidden_built`; a mesh, as a hidden instance),
// and lights, which always have theirs (not a rect light's card, which is geometry, nor the sun, whose
// colour is the sky bake's).
let sun = matches!(self.environment.sky, desc::Sky::Atmosphere { sun: Some(s), .. } if s == id);
let o = &self.objects[&id];
let in_place = match &o.kind {
Kind::Particles { emitter_area, .. } => *emitter_area <= 0.0,
Kind::Volume { .. } => true,
// (A mesh's or a model's instances by their masks, a group's each: the renderer says whether it can.)
Kind::Mesh { .. } | Kind::Model { .. } | Kind::Group => true,
Kind::Light(l) => !sun && !matches!(l, desc::Light::Rect { visible: true, .. }),
_ => false,
};
if in_place {
self.changes.shown.insert(id);
} else {
mark_structural(&mut self.changes, line!());
}
}
Ok(())
}
/// Whether the build holds `id` though it is hidden: its own `visible` is false, everything above it is shown, and
/// it is a particle system that is not light-sampled (a rain curtain the weather turns off) or a volume (a pool's
/// idle fireball): shown again in place. (Volumes while the kernel has room for them: scene.rs `build`.)
pub fn hidden_built(&self, id: u32) -> bool {
let Some(o) = self.objects.get(&id) else { return false };
let kept = match o.kind {
Kind::Particles { emitter_area, .. } => emitter_area <= 0.0,
Kind::Volume { .. } => true,
_ => false,
};
!o.visible && kept && o.parent.is_none_or(|p| self.shown(p))
}
pub fn set_power(&mut self, id: u32, power: f32) -> Result<()> {
let o = self.objects.get_mut(&id).ok_or_else(|| anyhow!("unknown object {id}"))?;
if o.power != power {
o.power = power;
self.changes.powers.insert(id);
if matches!(o.kind, Kind::Instanced { .. }) {
self.changes.instanced.insert(id);
}
}
Ok(())
}
pub fn set_custom(&mut self, id: u32, v: [f32; 4]) -> Result<()> {
let o = self.objects.get_mut(&id).ok_or_else(|| anyhow!("unknown object {id}"))?;
if o.custom != v {
o.custom = v;
self.changes.customs.insert(id);
if matches!(o.kind, Kind::Instanced { .. }) {
self.changes.instanced.insert(id);
}
}
Ok(())
}
/// An instanced object's instances: `count` drawn, `matrices` (16 numbers each), optionally `colors` (3 each) and
/// per-instance data (4 each), all for its whole capacity; None keeps what it had. Game code is untrusted: sizes
/// are checked, colours and data made finite (colours >= 0); a matrix that is not finite or not invertible hides
/// its instance (live/edits.rs, scene.rs). Colours appearing or going rebuild (a kernel feature); the rest is in place.
pub fn set_instances(&mut self, id: u32, count: u32, matrices: Option<Vec<f32>>, colors: Option<Vec<f32>>, custom: Option<Vec<f32>>) -> Result<()> {
let o = self.objects.get(&id).ok_or_else(|| anyhow!("unknown object {id}"))?;
let Kind::Instanced { capacity, .. } = o.kind else { return Err(anyhow!("object {}: not an instanced mesh", o.name)) };
let cap = capacity as usize;
if count > capacity {
return Err(anyhow!("object {}: count {count} exceeds the {capacity} instances", o.name));
}
for (what, v, k) in [("matrices", &matrices, 16), ("colors", &colors, 3), ("customData", &custom, 4)] {
if v.as_ref().is_some_and(|v| v.len() != cap * k) {
return Err(anyhow!("object {}: {what} must be {k} numbers for each of the {capacity} instances", o.name));
}
}
let t = self.instanced.entry(id).or_default();
if matrices.is_none() && t.matrices.len() != cap * 16 {
t.matrices = Arc::new([Mat4::IDENTITY.to_cols_array()].repeat(cap).concat());
}
let colored = t.colors.is_some();
t.count = count;
if let Some(m) = matrices {
t.matrices = Arc::new(m);
}
if let Some(mut c) = colors {
for x in &mut c {
*x = if x.is_finite() { x.max(0.0) } else { 1.0 };
}
t.colors = Some(Arc::new(c));
}
if let Some(mut c) = custom {
for x in &mut c {
if !x.is_finite() {
*x = 0.0;
}
}
t.custom = Some(Arc::new(c));
}
if t.colors.is_some() != colored {
mark_structural(&mut self.changes, line!());
} else if !self.changes.created.contains(&id) {
self.changes.instanced.insert(id);
}
Ok(())
}
pub fn set_light(&mut self, id: u32, l: desc::Light) -> Result<()> {
// Its entry in the light table, in place: another kind of light or another shadow flag too (the table is
// sorted again). A rect light's card that comes or goes is triangles, and the atmosphere's sun is the sky's:
// those rebuild where their class changes.
let table = self.table_light(id, &Kind::Light(l.clone()));
let was = self.objects.get(&id).is_some_and(|o| self.table_light(id, &o.kind));
let o = self.objects.get_mut(&id).ok_or_else(|| anyhow!("unknown object {id}"))?;
match &o.kind {
// (A card of another size is another instance transform: the build's.)
Kind::Light(old) if (light_class(old) == light_class(&l) || (table && was)) && card_size(old) == card_size(&l) => {
self.changes.lights.insert(id);
}
_ => mark_structural(&mut self.changes, line!()),
}
o.kind = Kind::Light(l);
Ok(())
}
pub fn set_camera_desc(&mut self, id: u32, c: desc::Camera) -> Result<()> {
let active = self.settings.camera == Some(id);
let o = self.objects.get_mut(&id).ok_or_else(|| anyhow!("unknown object {id}"))?;
// In place, when it is the scene's camera: a field of view is the view's (as a camera's move: the view takes
// it), a depth of field and an exposure are the post passes' (and the kernel's clamp). Nothing is built from a
// camera that is not the scene's, nor from near and far; a camera made of another kind of object is a new object.
let (fov, rest) = match &o.kind {
Kind::Camera(old) => (old.fov != c.fov, old.dof != c.dof || old.exposure != c.exposure),
_ => {
mark_structural(&mut self.changes, line!());
(false, false)
}
};
o.kind = Kind::Camera(c);
self.changes.camera |= active && fov;
self.changes.view |= active && rest;
Ok(())
}
/// Poses a model (clip sampled at a time); a parameter change, applied by re-skinning its triangles.
pub fn set_animation(&mut self, id: u32, a: Option<desc::Animation>) -> Result<()> {
let o = self.objects.get_mut(&id).ok_or_else(|| anyhow!("unknown object {id}"))?;
let Kind::Model { animation, .. } = &mut o.kind else { return Err(anyhow!("object {id} is not a model")) };
if *animation != a {
*animation = a;
self.changes.poses.insert(id);
}
Ok(())
}
/// Removes an object and its descendants. Returns their ids (those it had: the bodies that drove them go too).
/// A geometry (triangles or procedural) no object uses any more, let go (the voxel engine's, when it draws a part
/// again in new objects: the old objects' geometries would otherwise stay for good). One an object still uses is
/// kept. Returns whether it went.
pub fn drop_geometry(&mut self, id: u32) -> bool {
let used = self.objects.values().any(|o| match &o.kind {
Kind::Mesh { geometry, .. } | Kind::Procedural { geometry, .. } | Kind::Instanced { geometry, .. } => *geometry == id,
_ => false,
});
if used {
return false;
}
self.changes.geometries.remove(&id);
self.geometries.remove(&id).is_some() | self.proc_geometries.remove(&id).is_some()
}
/// Takes object `id` out of `objects`, counting it out of `models` (a file's last model: `Changes::gone_models`).
fn take_object(&mut self, id: u32) -> Option<Object> {
let o = self.objects.remove(&id)?;
if let Kind::Model { uri, functions, .. } = &o.kind {
let key = crate::scene::model_key(uri, functions);
if let Some(n) = self.models.get_mut(&key) {
*n = n.saturating_sub(1);
if *n == 0 {
self.models.remove(&key);
self.changes.gone_models.insert(key);
}
}
}
Some(o)
}
pub fn remove(&mut self, id: u32) -> Vec<u32> {
let mut doomed = vec![id];
let mut k = 0;
while k < doomed.len() {
let p = doomed[k];
if self.kids.get(&p).is_some_and(|&n| n > 0) {
doomed.extend(self.objects.iter().filter(|(_, o)| o.parent == Some(p)).map(|(i, _)| *i));
}
k += 1;
}
// (the parents of what goes have one child fewer; what goes has none)
for d in &doomed {
if let Some(Some(p)) = self.objects.get(d).map(|o| o.parent) {
if let Some(n) = self.kids.get_mut(&p) {
*n = n.saturating_sub(1);
}
}
self.kids.remove(d);
}
// A mesh, procedural geometry, or a group of those, is removed in place, and so is a lone instanced mesh or
// model (or never added, if it came in this batch; live/edits.rs `edit_geometry` rebuilds for what it cannot
// take out).
// A light of the light table alone: its entry goes, in place. A group draws nothing.
let alone = |o: &Object| doomed.len() == 1 && matches!(o.kind, Kind::Instanced { procedural: false, .. } | Kind::Model { .. });
// (So does a camera that is not the scene's.)
let lit: Vec<bool> = doomed.iter().map(|d| self.objects.get(d).is_some_and(|o| self.table_light(*d, &o.kind))).collect();
// (And a volume: its entry of the media table goes.)
let spare = |d: &u32, o: &Object| matches!(o.kind, Kind::Camera(_)) && self.settings.camera != Some(*d);
let mist = |o: &Object| matches!(o.kind, Kind::Volume { .. });
if doomed.iter().zip(&lit).all(|(d, lit)| self.objects.get(d).is_some_and(|o| edits_in_place(&o.kind) || alone(o) || matches!(o.kind, Kind::Group) || *lit || spare(d, o) || mist(o))) {
for (d, lit) in doomed.iter().zip(&lit) {
self.instanced.remove(d);
if *lit {
self.take_object(*d);
self.changes.lights.insert(*d);
} else if self.objects.get(d).is_some_and(mist) {
self.take_object(*d);
self.changes.media = true;
} else if self.take_object(*d).is_some_and(|o| !matches!(o.kind, Kind::Group | Kind::Camera(_))) && !self.changes.added.remove(d) {
self.changes.removed.insert(*d);
}
// What else this batch changed of it goes with it (a pose, a move, its visibility: there is nothing
// left to pose, and the renderer would rebuild for an object it cannot find).
let c = &mut self.changes;
for set in [&mut c.poses, &mut c.moved, &mut c.started, &mut c.shown, &mut c.powers, &mut c.customs, &mut c.instanced] {
set.remove(d);
}
}
return doomed;
}
if std::env::var("THREERT_EDIT_LOG").is_ok_and(|v| v == "1") {
eprintln!("world: structural: removal of {} objects not in place ({:?})", doomed.len(), doomed.iter().take(3).filter_map(|d| self.objects.get(d)).map(|o| (o.name.clone(), std::mem::discriminant(&o.kind))).collect::<Vec<_>>());
}
for &d in &doomed {
self.instanced.remove(&d);
if self.take_object(d).is_some() {
mark_structural(&mut self.changes, line!());
}
}
doomed
}
pub fn set_environment(&mut self, e: desc::Environment) {
// Fog appearing, turning volumetric or going, and a background appearing or going, are kernel features: another
// variant of the kernel, not another scene. Another sky is another environment map.
// (A planet's viewer altitude alone re-bakes in place: live/edits.rs `move_altitude`.)
let same_but_altitude = match (&self.environment.sky, &e.sky) {
(desc::Sky::Atmosphere { altitude: Some(_), .. }, desc::Sky::Atmosphere { altitude: Some(now), .. }) => {
let mut was = self.environment.sky.clone();
if let desc::Sky::Atmosphere { altitude, .. } = &mut was {
*altitude = Some(*now);
}
was == e.sky
}
_ => false,
};
if same_but_altitude {
self.changes.altitude |= self.environment.sky != e.sky;
} else {
self.changes.sky |= self.environment.sky != e.sky;
}
self.changes.environment = true;
self.environment = e;
}
pub fn set_settings(&mut self, s: Settings) {
let old = &self.settings;
// (The size and the clock are an offline render's: a live view has its host's size and its own clock.)
if old.preset != s.preset || old.overrides != s.overrides || old.name != s.name {
self.changes.settings = true;
}
if old.camera != s.camera {
// Another camera: the view takes it (its place and lens, its depth of field and its exposure).
self.changes.camera = true;
}
self.settings = s;
}
pub fn take_changes(&mut self) -> Changes {
std::mem::take(&mut self.changes)
}
// ------------------------------------------------------------------------------------------ queries
/// The scene's camera (`Settings::camera`), when it names one.
pub fn scene_camera(&self) -> Option<&desc::Camera> {
match self.settings.camera.and_then(|id| self.objects.get(&id)).map(|o| &o.kind) {
Some(Kind::Camera(c)) => Some(c),
_ => None,
}
}
/// Object `id`'s world matrix: its transform and its parents'. One that is not finite (a NaN or infinite position,
/// rotation or scale anywhere up the chain, as a script may set) places the object at a point, scale 1e-6 at its
/// translation where that is finite, as `scene::instance_world` places a hidden instance: what it draws is not
/// seen, and nothing built from it (the acceleration structures, the software traversal's trees, the light tree)
/// is given a number that is not finite (docs/RUNTIME.md "What the kernel trusts").
pub fn world_matrix(&self, id: u32) -> Mat4 {
let m = self.world_matrix_as_set(id);
if m.is_finite() {
return m;
}
let at = if m.w_axis.is_finite() { m.w_axis.truncate() } else { Vec3::ZERO };
Mat4::from_scale_rotation_translation(Vec3::splat(1e-6), Quat::IDENTITY, at)
}
/// The product of the transforms as they were set, finite or not.
fn world_matrix_as_set(&self, id: u32) -> Mat4 {
let mut m = Mat4::IDENTITY;
let mut cur = Some(id);
let mut guard = 0;
while let Some(i) = cur {
let Some(o) = self.objects.get(&i) else { break };
m = o.local() * m;
cur = o.parent;
guard += 1;
if guard > 1024 {
break;
}
}
m
}
/// Ids in an order where parents come before children.
pub fn ordered(&self) -> Vec<u32> {
let mut out = Vec::with_capacity(self.objects.len());
let mut placed: HashSet<u32> = HashSet::new();
let mut rest: Vec<u32> = self.objects.keys().copied().collect();
while !rest.is_empty() {
let before = rest.len();
rest.retain(|i| {
let ready = self.objects[i].parent.is_none_or(|p| placed.contains(&p) || !self.objects.contains_key(&p));
if ready {
placed.insert(*i);
out.push(*i);
}
!ready
});
if rest.len() == before {
out.append(&mut rest);
}
}
out
}
pub fn set_volume_fn(&mut self, name: &str, code: String, helpers: String) {
if self.volume_fns.get(name).is_some_and(|(c, h)| *c == code && *h == helpers) {
return;
}
self.volume_fns.insert(name.to_string(), (code, helpers));
// (The kernel's code, in place: as a material function's, `set_shader`.)
self.changes.volume_functions = true;
}
pub fn set_grid_program(&mut self, name: &str, code: String, helpers: String) {
if self.grid_programs.get(name).is_some_and(|(c, h)| *c == code && *h == helpers) {
return;
}
self.grid_programs.insert(name.to_string(), (code, helpers));
// (The grids' pass, in place: made again with the media table.)
self.changes.media = true;
}
/// Creates or replaces a density grid. New data for a grid of the same size and program is uploaded in place; a
/// new grid, another size or another program has the scene's grids made again with the media table.
pub fn set_grid(&mut self, id: u32, dims: [u32; 3], channels: u32, data: Option<&[f32]>, program: Option<(String, Vec<f32>)>) -> Result<()> {
let cells = dims.iter().map(|&d| d as u64).product::<u64>();
if dims.iter().any(|&d| d == 0 || d > GRID_MAX_AXIS) || cells > GRID_MAX_CELLS {
return Err(anyhow!("density grid {id}: size {dims:?} (1 to {GRID_MAX_AXIS} cells an axis, at most {GRID_MAX_CELLS} in all)"));
}
if channels != 1 && channels != 4 {
return Err(anyhow!("density grid {id}: {channels} channels (1 or 4)"));
}
let data = match data {
Some(d) => {
if d.len() as u64 != cells * channels as u64 || d.iter().any(|v| !v.is_finite()) {
return Err(anyhow!("density grid {id}: data must be {} finite numbers ({channels} a cell)", cells * channels as u64));
}
Some(Arc::new(if channels == 4 { d.to_vec() } else { d.iter().flat_map(|&v| [v, 0.0, 0.0, 0.0]).collect() }))
}
None => None,
};
// The world's grids hold at most twice a scene's cells: over that, the ones no volume names any more go (but
// this batch's, whose volumes may follow), and if that is not enough the grid is refused.
let others = |w: &World| w.grids.iter().filter(|(k, _)| **k != id).map(|(_, g)| g.dims.iter().map(|&d| d as u64).product::<u64>()).sum::<u64>();
if others(self) + cells > 2 * GRID_MAX_SCENE_CELLS {
let used: HashSet<u32> = self.objects.values().filter_map(|o| if let Kind::Volume { grid: Some(g), .. } = &o.kind { Some(*g) } else { None }).collect();
let fresh = self.changes.grids_new.clone();
self.grids.retain(|k, _| used.contains(k) || fresh.contains(k));
if others(self) + cells > 2 * GRID_MAX_SCENE_CELLS {
return Err(anyhow!("density grid {id}: the world's density grids exceed {} cells", 2 * GRID_MAX_SCENE_CELLS));
}
}
self.changes.grids_new.insert(id);
let same = self.grids.get(&id).is_some_and(|g| g.dims == dims && g.program == program);
if same {
if data.is_some() {
self.grid_dirty.insert(id);
}
} else {
self.changes.media = true;
}
// (No data with a same grid: its contents stay, e.g. a simulated grid whose parameters were sent again.)
let keep = if same && data.is_none() { self.grids.get(&id).and_then(|g| g.data.clone()) } else { None };
// The same grid still, for what its program has simulated: its size and its program's name (with new
// parameters the smoke stays).
let made = match self.grids.get(&id) {
Some(g) if g.dims == dims && g.program.as_ref().map(|p| &p.0) == program.as_ref().map(|p| &p.0) => g.made,
_ => {
self.grids_made = self.grids_made.wrapping_add(1);
self.grids_made
}
};
self.grids.insert(id, DensityGrid { dims, data: data.or(keep), program, made });
Ok(())
}
/// Sources the game gives a volume's grid program (12 floats each), taken by the live view's next frame.
pub fn add_grid_sources(&mut self, id: u32, data: &[f32]) -> Result<()> {
if !matches!(self.objects.get(&id).map(|o| &o.kind), Some(Kind::Volume { grid: Some(_), .. })) {
return Err(anyhow!("grid sources: object {id} is not a volume with a density grid"));
}
if data.len() % 12 != 0 || data.iter().any(|v| !v.is_finite()) {
return Err(anyhow!("grid sources: 12 finite floats a source"));
}
let pending = self.grid_sources.entry(id).or_default();
let room = (GRID_MAX_SOURCES * 12).saturating_sub(pending.len());
pending.extend_from_slice(&data[..data.len().min(room)]);
Ok(())
}
pub fn set_geometry_fn(&mut self, name: &str, code: String, helpers: String) {
if self.geometry_fns.get(name).is_some_and(|(c, h)| *c == code && *h == helpers) {
return;
}
self.geometry_fns.insert(name.to_string(), (code, helpers));
mark_structural(&mut self.changes, line!());
}
pub fn set_particle_program(&mut self, name: &str, emit: String, update: String, helpers: String) {
let v = (emit, update, helpers);
if self.particle_programs.get(name) == Some(&v) {
return;
}
self.particle_programs.insert(name.to_string(), v);
mark_structural(&mut self.changes, line!());
}
/// Particles the game spawns into a `GpuParticles` node (8 floats each), taken by the live view's next frame.
pub fn spawn_particles(&mut self, id: u32, data: &[f32]) -> Result<()> {
if !matches!(self.objects.get(&id).map(|o| &o.kind), Some(Kind::GpuParticles { .. })) {
return Err(anyhow!("spawn: object {id} is not a GpuParticles node"));
}
if data.len() % 8 != 0 || data.iter().any(|v| !v.is_finite()) {
return Err(anyhow!("spawn: 8 finite floats a particle"));
}
// At most what one frame takes (gpu.rs MAX_SPAWNS) waits per node: the rest is dropped.
let pending = self.particle_spawns.entry(id).or_default();
let room = (crate::gpu::MAX_SPAWNS * 8).saturating_sub(pending.len());
pending.extend_from_slice(&data[..data.len().min(room)]);
Ok(())
}
pub fn set_particle_fn(&mut self, name: &str, code: String, helpers: String) {
if self.particle_fns.get(name).is_some_and(|(c, h)| *c == code && *h == helpers) {
return;
}
self.particle_fns.insert(name.to_string(), (code, helpers));
mark_structural(&mut self.changes, line!());
}
/// Objects drawn: visible themselves and all their ancestors.
/// Files the scene reads from the asset root: models and file textures (uris, sorted).
pub fn files(&self) -> Vec<String> {
let models = self.objects.values().filter_map(|o| match &o.kind {
Kind::Model { uri, .. } => Some(uri.clone()),
_ => None,
});
let textures = self.textures.values().filter_map(|t| match &t.source {
TextureSource::File(uri) => Some(uri.clone()),
TextureSource::Encoded(_) | TextureSource::Pixels { .. } | TextureSource::Stream { .. } => None,
});
let procs = self.proc_geometries.values().filter_map(|g| match &g.source {
ProcSource::Asset(uri) => Some(uri.clone()),
ProcSource::Inline(_) => None,
});
let set: std::collections::BTreeSet<String> = models.chain(textures).chain(procs).collect();
set.into_iter().collect()
}
pub fn shown(&self, id: u32) -> bool {
let mut cur = Some(id);
while let Some(i) = cur {
match self.objects.get(&i) {
Some(o) if o.visible => cur = o.parent,
Some(_) => return false,
None => return true,
}
}
true
}
}
#[cfg(test)]
mod tests {
/// What the kernel's traversals are built from is finite where it enters (docs/RUNTIME.md "What the kernel
/// trusts"): a geometry's positions and a volume's majorant are checked; a transform is kept as set, and an object
/// whose world matrix is not finite (its own or a parent's) is placed at a point, at its translation where that is
/// finite, as a hidden instance is.
#[test]
fn what_the_kernel_walks_is_finite_where_it_enters() {
let mut w = World::default();
let tri = |x: f32| Geometry { positions: vec![x, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0], normals: vec![0.0; 9], uvs: vec![0.0; 6], indices: vec![0, 1, 2], groups: vec![], colors: vec![] };
assert!(w.set_geometry(1, tri(f32::NAN)).unwrap_err().to_string().contains("not finite"));
assert!(w.set_geometry(1, tri(f32::INFINITY)).is_err());
w.set_geometry(1, tri(0.0)).unwrap();
let volume = |majorant: f32| Kind::Volume { function: "f".into(), params: vec![], shape: 0, majorant, g: 0.0, homogeneous: false, animated: false, grid: None };
for bad in [f32::INFINITY, f32::NAN, 0.0, -1.0] {
assert!(w.set_object(2, "fog".into(), None, volume(bad), false, false).is_err(), "majorant {bad}");
}
w.set_object(2, "fog".into(), None, volume(0.5), false, false).unwrap();
w.set_object(3, "parent".into(), None, Kind::Group, false, true).unwrap();
w.set_object(4, "child".into(), Some(3), Kind::Group, false, true).unwrap();
w.set_transform(4, Vec3::new(1.0, 2.0, 3.0), Quat::IDENTITY, Vec3::ONE).unwrap();
assert_eq!(w.world_matrix(4).w_axis.truncate(), Vec3::new(1.0, 2.0, 3.0));
w.set_transform(3, Vec3::ZERO, Quat::IDENTITY, Vec3::new(f32::NAN, 1.0, 1.0)).unwrap();
let m = w.world_matrix(4);
assert!(m.is_finite() && m.x_axis.length() < 1e-5, "a NaN scale up the chain: a point ({m})");
w.set_transform(4, Vec3::new(f32::INFINITY, 0.0, 0.0), Quat::IDENTITY, Vec3::ONE).unwrap();
assert!(w.world_matrix(4).is_finite());
assert_eq!(w.objects[&4].position.x, f32::INFINITY, "the transform kept as set");
}
/// What a batch changed of an object goes with the object when the same batch removes it in place: its pose, its
/// move, its visibility, its power. (The renderer finds nothing to pose, and would rebuild.)
#[test]
fn an_object_removed_takes_its_other_changes_with_it() {
let mut w = World::default();
let pose = |time| Some(desc::Animation { clip: "bend".into(), time, r#loop: true, nodes: Default::default() });
for id in [1, 2] {
w.set_object(id, format!("m{id}"), None, Kind::Model { uri: "tests/render/data/arm.glb".into(), nodes: None, animation: pose(0.0), functions: vec![] }, true, true).unwrap();
}
w.take_changes();
for id in [1, 2] {
w.set_animation(id, pose(0.5)).unwrap();
w.set_transform(id, Vec3::new(1.0, 0.0, 0.0), Quat::IDENTITY, Vec3::ONE).unwrap();
w.set_visible(id, false).unwrap();
}
w.remove(1);
let c = w.take_changes();
assert!(!c.structural && c.removed.contains(&1), "removed in place");
for (what, set) in [("poses", &c.poses), ("moved", &c.moved), ("shown", &c.shown), ("started", &c.started), ("powers", &c.powers), ("customs", &c.customs), ("instanced", &c.instanced)] {
assert!(!set.contains(&1), "{what}: nothing of the object removed");
}
assert!(c.poses.contains(&2) && c.moved.contains(&2) && c.shown.contains(&2), "the other's changes are kept");
}
/// Density grids: sizes and data are checked; a new grid, another size, another program or other parameters are
/// the media table's change (the grids are made again in place), new data for the same grid is uploaded in place
/// (a grid sent again without data keeps what it had); sources go only to volumes with a grid, 12 finite floats
/// each, at most GRID_MAX_SOURCES pending.
#[test]
fn density_grids_are_checked_and_updated_in_place() {
let mut w = World::default();
assert!(w.set_grid(1, [0, 4, 4], 1, None, None).is_err());
assert!(w.set_grid(1, [513, 4, 4], 1, None, None).is_err());
assert!(w.set_grid(1, [512, 512, 64], 1, None, None).is_err(), "more cells than GRID_MAX_CELLS");
assert!(w.set_grid(1, [2, 2, 2], 3, None, None).is_err());
assert!(w.set_grid(1, [2, 2, 2], 1, Some(&[1.0; 7]), None).is_err());
assert!(w.set_grid(1, [2, 2, 2], 1, Some(&[f32::NAN; 8]), None).is_err());
assert!(w.grids.is_empty());
w.take_changes();
w.set_grid(1, [2, 2, 2], 1, Some(&[0.5; 8]), None).unwrap();
let media = |w: &mut World| {
let c = w.take_changes();
assert!(!c.structural, "no rebuild");
c.media
};
assert!(media(&mut w), "a new grid");
assert_eq!(w.grids[&1].data.as_ref().unwrap()[..5], [0.5, 0.0, 0.0, 0.0, 0.5], "one channel: A's first");
w.set_grid(1, [2, 2, 2], 4, Some(&[2.0; 32]), None).unwrap();
assert!(!media(&mut w) && w.grid_dirty.contains(&1), "new data: uploaded in place");
w.grid_dirty.clear();
w.set_grid(1, [2, 2, 2], 1, None, None).unwrap();
assert!(!media(&mut w) && w.grid_dirty.is_empty() && w.grids[&1].data.as_ref().unwrap()[1] == 2.0, "no data: kept");
w.set_grid(1, [2, 2, 2], 1, None, Some(("p".into(), vec![1.0]))).unwrap();
assert!(media(&mut w), "another program");
let made = w.grids[&1].made;
w.set_grid(1, [2, 2, 2], 1, None, Some(("p".into(), vec![2.0]))).unwrap();
assert!(media(&mut w) && w.grids[&1].made == made, "new parameters; it is the same grid still (what it simulated stays)");
w.set_grid(1, [2, 2, 2], 1, None, Some(("q".into(), vec![2.0]))).unwrap();
assert!(w.grids[&1].made != made, "another program: another grid");
let made = w.grids[&1].made;
w.set_grid(1, [2, 2, 4], 1, None, Some(("q".into(), vec![2.0]))).unwrap();
assert!(media(&mut w) && w.grids[&1].made != made, "another size");
w.set_grid_program("q", "s.a.x = 1.0;".into(), String::new());
assert!(media(&mut w), "a grid program's code");
w.set_grid_program("q", "s.a.x = 1.0;".into(), String::new());
assert!(!media(&mut w), "the same code again");
// Sources.
let volume = |grid| Kind::Volume { function: "f".into(), params: vec![], shape: 0, majorant: 1.0, g: 0.0, homogeneous: false, animated: false, grid };
w.set_object(5, "plain".into(), None, volume(None), false, false).unwrap();
w.set_object(6, "smoke".into(), None, volume(Some(1)), false, false).unwrap();
assert!(w.add_grid_sources(5, &[0.0; 12]).is_err());
assert!(w.add_grid_sources(6, &[0.0; 11]).is_err());
assert!(w.add_grid_sources(6, &[f32::INFINITY; 12]).is_err());
w.add_grid_sources(6, &[1.0; 24]).unwrap();
w.add_grid_sources(6, &vec![1.0; 12 * 200]).unwrap();
assert_eq!(w.grid_sources[&6].len(), GRID_MAX_SOURCES * 12);
// The world's budget: grids no volume names are dropped when it is passed (not this batch's); grids in use stay,
// and past the budget a new one is refused.
w.take_changes();
for id in 10..13 {
w.set_grid(id, [256, 256, 128], 1, None, None).unwrap();
}
assert_eq!(w.grids.len(), 4, "grid 1 and this batch's three (25.2 M cells of the budget's 33.5 M)");
assert!(w.set_grid(13, [256, 256, 128], 1, None, None).is_err(), "this batch's are kept: no room for a fourth");
w.take_changes();
w.set_grid(13, [256, 256, 128], 1, None, None).unwrap();
assert!(w.grids.contains_key(&1) && w.grids.contains_key(&13) && !w.grids.contains_key(&10), "unused ones went, grid 1 (in use) stayed");
}
/// Hiding by an object's own `visible`: in place for a volume, a light without a card and a particle system that
/// is not light-sampled (`Changes::shown`; hidden, the build keeps a volume: `hidden_built`); a rebuild for a mesh,
/// a rect light with its card, the sun.
#[test]
fn hiding_a_volume_or_a_light_is_not_structural() {
let mut w = World::default();
let light = |json: serde_json::Value| Kind::Light(serde_json::from_value(json).unwrap());
let volume = Kind::Volume { function: "f".into(), params: vec![], shape: 1, majorant: 1.0, g: 0.0, homogeneous: false, animated: true, grid: None };
w.set_object(1, "fire".into(), None, volume, false, false).unwrap();
w.set_object(2, "lamp".into(), None, light(serde_json::json!({ "type": "point", "color": [1, 1, 1], "castShadow": true, "intensity": 100, "radius": 0.01, "range": 0 })), false, false).unwrap();
w.set_object(3, "card".into(), None, light(serde_json::json!({ "type": "rect", "color": [1, 1, 1], "castShadow": true, "intensity": 100, "width": 1, "height": 1, "range": 0 })), false, false).unwrap();
w.set_object(4, "panel".into(), None, light(serde_json::json!({ "type": "rect", "color": [1, 1, 1], "castShadow": true, "intensity": 100, "width": 1, "height": 1, "range": 0, "visible": false })), false, false).unwrap();
w.set_object(5, "group".into(), None, Kind::Group, false, false).unwrap();
assert!(w.take_changes().structural, "the first commit builds the scene");
for id in [1, 2, 4] {
w.set_visible(id, false).unwrap();
let c = w.take_changes();
assert!(!c.structural && c.shown.contains(&id) && c.any(), "{id}: hidden in place");
assert!(!w.shown(id));
w.set_visible(id, false).unwrap();
assert!(!w.take_changes().any(), "{id}: no change");
w.set_visible(id, true).unwrap();
let c = w.take_changes();
assert!(!c.structural && c.shown.contains(&id), "{id}: shown in place");
}
w.set_visible(1, false).unwrap();
assert!(w.hidden_built(1) && !w.hidden_built(2), "a hidden volume keeps its place in the build; a light always has one");
// A card's colour is its material's, in place; its size is its instance's transform, the build's. A rect light
// without a card is its table entry whatever changes.
let rect = |w: f32, color: f32, visible: bool| serde_json::from_value::<desc::Light>(serde_json::json!({ "type": "rect", "color": [color, 1, 1], "castShadow": true, "intensity": 100, "width": w, "height": 1, "range": 0, "visible": visible })).unwrap();
w.set_light(3, rect(1.0, 0.5, true)).unwrap();
let c = w.take_changes();
assert!(!c.structural && c.lights.contains(&3), "a card of another colour: in place");
w.set_light(3, rect(2.0, 0.5, true)).unwrap();
assert!(w.take_changes().structural, "a card of another size: the build's");
w.set_light(4, rect(2.0, 0.5, false)).unwrap();
let c = w.take_changes();
assert!(!c.structural && c.lights.contains(&4), "a rect light without a card, of another size: in place");
w.set_visible(3, false).unwrap();
assert!(w.take_changes().structural, "a rect light's card is geometry");
// (A group, as a mesh: the renderer hides its meshes' instances, or says it cannot.)
w.set_visible(5, false).unwrap();
let c = w.take_changes();
assert!(!c.structural && c.shown.contains(&5), "a group: for the renderer to hide in place");
let inner = Kind::Volume { function: "f".into(), params: vec![], shape: 0, majorant: 1.0, g: 0.0, homogeneous: false, animated: false, grid: None };
w.set_object(6, "inner".into(), Some(5), inner, false, false).unwrap();
w.set_visible(6, false).unwrap();
assert!(!w.hidden_built(6), "under a hidden parent nothing is kept");
}
/// Wind sway: the object leans downwind about its origin by Sway::angle, the phase from its world position when it
/// has none; set_sway(None) puts it back at rest.
#[test]
fn sway_leans_objects_downwind_about_their_origin() {
let mut w = World::default();
w.set_object(1, "plant".into(), None, Kind::Group, true, true).unwrap();
w.set_transform(1, Vec3::new(2.0, 0.0, 3.0), Quat::IDENTITY, Vec3::ONE).unwrap();
w.take_changes();
let s = Sway { direction: 0.0, strength: 0.6, frequency: 0.5, stiffness: 0.0, phase: None };
w.set_sway(1, Some(s)).unwrap();
assert!(w.apply_sway(0.5));
let c = w.take_changes();
assert!(c.moved.contains(&1) && !c.structural, "a movable object moves in place");
let a = s.angle(0.5, sway_phase(Vec3::new(2.0, 0.0, 3.0)));
let top = w.world_matrix(1).transform_point3(Vec3::Y);
assert!((top - Vec3::new(2.0 + a.sin(), a.cos(), 3.0)).length() < 1e-5, "leans toward +x by the angle: {top}");
assert!(!w.apply_sway(0.5), "same time: nothing moves");
w.set_sway(1, None).unwrap();
assert!((w.world_matrix(1).transform_point3(Vec3::Y) - Vec3::new(2.0, 1.0, 3.0)).length() < 1e-6, "back at rest");
}
/// Procedural geometry: bad boxes are refused; a procedural object moves in place (an instance) from its first move,
/// where fixed triangles rebuild once.
#[test]
fn procedural_objects_move_in_place() {
let mut w = World::default();
assert!(w.set_proc_geometry(1, "f".into(), vec![0.0; 5], vec![]).is_err());
assert!(w.set_proc_geometry(1, "f".into(), vec![1.0, 0.0, 0.0, 0.0, 1.0, 1.0], vec![]).is_err(), "min > max");
assert!(w.set_proc_geometry(1, "f".into(), vec![f32::NAN, 0.0, 0.0, 1.0, 1.0, 1.0], vec![]).is_err());
assert!(w.set_proc_asset(3, "f".into(), "../outside.bin".into()).is_err(), "asset paths stay inside the asset root");
w.set_proc_asset(4, "f".into(), "voxel/level.tpg".into()).unwrap();
assert_eq!(w.files(), vec!["voxel/level.tpg".to_string()]);
w.set_proc_geometry(1, "f".into(), vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0], vec![7]).unwrap();
w.set_object(2, "p".into(), None, Kind::Procedural { geometry: 1, materials: vec![3] }, true, false).unwrap();
w.take_changes();
w.set_transform(2, Vec3::X, Quat::IDENTITY, Vec3::ONE).unwrap();
let c = w.take_changes();
assert!(c.moved.contains(&2) && !c.structural && c.promoted.is_empty());
}
use super::*;
fn mat() -> desc::Material {
serde_json::from_value(serde_json::json!({ "name": "m", "color": [1, 1, 1], "opacity": 1, "metalness": 0, "roughness": 0.5, "emissive": [0, 0, 0], "emissiveIntensity": 1, "doubleSided": false })).unwrap()
}
/// What a game adds while it runs (ROADMAP § 6 step 7): a material without textures is added in place; a mesh a
/// rigid body will drive is placed in place and is movable from the start; its body's moves are moves in place.
#[test]
fn driven_objects_and_new_materials_in_place() {
let tri = || Geometry { positions: vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0], normals: vec![0.0; 9], uvs: vec![0.0; 6], indices: vec![0, 1, 2], groups: vec![], colors: vec![] };
let mesh = |material, own_blas| Kind::Mesh { geometry: 1, material, own_blas, materials: vec![] };
let mut w = World::default();
w.set_material(1, mat());
w.set_geometry(1, tri()).unwrap();
w.set_object(1, "still".into(), None, mesh(1, false), true, false).unwrap();
assert!(w.take_changes().structural, "the first commit builds the scene");
w.set_material(2, mat());
let c = w.take_changes();
assert!(!c.structural && c.any() && c.new_materials.contains(&2), "a new material of plain parameters: in place");
let mut textured = mat();
textured.map = Some(9);
w.set_material(3, textured.clone());
let c = w.take_changes();
assert!(!c.structural && c.new_materials.contains(&3), "one with a texture: in place too (the texture is placed in the pages)");
// A new one that is a particle's (`transparent`), or has vertex colours: a rebuild.
for (k, what) in ["transparent", "vertex colours"].iter().enumerate() {
let mut m = mat();
(m.transparent, m.vertex_colors) = (k == 0, k == 1);
w.set_material(20 + k as u32, m);
assert!(w.take_changes().structural, "a new material with {what}: a rebuild");
}
// (The engine's `object` call gives a mesh a body will drive its own BLAS.)
w.set_object(2, "box".into(), None, mesh(2, true), true, false).unwrap();
w.set_driven(2).unwrap();
w.set_transform(2, Vec3::Y, Quat::IDENTITY, Vec3::ONE).unwrap();
let c = w.take_changes();
assert!(!c.structural && c.added.contains(&2) && c.moved.is_empty(), "added in place, where it is");
assert!(w.objects[&2].driven && w.movable(2));
assert!(w.place_driven(2, Vec3::new(0.0, 2.0, 0.0), Quat::IDENTITY));
let c = w.take_changes();
assert!(!c.structural && c.moved.contains(&2) && w.objects[&2].position.y == 2.0, "its body's move: in place");
assert!(w.place_driven(2, Vec3::new(0.0, 2.0, 0.0), Quat::IDENTITY) && !w.take_changes().any(), "where it is already: nothing");
assert!(!w.place_driven(99, Vec3::ZERO, Quat::IDENTITY));
// An object the scene was built with becomes one a body drives: a rebuild, once.
w.set_driven(1).unwrap();
assert!(w.take_changes().structural && w.movable(1));
w.set_driven(1).unwrap();
assert!(!w.take_changes().any());
}
#[test]
fn geometry_edits_in_place() {
let tri = || Geometry { positions: vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0], normals: vec![0.0; 9], uvs: vec![0.0; 6], indices: vec![0, 1, 2], groups: vec![], colors: vec![] };
let mut w = World::default();
w.set_material(1, mat());
w.set_geometry(1, tri()).unwrap();
w.set_geometry(2, tri()).unwrap();
w.set_object(1, "own".into(), None, Kind::Mesh { geometry: 1, material: 1, own_blas: true, materials: vec![] }, true, false).unwrap();
w.set_object(2, "flat".into(), None, Kind::Mesh { geometry: 2, material: 1, own_blas: false, materials: vec![] }, true, false).unwrap();
w.set_proc_geometry(3, "f".into(), vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0], vec![]).unwrap();
w.set_object(3, "proc".into(), None, Kind::Procedural { geometry: 3, materials: vec![1] }, true, false).unwrap();
assert!(w.take_changes().structural, "the first commit builds the scene");
// Replacing geometry: in place, whether or not the scene said it edits the mesh.
w.set_geometry(1, tri()).unwrap();
w.set_proc_geometry(3, "f".into(), vec![0.0, 0.0, 0.0, 2.0, 2.0, 2.0], vec![]).unwrap();
let c = w.take_changes();
assert!(!c.structural && c.geometries.contains(&1) && c.geometries.contains(&3) && c.edits());
w.set_geometry(2, tri()).unwrap();
let c = w.take_changes();
assert!(!c.structural && c.geometries.contains(&2), "a mesh's geometry the scene did not say it edits: in place too");
// A mesh given another geometry is one the scene edits from now on (the build keeps room for that), and stays so.
w.set_object(12, "lod".into(), None, Kind::Mesh { geometry: 1, material: 1, own_blas: false, materials: vec![] }, true, false).unwrap();
let c = w.take_changes();
assert!(!c.structural && c.added.contains(&12) && matches!(w.objects[&12].kind, Kind::Mesh { own_blas: false, .. }), "a new mesh: placed in place");
w.set_object(12, "lod".into(), None, Kind::Mesh { geometry: 2, material: 1, own_blas: false, materials: vec![] }, true, false).unwrap();
let c = w.take_changes();
assert!(!c.structural && c.added.contains(&12) && matches!(w.objects[&12].kind, Kind::Mesh { own_blas: true, .. }));
w.set_object(12, "lod".into(), None, Kind::Mesh { geometry: 1, material: 1, own_blas: false, materials: vec![] }, true, false).unwrap();
let c = w.take_changes();
assert!(!c.structural && c.added.contains(&12) && matches!(w.objects[&12].kind, Kind::Mesh { own_blas: true, .. }), "it stays one the scene edits");
w.remove(12);
w.take_changes();
// Added (placed where it is: its transform is not a move), re-created with other geometry, removed.
w.set_object(4, "piece".into(), None, Kind::Procedural { geometry: 3, materials: vec![1] }, true, false).unwrap();
w.set_transform(4, Vec3::X, Quat::IDENTITY, Vec3::ONE).unwrap();
w.set_object(1, "own".into(), None, Kind::Mesh { geometry: 2, material: 1, own_blas: true, materials: vec![] }, true, false).unwrap();
w.remove(3);
let c = w.take_changes();
assert!(!c.structural && c.moved.is_empty(), "{c:?}");
assert_eq!((c.added.iter().copied().collect::<Vec<_>>(), c.removed.iter().copied().collect::<Vec<_>>()), (vec![1, 4], vec![3]));
// Added and removed in one batch: nothing to do.
w.set_object(5, "brief".into(), None, Kind::Procedural { geometry: 3, materials: vec![1] }, true, false).unwrap();
w.remove(5);
assert!(!w.take_changes().any());
// Not in place: movable procedural geometry, another kind.
w.set_object(6, "mover".into(), None, Kind::Procedural { geometry: 3, materials: vec![1] }, true, true).unwrap();
assert!(w.take_changes().structural, "movable");
w.set_object(1, "own".into(), None, Kind::Procedural { geometry: 3, materials: vec![1] }, true, false).unwrap();
assert!(w.take_changes().structural, "another kind");
// In place: a movable mesh added (its instance moves), any mesh removed, an object with children that are
// meshes, procedural geometry or groups.
w.set_object(13, "moving".into(), None, Kind::Mesh { geometry: 1, material: 1, own_blas: false, materials: vec![] }, true, true).unwrap();
let c = w.take_changes();
assert!(!c.structural && c.added.contains(&13), "a movable mesh: placed in place");
w.set_object(11, "flat2".into(), None, Kind::Mesh { geometry: 1, material: 1, own_blas: false, materials: vec![] }, true, false).unwrap();
w.take_changes();
w.remove(11);
let c = w.take_changes();
assert!(!c.structural && c.removed.contains(&11), "a mesh the scene did not say it edits, removed");
w.set_object(7, "child".into(), Some(4), Kind::Procedural { geometry: 3, materials: vec![1] }, true, false).unwrap();
w.set_object(14, "set".into(), Some(4), Kind::Group, true, false).unwrap();
w.take_changes();
assert_eq!(w.remove(4).len(), 3);
let c = w.take_changes();
assert!(!c.structural && c.removed.iter().copied().collect::<std::collections::BTreeSet<_>>() == [4, 7].into(), "with children: each taken out, the group has nothing drawn");
// Not in place: something else among them.
w.set_object(15, "set".into(), None, Kind::Group, true, false).unwrap();
w.set_object(16, "lamp".into(), Some(15), Kind::Light(serde_json::from_value(serde_json::json!({ "type": "point", "color": [1, 1, 1], "castShadow": true, "intensity": 1, "range": 0, "radius": 0.01 })).unwrap()), true, false).unwrap();
w.take_changes();
w.remove(15);
let c = w.take_changes();
assert!(!c.structural && c.lights.contains(&16) && c.removed.is_empty(), "a group with a light: the light's entry goes, in place");
// A light alone, and a group alone: in place too. A light set again as one: its entry's change.
let lamp = |shadow: bool| Kind::Light(serde_json::from_value(serde_json::json!({ "type": "point", "color": [1, 1, 1], "castShadow": shadow, "intensity": 1, "range": 0, "radius": 0.01 })).unwrap());
w.set_object(17, "lamp".into(), None, lamp(true), true, false).unwrap();
let c = w.take_changes();
assert!(!c.structural && c.lights.contains(&17), "a new light: its entry, in place");
w.set_object(17, "lamp".into(), None, lamp(false), true, false).unwrap();
assert!(!w.changes.structural && w.take_changes().lights.contains(&17), "the light set again without its shadow");
w.set_object(18, "set".into(), None, Kind::Group, true, false).unwrap();
assert!(!w.take_changes().structural, "a new group draws nothing");
w.remove(18);
w.remove(17);
let c = w.take_changes();
assert!(!c.structural && c.lights.contains(&17), "a group and a light removed");
// A camera that is not the scene's: created, moved and removed, nothing rebuilt.
let lens = || Kind::Camera(serde_json::from_value(serde_json::json!({ "fov": 50.0, "near": 0.1, "far": 100.0, "exposure": { "mode": "manual", "ev100": 0.0 } })).unwrap());
w.set_object(19, "spare".into(), None, lens(), true, false).unwrap();
w.set_transform(19, Vec3::X, Quat::IDENTITY, Vec3::ONE).unwrap();
w.remove(19);
let c = w.take_changes();
assert!(!c.structural && !c.camera && c.removed.is_empty() && c.promoted.is_empty(), "a camera that is not the scene's");
// Not in place: something else among them (a rect light with a card is triangles).
w.set_object(15, "set".into(), None, Kind::Group, true, false).unwrap();
w.set_object(16, "card".into(), Some(15), Kind::Light(serde_json::from_value(serde_json::json!({ "type": "rect", "color": [1, 1, 1], "castShadow": true, "intensity": 1, "width": 1, "height": 1, "visible": true })).unwrap()), true, false).unwrap();
assert!(w.take_changes().structural, "a rect light with a card: a rebuild");
w.remove(15);
assert!(w.take_changes().structural, "a group with a rect light's card");
// Under a still group in a movable subtree (`movable` walks the ancestors, as the build does).
w.set_object(8, "rig".into(), None, Kind::Group, true, true).unwrap();
w.set_object(9, "still".into(), Some(8), Kind::Group, true, false).unwrap();
w.take_changes();
w.set_object(10, "piece".into(), Some(9), Kind::Procedural { geometry: 3, materials: vec![1] }, true, false).unwrap();
assert!(w.take_changes().structural, "a movable ancestor");
}
/// Instanced objects: their table checked; the table, the node's transform, power and customData change in place;
/// colours appearing rebuild (a kernel feature).
#[test]
fn instanced_objects_change_in_place() {
let tri = Geometry { positions: vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0], normals: vec![0.0; 9], uvs: vec![0.0; 6], indices: vec![0, 1, 2], groups: vec![], colors: vec![] };
let mut w = World::default();
w.set_material(1, mat());
w.set_geometry(1, tri).unwrap();
w.set_object(2, "copies".into(), None, Kind::Instanced { geometry: 1, procedural: false, materials: vec![1], capacity: 2 }, true, false).unwrap();
let m: Vec<f32> = [Mat4::IDENTITY.to_cols_array(), Mat4::from_translation(Vec3::X).to_cols_array()].concat();
assert!(w.set_instances(2, 3, Some(m.clone()), None, None).is_err(), "count past the capacity");
assert!(w.set_instances(2, 2, Some(m[..16].to_vec()), None, None).is_err(), "matrices for 1 of 2");
assert!(w.set_instances(2, 2, None, Some(vec![1.0; 5]), None).is_err(), "colours");
w.set_instances(2, 2, Some(m), None, Some(vec![f32::NAN, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0])).unwrap();
assert!(w.take_changes().structural, "the first commit builds the scene");
let t = &w.instanced[&2];
assert_eq!((t.matrix(1), t.custom(0, [9.0; 4]), t.color(1)), (Mat4::from_translation(Vec3::X), [0.0, 1.0, 2.0, 3.0], [1.0; 3]));
w.set_instances(2, 1, None, None, None).unwrap();
w.set_transform(2, Vec3::Y, Quat::IDENTITY, Vec3::ONE).unwrap();
w.set_power(2, 3.0).unwrap();
let c = w.take_changes();
assert!(!c.structural && c.instanced.contains(&2) && c.moved.is_empty() && w.objects[&2].movable == false, "{c:?}");
w.set_instances(2, 1, None, Some(vec![2.0, f32::INFINITY, -1.0, 1.0, 1.0, 1.0]), None).unwrap();
assert!(w.take_changes().structural, "colours appearing");
assert_eq!(w.instanced[&2].color(0), [2.0, 1.0, 0.0]);
w.set_instances(2, 2, None, Some(vec![0.5; 6]), None).unwrap();
assert!(!w.take_changes().structural, "new colours");
w.set_geometry(1, Geometry { positions: vec![0.0; 9], normals: vec![0.0; 9], uvs: vec![0.0; 6], indices: vec![0, 1, 2], groups: vec![], colors: vec![] }).unwrap();
assert!(w.take_changes().structural, "an instanced mesh's geometry");
w.remove(2);
assert!(w.instanced.is_empty());
}
/// three.js's background (F_BACKGROUND) and the fog's shape (F_FOG, F_VOLUME) are kernel features: appearing or
/// going is a parameter edit, as a new colour is (the live view takes the kernel's other variant). So is another sky.
#[test]
fn a_background_and_fog_come_and_go_in_place() {
let mut w = World::default();
w.take_changes();
let base = w.environment.clone();
let env = |b: Option<[f32; 3]>| desc::Environment { background: b, ..base.clone() };
for (b, what) in [(Some([1.0, 0.0, 0.0]), "a background appears"), (Some([0.0, 1.0, 0.0]), "a new colour"), (None, "the background goes")] {
w.set_environment(env(b));
let c = w.take_changes();
assert!(!c.structural && c.environment, "{what}");
}
let fog: desc::Fog = serde_json::from_value(serde_json::json!({ "density": 0.02, "heightFalloff": 0.2, "height": 0.0, "color": [1, 1, 1] })).unwrap();
w.set_environment(desc::Environment { fog: Some(fog), ..base.clone() });
let c = w.take_changes();
assert!(!c.structural && c.environment, "fog appears");
let sky: desc::Sky = serde_json::from_value(serde_json::json!({ "type": "color", "color": [0, 0, 1], "intensity": 1, "skyLightIntensity": 1 })).unwrap();
w.set_environment(desc::Environment { sky, ..base.clone() });
let c = w.take_changes();
assert!(!c.structural && c.sky && c.environment, "another sky");
}
/// The scene camera's lens and exposure, and the preset: in place. Another camera's lens: nothing to do.
#[test]
fn a_lens_an_exposure_and_a_preset_change_in_place() {
let mut w = World::default();
let cam = |fov: f32, exposure: serde_json::Value| -> desc::Camera { serde_json::from_value(serde_json::json!({ "fov": fov, "near": 0.1, "far": 100, "exposure": exposure })).unwrap() };
let manual = |ev: f32| serde_json::json!({ "mode": "manual", "ev100": ev });
w.set_object(1, "camera".into(), None, Kind::Camera(cam(50.0, manual(0.0))), true, false).unwrap();
w.set_object(2, "other".into(), None, Kind::Camera(cam(50.0, manual(0.0))), true, false).unwrap();
w.set_settings(Settings { camera: Some(1), ..Default::default() });
w.take_changes();
w.set_camera_desc(1, cam(30.0, manual(0.0))).unwrap();
let c = w.take_changes();
assert!(!c.structural && c.camera && !c.view, "a lens: the view takes it");
let mut with_dof = cam(30.0, manual(0.0));
with_dof.dof = Some(serde_json::from_value(serde_json::json!({ "focusDistance": 3, "fStop": 2, "sensorWidth": 36 })).unwrap());
w.set_camera_desc(1, with_dof).unwrap();
let c = w.take_changes();
assert!(!c.structural && !c.camera && c.view, "a depth of field: the view stays");
w.set_camera_desc(1, cam(30.0, manual(0.0))).unwrap();
w.take_changes();
w.set_camera_desc(1, cam(30.0, manual(2.0))).unwrap();
let c = w.take_changes();
assert!(!c.structural && !c.camera && c.view, "an exposure value");
w.set_camera_desc(1, cam(30.0, serde_json::json!({ "mode": "auto", "compensation": 0, "minEv100": -2, "maxEv100": 12 }))).unwrap();
let c = w.take_changes();
assert!(!c.structural && !c.camera && c.view, "an exposure mode");
w.set_camera_desc(2, cam(20.0, manual(5.0))).unwrap();
assert!(!w.take_changes().any(), "a camera that is not the scene's");
w.set_settings(Settings { camera: Some(2), ..w.settings.clone() });
let c = w.take_changes();
assert!(!c.structural && c.camera, "the scene's camera is another");
w.set_settings(Settings { preset: "preview".into(), ..w.settings.clone() });
let c = w.take_changes();
assert!(!c.structural && c.settings, "another preset");
w.set_settings(Settings { overrides: Some(serde_json::json!({ "native": { "maxBounces": 2 } })), ..w.settings.clone() });
let c = w.take_changes();
assert!(!c.structural && c.settings, "the preset's overrides");
w.set_settings(Settings { width: 640, height: 360, time: 3.0, ..w.settings.clone() });
assert!(!w.take_changes().any(), "an offline render's size and clock");
}
#[test]
fn classifies_edits() {
let mut w = World::default();
w.set_geometry(1, Geometry { positions: vec![0.0; 9], normals: vec![0.0; 9], uvs: vec![0.0; 6], indices: vec![0, 1, 2], groups: vec![], colors: vec![] }).unwrap();
w.set_material(1, mat());
w.set_object(1, "a".into(), None, Kind::Mesh { geometry: 1, material: 1, own_blas: false, materials: vec![] }, true, false).unwrap();
w.set_object(2, "cam".into(), None, Kind::Group, false, false).unwrap();
for bad in ["../x.glb", "/etc/passwd", "a/../../b", "https://x/y.glb", ""] {
assert!(w.set_object(9, "m".into(), None, Kind::Model { uri: bad.into(), nodes: None, animation: None, functions: vec![] }, true, false).is_err(), "{bad}");
}
w.settings.camera = Some(2);
assert!(w.take_changes().structural);
let mut m = mat();
m.roughness = 0.2;
w.set_material(1, m.clone());
w.set_power(1, 0.5).unwrap();
w.set_transform(2, Vec3::X, Quat::IDENTITY, Vec3::ONE).unwrap();
let c = w.take_changes();
assert!(!c.structural && c.materials.contains(&1) && c.powers.contains(&1) && c.camera);
// An alpha test that comes, changes or goes is the material's change (the tables say whether its triangles
// can follow in place: tables.rs `apply`).
for (test, what) in [(Some(0.5), "an alpha test"), (Some(0.3), "another threshold"), (None, "no alpha test again")] {
m.alpha_test = test;
w.set_material(1, m.clone());
let c = w.take_changes();
assert!(!c.structural && c.materials.contains(&1), "{what}: the material's change");
}
// Its textures too: a map that comes, another, none again.
for (map, what) in [(Some(7), "a map"), (Some(8), "another map"), (None, "no map again")] {
m.map = map;
w.set_material(1, m.clone());
let c = w.take_changes();
assert!(!c.structural && c.materials.contains(&1), "{what}: the material's change");
}
// A texture: a new one is nothing until a material names it, the same again is nothing, another under its
// number is that texture's change.
let texture = |v: u8| Texture { source: TextureSource::Pixels { width: 1, height: 1, rgba: Arc::new(vec![v; 4]) }, srgb: true, wrap: true, repeat: [1.0, 1.0], offset: [0.0, 0.0] };
w.set_texture(7, texture(1)).unwrap();
w.set_texture(7, texture(1)).unwrap();
assert!(!w.take_changes().any(), "a new texture, and the same again: no change");
w.set_texture(7, texture(2)).unwrap();
let c = w.take_changes();
assert!(!c.structural && c.textures.contains(&7) && c.any(), "other pixels: the texture's change");
w.set_texture(7, Texture { repeat: [2.0, 1.0], ..texture(2) }).unwrap();
assert!(w.take_changes().textures.contains(&7), "another repeat: the texture's change");
// A material function: new, the same again (nothing), other code; a material given one.
w.set_shader("f", "fn mf_f() {}".into(), String::new());
let c = w.take_changes();
assert!(!c.structural && c.functions && c.any(), "a new function: the kernel's code, in place");
w.set_shader("f", "fn mf_f() {}".into(), String::new());
assert!(!w.take_changes().any(), "the same function again: no change");
w.set_shader("f", "fn mf_f() { }".into(), String::new());
assert!(w.take_changes().functions, "other code: the function's change");
m.shader = Some(desc::ShaderRef { id: "f".into(), params: vec![], textures: vec![] });
w.set_material(1, m.clone());
let c = w.take_changes();
assert!(!c.structural && c.materials.contains(&1), "a material given a function: the material's change");
m.shader = None;
w.set_material(1, m.clone());
w.take_changes();
// `transparent` moves particles between the scene and the translucency pass: a rebuild.
m.transparent = true;
w.set_material(1, m.clone());
assert!(w.take_changes().structural, "a material that turns transparent: a rebuild");
m.transparent = false;
w.set_material(1, m);
w.take_changes();
w.set_object(5, "placed".into(), None, Kind::Mesh { geometry: 1, material: 1, own_blas: false, materials: vec![] }, true, false).unwrap();
w.set_transform(5, Vec3::Y, Quat::IDENTITY, Vec3::ONE).unwrap();
assert!(w.take_changes().promoted.is_empty(), "placing a new object is not a move");
w.set_transform(1, Vec3::Y, Quat::IDENTITY, Vec3::ONE).unwrap();
let c = w.take_changes();
assert!(!c.structural && c.promoted.is_empty() && c.started.contains(&1) && c.moved.contains(&1) && w.objects[&1].movable, "a still mesh's first move: its instance's, and it is movable from now on");
w.set_transform(1, Vec3::Z, Quat::IDENTITY, Vec3::ONE).unwrap();
let c = w.take_changes();
assert!(!c.structural && c.moved.contains(&1), "then it moves in place");
// Children of a movable group move with it, in place.
w.set_object(3, "car".into(), None, Kind::Group, true, true).unwrap();
w.set_object(4, "wheel".into(), Some(3), Kind::Mesh { geometry: 1, material: 1, own_blas: false, materials: vec![] }, true, false).unwrap();
w.take_changes();
w.set_transform(3, Vec3::X, Quat::IDENTITY, Vec3::ONE).unwrap();
w.set_transform(4, Vec3::Y, Quat::IDENTITY, Vec3::ONE).unwrap();
let c = w.take_changes();
assert!(!c.structural && c.moved.contains(&3) && c.moved.contains(&4));
assert_eq!(w.subtree(3), vec![3, 4]);
let mut sw = w.subtree_with(3, &w.children());
sw.sort();
assert_eq!(sw, vec![3, 4]);
assert!(!w.movable(5));
w.remove(1);
assert!(w.objects.get(&1).is_none());
}
}