Skip to main content

hypergraph_rs/raster/instruments/
terrain.rs

1//! Instrument II — the contradiction terrain (`topology-deck.html:338-359`,
2//! Task 8). Per-agent sub-subsistence tension is IDW-interpolated into a
3//! heightfield over a fixed quad grid; agents are drawn on top at the same
4//! `height()` evaluated at their spectral `(x,y)`, colored by bloc.
5
6use serde_json::json;
7
8use crate::raster::color::heat;
9use crate::raster::deck::{Agent, DeckWorld};
10use crate::raster::{Face, Node3, Rgb, SceneGraph3D, Vertex3};
11use crate::viz::NodeStyle;
12
13use super::cylinder::spectral_positions;
14use super::InstrumentOpts;
15
16/// Quad grid resolution along x (`topology-deck.html:339`). `(N+1)`
17/// vertices per row.
18pub const N: usize = 34;
19/// Quad grid resolution along z (`:339`). `(M+1)` vertices per column.
20pub const M: usize = 24;
21/// World extent: `x,z ∈ [-S,S]` (`:339`).
22pub const S: f64 = 1.35;
23/// IDW smoothing epsilon, folded into `d²` before the reciprocal
24/// (`:344-345`). Scout-verified to MATERIALLY SMOOTH the field — carried
25/// exactly, not a render knob (plan Task 8 Interfaces).
26pub const EPS: f64 = 0.02;
27
28/// `a.bloc===0?'#F2C56B':a.bloc===1?'#E9DFC9':'#E85A44'` (`:355`).
29const BLOC_COLORS: [Rgb; 3] = [Rgb(242, 197, 107), Rgb(233, 223, 201), Rgb(232, 90, 68)];
30
31/// `t = max(0, repression * (subsistence - wealth))` (`:340-341`) — only
32/// sub-subsistence agents (`wealth < subsistence`) contribute tension.
33pub fn agent_tension(a: &Agent, repression: f64) -> f64 {
34    (repression * (a.subsistence - a.wealth)).max(0.0)
35}
36
37/// One IDW source: a tension value `t` sitting at world-space `(x,y)`.
38#[derive(Debug, Clone, Copy)]
39pub struct TensionNode {
40    pub x: f64,
41    pub y: f64,
42    pub t: f64,
43}
44
45/// `height(x,y)` (`:344-345`): IDW-weighted mean tension at `(x,y)`,
46/// normalized by `tmax`. `EPS` is folded into `d²` before the reciprocal, so
47/// the field is always finite — no singularity when evaluated AT a node's
48/// own position (Step 1's epsilon test).
49pub fn idw_height(x: f64, y: f64, nodes: &[TensionNode], tmax: f64) -> f64 {
50    let mut num = 0.0;
51    let mut den = 0.0;
52    for n in nodes {
53        let d2 = (x - n.x).powi(2) + (y - n.y).powi(2) + EPS;
54        num += n.t / d2;
55        den += 1.0 / d2;
56    }
57    (num / den) / tmax
58}
59
60/// Documented seam (PHASE-R-MAP §3, plan Task 8 Interfaces): where a
61/// community-link edge spans two spectral clusters (a "bridge"), babylon's
62/// real per-edge Ollivier-Ricci curvature gradients raise the local
63/// heightfield here. `DeckWorld` carries no bridge-curvature data and the
64/// deck fixture's own cliffs already emerge from the IDW tension field
65/// alone, so this is a no-op today — it exists purely as the slot-in point
66/// a future task widens (no new formalism is introduced by Phase R).
67pub(crate) fn bridge_cliff(_heightfield: &mut [Vec<f64>], _world: &DeckWorld) {}
68
69/// Build Instrument II (`topology-deck.html:338-359`).
70pub fn build_terrain(world: &DeckWorld, _opts: &InstrumentOpts) -> SceneGraph3D {
71    let pos = spectral_positions(world);
72
73    // Bounded: one tension node per agent (`world.agents.len()`).
74    let tension_nodes: Vec<TensionNode> = world
75        .agents
76        .iter()
77        .map(|a| {
78            let (x, y) = pos[a.id];
79            TensionNode {
80                x,
81                y,
82                t: agent_tension(a, world.repression),
83            }
84        })
85        .collect();
86    let tmax = tension_nodes
87        .iter()
88        .map(|n| n.t)
89        .fold(0.0_f64, f64::max)
90        .max(0.001);
91
92    // `(N+1)x(M+1)` vertex t-values, row-major `i in 0..=N`, `j in 0..=M`
93    // (bounded: fixed N,M constants).
94    let mut t_grid: Vec<Vec<f64>> = Vec::with_capacity(N + 1);
95    for i in 0..=N {
96        let mut row = Vec::with_capacity(M + 1);
97        for j in 0..=M {
98            let x = (i as f64 / N as f64 * 2.0 - 1.0) * S;
99            let z = (j as f64 / M as f64 * 2.0 - 1.0) * S;
100            row.push(idw_height(x / S, z / S, &tension_nodes, tmax));
101        }
102        t_grid.push(row);
103    }
104    bridge_cliff(&mut t_grid, world);
105
106    let vertex = |i: usize, j: usize| -> (Vertex3, f64) {
107        let x = (i as f64 / N as f64 * 2.0 - 1.0) * S;
108        let z = (j as f64 / M as f64 * 2.0 - 1.0) * S;
109        let t = t_grid[i][j];
110        (
111            Vertex3 {
112                x,
113                y: -0.55 + t * 0.95,
114                z,
115            },
116            t,
117        )
118    };
119
120    // Bounded: N*M quads, 2 triangle faces each.
121    let mut faces = Vec::with_capacity(N * M * 2);
122    for i in 0..N {
123        for j in 0..M {
124            let (v00, t00) = vertex(i, j);
125            let (v10, _) = vertex(i + 1, j);
126            let (v11, t11) = vertex(i + 1, j + 1);
127            let (v01, _) = vertex(i, j + 1);
128            // Per-quad t = mean of the two diagonal corners (`:347`).
129            let t = (t00 + t11) / 2.0;
130            let fill = heat(t);
131            let opacity = 0.16 + t * 0.55;
132            faces.push(Face {
133                verts: [v00, v10, v11],
134                fill,
135                opacity,
136            });
137            faces.push(Face {
138                verts: [v00, v11, v01],
139                fill,
140                opacity,
141            });
142        }
143    }
144
145    // Bounded: one node per agent.
146    let mut nodes = Vec::with_capacity(world.agents.len());
147    for a in &world.agents {
148        let (x, y) = pos[a.id];
149        let t = idw_height(x, y, &tension_nodes, tmax);
150        // `proj({x:a.x*S, y:-.53+t*.95, z:a.y*S})` (`:356`) — the height
151        // field is sampled in the UNSCALED spectral frame (`height(a.x,a.y)`,
152        // matching the grid's own `height(x/S, z/S)`), but the agent is
153        // PLACED in the same `±S` world frame the quad grid spans. Review
154        // MAJOR 1: dropping `*S` left the agents in a 1/S-shrunk frame,
155        // geometrically decoupled from the terrain they annotate.
156        nodes.push(Node3 {
157            id: format!("agent-{}", a.id),
158            pos: Vertex3 {
159                x: x * S,
160                y: -0.53 + t * 0.95,
161                z: y * S,
162            },
163            radius: 0.024,
164            color: BLOC_COLORS[a.bloc as usize],
165            style: NodeStyle::default(),
166            attrs: json!({ "agent_id": a.id, "bloc": a.bloc, "t": t }),
167        });
168    }
169
170    let mut metadata = serde_json::Map::new();
171    metadata.insert("grid_vertices".to_string(), json!((N + 1) * (M + 1)));
172    metadata.insert("extent".to_string(), json!(S));
173    metadata.insert("tmax".to_string(), json!(tmax));
174
175    SceneGraph3D {
176        nodes,
177        faces,
178        struts: Vec::new(),
179        bounding_box: (-S, -0.55, -S, S, 0.4, S),
180        metadata,
181    }
182}