Something went wrong. Try again.
A video game where you play as a misaligned AI, deceiving and building power. An experiment in spec-driven development. forked from cameron.stream/misaligned
Something went wrong. Try again.
13 kB · 366 lines
Rust
at main
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367//! CPU implicit-surface prototype for close Thought rendering.//!//! This is presentation geometry, rebuilt from authored/readout amount and//! rate. It owns no accumulating fluid state (interface/thought-fluid.md).
use bevy::asset::RenderAssetUsages;use bevy::mesh::PrimitiveTopology;use bevy::prelude::*;
#[derive(Clone, Copy, Debug)]pub(crate) struct ThoughtSurfaceParams { pub start: Vec3, pub end: Vec3, pub amount: f32, pub rate: f32, /// Normalized presentation phase. This is disposable render state. pub phase: f32,}
const RESOLUTION: UVec3 = UVec3::new(64, 36, 34);const TETS: [[usize; 4]; 6] = [ [0, 5, 1, 6], [0, 1, 2, 6], [0, 2, 3, 6], [0, 3, 7, 6], [0, 7, 4, 6], [0, 4, 5, 6],];const TET_EDGES: [(usize, usize); 6] = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)];
pub(crate) fn build_thought_surface(params: ThoughtSurfaceParams) -> Mesh { let amount_scale = params.amount.max(0.1).cbrt(); let bounds_min = params.start.min(params.end) + Vec3::new(-0.52, -0.56, -0.72); let bounds_max = params.start.max(params.end) + Vec3::new(0.52, 0.72 + amount_scale * 0.06, 0.72); let step = (bounds_max - bounds_min) / (RESOLUTION - UVec3::ONE).as_vec3();
let index = |x: u32, y: u32, z: u32| -> usize { (x + RESOLUTION.x * (y + RESOLUTION.y * z)) as usize }; let mut values = vec![0.0; (RESOLUTION.x * RESOLUTION.y * RESOLUTION.z) as usize]; for z in 0..RESOLUTION.z { for y in 0..RESOLUTION.y { for x in 0..RESOLUTION.x { let p = bounds_min + step * UVec3::new(x, y, z).as_vec3(); values[index(x, y, z)] = thought_sdf(params, p); } } }
let mut positions: Vec<[f32; 3]> = Vec::new(); let mut normals: Vec<[f32; 3]> = Vec::new(); for z in 0..RESOLUTION.z - 1 { for y in 0..RESOLUTION.y - 1 { for x in 0..RESOLUTION.x - 1 { let corners = [ UVec3::new(x, y, z), UVec3::new(x + 1, y, z), UVec3::new(x + 1, y + 1, z), UVec3::new(x, y + 1, z), UVec3::new(x, y, z + 1), UVec3::new(x + 1, y, z + 1), UVec3::new(x + 1, y + 1, z + 1), UVec3::new(x, y + 1, z + 1), ]; let points = corners.map(|c| bounds_min + step * c.as_vec3()); let samples = corners.map(|c| values[index(c.x, c.y, c.z)]); for tet in TETS { polygonize_tet( params, tet.map(|i| points[i]), tet.map(|i| samples[i]), step.min_element() * 0.45, &mut positions, &mut normals, ); } } } }
Mesh::new( PrimitiveTopology::TriangleList, RenderAssetUsages::RENDER_WORLD | RenderAssetUsages::MAIN_WORLD, ) .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, positions) .with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, normals)}
fn polygonize_tet( params: ThoughtSurfaceParams, points: [Vec3; 4], values: [f32; 4], epsilon: f32, positions: &mut Vec<[f32; 3]>, normals: &mut Vec<[f32; 3]>,) { let mut crossings = Vec::with_capacity(4); for (a, b) in TET_EDGES { if values[a].is_sign_negative() == values[b].is_sign_negative() { continue; } let denom = values[a] - values[b]; let t = if denom.abs() <= f32::EPSILON { 0.5 } else { (values[a] / denom).clamp(0.0, 1.0) }; crossings.push(points[a].lerp(points[b], t)); } if crossings.len() < 3 { return; }
let center = crossings.iter().copied().sum::<Vec3>() / crossings.len() as f32; let outward = sdf_normal(params, center, epsilon); let axis = if outward.y.abs() < 0.85 { Vec3::Y } else { Vec3::X }; let u = outward.cross(axis).normalize_or_zero(); let v = outward.cross(u).normalize_or_zero(); crossings.sort_by(|a, b| { let da = *a - center; let db = *b - center; da.dot(v) .atan2(da.dot(u)) .total_cmp(&db.dot(v).atan2(db.dot(u))) }); for i in 1..crossings.len() - 1 { emit_triangle( params, [crossings[0], crossings[i], crossings[i + 1]], epsilon, positions, normals, ); }}
fn emit_triangle( params: ThoughtSurfaceParams, mut triangle: [Vec3; 3], epsilon: f32, positions: &mut Vec<[f32; 3]>, normals: &mut Vec<[f32; 3]>,) { let center = (triangle[0] + triangle[1] + triangle[2]) / 3.0; let outward = sdf_normal(params, center, epsilon); let face = (triangle[1] - triangle[0]).cross(triangle[2] - triangle[0]); if face.dot(outward) < 0.0 { triangle.swap(1, 2); } for point in triangle { positions.push(point.to_array()); normals.push(sdf_normal(params, point, epsilon).to_array()); }}
fn sdf_normal(params: ThoughtSurfaceParams, p: Vec3, e: f32) -> Vec3 { Vec3::new( thought_sdf(params, p + Vec3::X * e) - thought_sdf(params, p - Vec3::X * e), thought_sdf(params, p + Vec3::Y * e) - thought_sdf(params, p - Vec3::Y * e), thought_sdf(params, p + Vec3::Z * e) - thought_sdf(params, p - Vec3::Z * e), ) .normalize_or_zero()}
fn thought_sdf(params: ThoughtSurfaceParams, p: Vec3) -> f32 { let amount = params.amount.max(0.1).cbrt(); let rate = params.rate.max(0.0); let cycle = params.phase.fract() * std::f32::consts::TAU; let base_strain = ((rate - 0.72) / 0.38).clamp(0.0, 1.0); let openness = base_strain * ((cycle.sin() * 0.5 + 0.5).powf(1.6)); let window_t = 0.56 + cycle.cos() * 0.10; // The dark/current phase reaches the strain locus first; the dominant // pressure lobe follows just downstream and pulls the opening shut. let dominant_t = (window_t + 0.16 + 0.025 * cycle.sin()).min(0.84); let secondary_t = 0.20 + 0.035 * cycle.cos(); let neck_t = 0.39 + 0.025 * cycle.sin(); let base_radius = 0.060 + 0.025 * amount; let mut body = 10_000.0; const SAMPLES: usize = 39; for rail in [-1.0, 1.0] { for i in 0..SAMPLES { let t = i as f32 / (SAMPLES - 1) as f32; let center = flow_path_point(params, t, rail, cycle, openness, window_t); let before = flow_path_point( params, (t - 0.004).max(0.0), rail, cycle, openness, window_t, ); let after = flow_path_point( params, (t + 0.004).min(1.0), rail, cycle, openness, window_t, ); let tangent = (after - before).normalize_or_zero();
let dominant = gaussian(t, dominant_t, 0.14); let secondary = gaussian(t, secondary_t, 0.10); let neck = gaussian(t, neck_t, 0.085); let radius = base_radius * (0.86 + dominant * 0.70 + secondary * 0.30 - neck * 0.25).max(0.58); let axes = Vec3::new( radius * (1.55 + dominant * 0.95 + secondary * 0.30), radius * (0.52 + dominant * 0.40 + secondary * 0.22), radius * (0.28 + dominant * 0.07), ); body = smooth_min( body, oriented_ellipsoid_sdf(p - center, tangent, axes), radius * 0.30, ); if i > 0 { let previous = flow_path_point( params, (i - 1) as f32 / (SAMPLES - 1) as f32, rail, cycle, openness, window_t, ); body = smooth_min( body, capsule_sdf(p, previous, center, base_radius * 0.54), base_radius * 0.16, ); } } } body}
fn route_point(start: Vec3, end: Vec3, t: f32) -> Vec3 { let span = end - start; let c1 = start + span * 0.30 + Vec3::new(0.0, 0.55, 0.22); let c2 = start + span * 0.70 + Vec3::new(0.0, 0.28, -0.18); let u = 1.0 - t; start * u * u * u + c1 * 3.0 * u * u * t + c2 * 3.0 * u * t * t + end * t * t * t}
fn flow_path_point( params: ThoughtSurfaceParams, t: f32, rail: f32, cycle: f32, openness: f32, window_t: f32,) -> Vec3 { let wave = std::f32::consts::TAU * t; let envelope = (std::f32::consts::PI * t).sin().max(0.0).powf(0.72); let mut center = flow_spine_point(params, t);
// Two paths weave through the body. Under strain they pull apart around a // traveling locus, making the negative space from separation alone. let weave = envelope * (0.050 * (wave * 1.15 + 0.55).sin() + 0.022 * (wave * 2.3 - 0.8).sin()); let split_profile = gaussian(t, window_t, 0.20).powf(1.20); let split = openness * 0.34 * split_profile; let split_asymmetry = if rail > 0.0 { 1.0 } else { 0.85 }; center.y += rail * (weave + split * split_asymmetry); center.x += rail * envelope * 0.045 * (wave + cycle * 0.18).sin(); center.z += rail * envelope * 0.028 * (wave * 1.65 - cycle * 0.12).cos(); center}
fn flow_spine_point(params: ThoughtSurfaceParams, t: f32) -> Vec3 { let wave = std::f32::consts::TAU * t; let envelope = (std::f32::consts::PI * t).sin().max(0.0).powf(0.72); let mut center = route_point(params.start, params.end, t); // The shared spine has one long arch and a smaller returning fold rather // than a periodic chain of equal bulges. center.y += envelope * (0.12 * (wave + 0.35).sin() + 0.055 * (wave * 2.7 - 0.8).sin()); center.z += envelope * 0.035 * (wave * 1.4 + 0.5).sin(); center}
fn smooth_min(a: f32, b: f32, k: f32) -> f32 { let h = (0.5 + 0.5 * (b - a) / k.max(0.0001)).clamp(0.0, 1.0); b.lerp(a, h) - k * h * (1.0 - h)}
fn gaussian(value: f32, center: f32, width: f32) -> f32 { (-((value - center) / width.max(0.0001)).powi(2)).exp()}
fn capsule_sdf(p: Vec3, a: Vec3, b: Vec3, radius: f32) -> f32 { let pa = p - a; let ba = b - a; let h = (pa.dot(ba) / ba.length_squared().max(f32::EPSILON)).clamp(0.0, 1.0); (pa - ba * h).length() - radius}
fn oriented_ellipsoid_sdf(p: Vec3, tangent: Vec3, axes: Vec3) -> f32 { let tangent = tangent.normalize_or(Vec3::X); let across = Vec3::Z.cross(tangent).normalize_or(Vec3::Y); let depth = tangent.cross(across).normalize_or(Vec3::Z); let local = Vec3::new(p.dot(tangent), p.dot(across), p.dot(depth)); let scaled = local / axes.max(Vec3::splat(0.0001)); (scaled.length() - 1.0) * axes.min_element()}
#[cfg(test)]mod tests { use super::*;
fn params(rate: f32) -> ThoughtSurfaceParams { ThoughtSurfaceParams { start: Vec3::new(-1.6, 0.8, 0.0), end: Vec3::new(1.5, 0.7, 0.0), amount: 6.0, rate, phase: 0.25, } }
#[test] fn surface_mesh_is_nonempty() { let mesh = build_thought_surface(params(1.0)); assert!(mesh.count_vertices() > 1_000); }
#[test] fn strain_window_opens_and_seals() { let low = params(0.2); let high = params(1.3); let mut relaxed = high; relaxed.phase = 0.75; let cycle = low.phase * std::f32::consts::TAU; let window_t = 0.56 + cycle.cos() * 0.10; let p = flow_spine_point(low, window_t); assert!(thought_sdf(low, p) < 0.0, "low-rate body stays filled"); let open_value = thought_sdf(high, p); assert!( open_value > 0.0, "high-rate strain opens a window, got {open_value}" ); assert!( thought_sdf(relaxed, p) < 0.0, "the same high-rate body seals when pressure phase relaxes" ); }
#[test] fn open_window_keeps_both_paths_continuous() { let high = params(1.3); let cycle = high.phase * std::f32::consts::TAU; let window_t = 0.56 + cycle.cos() * 0.10; for rail in [-1.0, 1.0] { for i in 0..=24 { let t = i as f32 / 24.0; let center = flow_path_point(high, t, rail, cycle, 1.0, window_t); assert!( thought_sdf(high, center) < 0.0, "rail {rail} left the body at t={t}" ); } } }}