Bare-Metal Studio — direct-surface embodied cockpit
All four telemetry panes AND the six top hardware fault buttons render and hit-test directly inside one compiled 60 FPS Rust/WASM surface with zero DOM layout reflows in the loop. Click the six buttons inside the canvas bezel (or press keys 1–6) to drop a 3× payload onto the RLS cerebellar mass estimator, trigger a $0 generalized-momentum contact impact, sever the 48-byte MGTP001 link, or sweep the 16×12 retinal Δlog I event gate.
view the kernel that wrote this receipt crates/mathground-view/src/studio.rs
//! `studio.rs` — Direct-Surface 60 FPS Bare-Metal Embodied Cockpit Kernel.
//!
//! Runs the complete bare-metal & foresight physical AI loop in pure compiled Rust
//! with zero DOM layout queries in the hot loop:
//! 1. `TinyLatentMppiPlanner` (`16`-D `FWHT` Hadamard latent dynamics, `16` rollouts × `8` steps).
//! 2. `EventPatchGate` (`16×12 = 192` retinal log-contrast patches skipping `~92%` static background).
//! 3. `CerebellarRlsIdentifier` online forgetting-factor RLS payload mass & certified braking radius.
//! 4. `MomentumTorqueObserver` De Luca `$0` sensorless generalized momentum contact wrench recovery.
//! 5. `PortHamiltonianTank` mechanical passivity energy valve (`E_min = 0.25 J` floor).
//! 6. `tmac_lut4_matvec_slice` (`0` weight multiplications) + `CfcLiquidCell` continuous-time reflex.
//! 7. `MgtpFrame` (`48`-byte `MGTP001` zero-copy binary DataTrack frame + IEEE CRC-32) & link-loss brake.
use mgai_baremetal::{
CerebellarRlsIdentifier, CfcLiquidCell, MGTP_BYTE_LEN, MgtpFrame, MomentumTorqueObserver,
PortHamiltonianTank, pack_signs_to_nibbles, passive_dead_reckon_step, tmac_lut4_matvec_slice,
};
use mgai_safety::{EventPatchGate, TinyLatentMppiPlanner};
pub const PATCH_COLS: usize = 16;
pub const PATCH_ROWS: usize = 12;
pub const NUM_PATCHES: usize = PATCH_COLS * PATCH_ROWS;
#[derive(Debug, Clone)]
pub struct StudioStepReport {
pub tick: u64,
pub pose: (f64, f64, f64),
pub goal_xy: (f64, f64),
pub vel_cmd: (f64, f64),
pub vel_applied: (f64, f64),
pub rollout_paths: Vec<Vec<(f64, f64)>>,
pub min_mppi_cost: f64,
pub ess: f64,
pub active_patches: Vec<usize>,
pub skip_ratio: f64,
pub active_patch_pct: u8,
pub true_mass_kg: f64,
pub est_mass_kg: f64,
pub cert_decel_ms2: f64,
pub braking_radius_m: f64,
pub contact_wrench_xy: [f64; 2],
pub tank_energy_j: f64,
pub valve_scale: f64,
pub tank_clamped: bool,
pub cfc_state: [f64; 4],
pub tmac_y0: f64,
pub mgtp_wire: [u8; MGTP_BYTE_LEN],
pub mgtp_crc32: u32,
pub link_online: bool,
pub missed_ticks: u32,
pub heavy_payload: bool,
pub bit_ops: u64,
}
pub struct StudioCockpit {
pub tick: u64,
pub x_m: f64,
pub y_m: f64,
pub theta_rad: f64,
pub vx_ms: f64,
pub vy_ms: f64,
pub v_body_ms: f64,
pub omega_rads: f64,
pub goal_idx: usize,
pub obstacles_xyr: [(f64, f64, f64); 3],
pub heavy_payload: bool,
pub link_online: bool,
pub missed_ticks: u32,
pub contact_pulse_ticks: u32,
pub surge_ticks: u32,
pub retinal_burst_ticks: u32,
pub planner: TinyLatentMppiPlanner,
pub event_gate: EventPatchGate,
pub rls: CerebellarRlsIdentifier,
pub momentum_obs: MomentumTorqueObserver<2>,
pub tank: PortHamiltonianTank<2>,
pub cfc: CfcLiquidCell<4, 8>,
pub cfc_state: [f64; 4],
pub cfc_history: Vec<f64>,
pub trail_xy: Vec<(f64, f64)>,
tmac_nibbles: [u8; 32],
tmac_scales: [f64; 8],
prev_motor_force: [f64; 2],
last_good_vel: (f64, f64),
cumulative_energy_pj: u64,
}
const WAYPOINTS: [(f64, f64); 4] = [(14.8, 7.6), (14.6, 2.2), (3.2, 2.4), (3.4, 7.6)];
impl Default for StudioCockpit {
fn default() -> Self {
Self::new()
}
}
impl StudioCockpit {
pub fn new() -> Self {
let planner = TinyLatentMppiPlanner::new(16, 8, 16, 0.35, 2.1, 2.2).unwrap_or_else(|_| {
// Fallback unreachable with power-of-two 16
TinyLatentMppiPlanner {
latent_dim: 16,
horizon_steps: 8,
num_rollouts: 16,
temperature: 0.35,
v_max: 2.1,
omega_max: 2.2,
diag_scale: vec![0.1; 16],
}
});
let event_gate = EventPatchGate::default_grid(NUM_PATCHES);
let mut signs = [1_i8; 128];
for (idx, s) in signs.iter_mut().enumerate() {
*s = if ((idx * 17 + 5) % 5) < 3 { 1 } else { -1 };
}
let mut tmac_nibbles = [0_u8; 32];
let _ = pack_signs_to_nibbles(&signs, 8, 16, &mut tmac_nibbles);
let tmac_scales = [0.35, 0.42, 0.28, 0.51, 0.39, 0.44, 0.31, 0.47];
let mut w_f = [[0.0; 8]; 4];
let mut w_h = [[0.0; 8]; 4];
for i in 0..4 {
for k in 0..8 {
let ph = ((i * 11 + k * 7) as f64) * 0.41;
w_f[i][k] = 0.35 * ph.sin();
w_h[i][k] = 0.65 * (ph + 0.8).cos();
}
}
let cfc = CfcLiquidCell::new(w_f, w_h, [1.4, 2.2, 3.1, 1.9]);
Self {
tick: 0,
x_m: 2.8,
y_m: 5.0,
theta_rad: 0.15,
vx_ms: 0.0,
vy_ms: 0.0,
v_body_ms: 0.0,
omega_rads: 0.0,
goal_idx: 0,
obstacles_xyr: [(7.4, 6.2, 0.85), (10.6, 3.6, 0.90), (8.8, 5.0, 0.65)],
heavy_payload: false,
link_online: true,
missed_ticks: 0,
contact_pulse_ticks: 0,
surge_ticks: 0,
retinal_burst_ticks: 0,
planner,
event_gate,
rls: CerebellarRlsIdentifier::new(15.0, 52.0, 0.93, 2.5),
momentum_obs: MomentumTorqueObserver::new([15.0, 15.0], 24.0),
tank: PortHamiltonianTank::new(8.5, 0.25, 12.0, [1.2, 1.2], 0.82),
cfc,
cfc_state: [0.0; 4],
cfc_history: Vec::with_capacity(96),
trail_xy: Vec::with_capacity(140),
tmac_nibbles,
tmac_scales,
prev_motor_force: [0.0, 0.0],
last_good_vel: (0.0, 0.0),
cumulative_energy_pj: 0,
}
}
pub fn reset(&mut self) {
*self = Self::new();
}
pub fn toggle_payload(&mut self) {
self.heavy_payload = !self.heavy_payload;
}
pub fn inject_contact(&mut self) {
self.contact_pulse_ticks = 22;
}
pub fn toggle_link_loss(&mut self) {
self.link_online = !self.link_online;
if self.link_online {
self.missed_ticks = 0;
}
}
pub fn drain_tank_surge(&mut self) {
self.surge_ticks = 28;
}
pub fn trigger_retinal_burst(&mut self) {
self.retinal_burst_ticks = 36;
}
/// Hit-test normalized canvas coordinates `(nx, ny) in [0, 1] x [0, 1]` for the 6 top buttons.
pub fn handle_canvas_click(&mut self, nx: f64, ny: f64, cw: f64, ch: f64) -> Option<&'static str> {
let px = nx * cw;
let py = ny * ch;
if !(8.0..=42.0).contains(&py) {
return None;
}
let btn_x0 = 16.0;
let total_w = cw - 32.0;
let gap = 8.0;
let bw = (total_w - gap * 5.0) / 6.0;
for idx in 0..6 {
let x_left = btn_x0 + (idx as f64) * (bw + gap);
if px >= x_left && px <= x_left + bw {
return Some(match idx {
0 => {
self.toggle_payload();
"toggle_payload"
}
1 => {
self.inject_contact();
"inject_contact"
}
2 => {
self.toggle_link_loss();
"toggle_link"
}
3 => {
self.drain_tank_surge();
"surge_tank"
}
4 => {
self.trigger_retinal_burst();
"retinal_burst"
}
_ => {
self.reset();
"reset"
}
});
}
}
None
}
pub fn step(&mut self) -> StudioStepReport {
self.tick = self.tick.wrapping_add(1);
let dt_s = 0.04; // 25 Hz physical sim step at 60 FPS visual cadence
// Dynamic center obstacle slight oscillation so retinal patches & MPPI react organically
let phase = (self.tick as f64) * 0.035;
self.obstacles_xyr[2].1 = 5.0 + 1.35 * phase.sin();
let mut goal = WAYPOINTS[self.goal_idx];
if (self.x_m - goal.0).hypot(self.y_m - goal.1) < 0.95 {
self.goal_idx = (self.goal_idx + 1) % WAYPOINTS.len();
goal = WAYPOINTS[self.goal_idx];
}
// 1. Retinal 16x12 EventPatchGate
let mut intensities = [0.18_f64; NUM_PATCHES];
let rx_norm = (self.x_m / 18.0) * (PATCH_COLS as f64);
let ry_norm = (1.0 - self.y_m / 10.0) * (PATCH_ROWS as f64);
let ox_norm = (self.obstacles_xyr[2].0 / 18.0) * (PATCH_COLS as f64);
let oy_norm = (1.0 - self.obstacles_xyr[2].1 / 10.0) * (PATCH_ROWS as f64);
for r in 0..PATCH_ROWS {
for c in 0..PATCH_COLS {
let cf = c as f64 + 0.5;
let rf = r as f64 + 0.5;
// Static architectural background gradient (never fires after frame 0!)
let mut lum = 0.20 + 0.06 * ((cf * 0.4).sin() * (rf * 0.5).cos());
// Moving robot & oscillating obstacle signatures
let d_rob = (cf - rx_norm).hypot(rf - ry_norm);
if d_rob < 1.7 {
lum += 0.58 * (-d_rob * d_rob * 0.9).exp();
}
let d_obs = (cf - ox_norm).hypot(rf - oy_norm);
if d_obs < 1.5 {
lum += 0.45 * (-d_obs * d_obs * 1.1).exp();
}
if self.retinal_burst_ticks > 0 {
let sweep_x = ((36 - self.retinal_burst_ticks) as f64 / 36.0) * (PATCH_COLS as f64);
if (cf - sweep_x).abs() < 1.25 {
lum += 0.62;
}
}
intensities[r * PATCH_COLS + c] = lum;
}
}
if self.retinal_burst_ticks > 0 {
self.retinal_burst_ticks -= 1;
}
let gate_rep = self
.event_gate
.filter_patches(&intensities)
.unwrap_or(mgai_safety::EventGateReport {
active_indices: Vec::new(),
skip_ratio: 0.92,
active_pct_u8: 8,
bit_ops_saved: 0,
});
// 2. T-MAC 4-bit LUT4 feature projection + CfC liquid reflex cell (irregular jittered dt)
let mut x_feat = [0.0_f64; 16];
x_feat[0] = self.x_m / 18.0;
x_feat[1] = self.y_m / 10.0;
x_feat[2] = self.theta_rad.cos();
x_feat[3] = self.theta_rad.sin();
x_feat[4] = (goal.0 - self.x_m) / 18.0;
x_feat[5] = (goal.1 - self.y_m) / 10.0;
x_feat[6] = self.v_body_ms / 2.2;
x_feat[7] = self.omega_rads / 2.2;
for k in 0..8 {
x_feat[8 + k] = intensities[(k * 23) % NUM_PATCHES] - 0.25;
}
let mut tmac_y = [0.0_f64; 8];
let lut_ops = tmac_lut4_matvec_slice(
&self.tmac_nibbles,
8,
16,
&x_feat,
Some(&self.tmac_scales),
&mut tmac_y,
);
let jitter_dt = dt_s * (1.0 + 0.35 * ((self.tick as f64) * 0.27).sin());
self.cfc_state = self.cfc.step(&self.cfc_state, &tmac_y[0..4], jitter_dt);
if self.cfc_history.len() >= 96 {
self.cfc_history.remove(0);
}
self.cfc_history.push(self.cfc_state[0]);
// 3. Tiny Latent MPPI Foresight Planner over FWHT 16-D latent space
let mut z_cur = [0.0_f64; 16];
z_cur[0] = self.x_m;
z_cur[1] = self.y_m;
z_cur[2] = self.theta_rad;
for i in 0..4 {
z_cur[3 + i] = self.cfc_state[i] * 0.25;
}
let mut z_goal = [0.0_f64; 16];
z_goal[0] = goal.0;
z_goal[1] = goal.1;
let heading_to_goal = (goal.1 - self.y_m).atan2(goal.0 - self.x_m);
let mut ang_err = heading_to_goal - self.theta_rad;
while ang_err > core::f64::consts::PI {
ang_err -= core::f64::consts::TAU;
}
while ang_err < -core::f64::consts::PI {
ang_err += core::f64::consts::TAU;
}
let nom_action = (1.65, (1.9 * ang_err).clamp(-2.0, 2.0));
let mppi_res = self
.planner
.plan(&z_cur, &z_goal, nom_action, &self.obstacles_xyr, 0.14)
.unwrap_or(mgai_safety::TinyMppiResult {
optimal_action: nom_action,
min_rollout_cost: 0.0,
mean_rollout_cost: 0.0,
effective_sample_size: 4.0,
rollout_bit_ops: 8192,
rollout_xy_paths: Vec::new(),
});
// 4. Link-loss watchdog (LiveKit / MoQ MGTP001 DataTrack)
let vel_cmd = mppi_res.optimal_action;
let vel_after_link = if self.link_online {
self.missed_ticks = 0;
self.last_good_vel = vel_cmd;
vel_cmd
} else {
self.missed_ticks = self.missed_ticks.saturating_add(1);
passive_dead_reckon_step(self.last_good_vel, self.missed_ticks, dt_s, 2, 6.5)
};
// 5. Spinal Passivity Tank + De Luca $0 Momentum Observer + Cerebellar RLS Mass Adapter
let true_mass = if self.heavy_payload { 45.0 } else { 15.0 };
let desired_vx = vel_after_link.0 * self.theta_rad.cos();
let desired_vy = vel_after_link.0 * self.theta_rad.sin();
let mut u_force = [
28.0 * (desired_vx - self.vx_ms),
28.0 * (desired_vy - self.vy_ms),
];
if self.surge_ticks > 0 {
self.surge_ticks -= 1;
u_force[0] += 95.0 * self.theta_rad.cos();
u_force[1] += 95.0 * self.theta_rad.sin();
}
let est_wrench =
self.momentum_obs
.observe(&[self.vx_ms, self.vy_ms], &self.prev_motor_force, dt_s, None);
let tank_rec = self.tank.step(&u_force, &[self.vx_ms, self.vy_ms], dt_s);
self.prev_motor_force = tank_rec.u_safe;
// External wall-bump force if triggered
let ext_fx = if self.contact_pulse_ticks > 0 {
self.contact_pulse_ticks -= 1;
-135.0 * self.theta_rad.cos()
} else {
0.0
};
let ext_fy = if self.contact_pulse_ticks > 0 {
-135.0 * self.theta_rad.sin()
} else {
0.0
};
let drag = 0.22;
let ax = (tank_rec.u_safe[0] + ext_fx - drag * true_mass * self.vx_ms) / true_mass;
let ay = (tank_rec.u_safe[1] + ext_fy - drag * true_mass * self.vy_ms) / true_mass;
let fwd_force =
tank_rec.u_safe[0] * self.theta_rad.cos() + tank_rec.u_safe[1] * self.theta_rad.sin();
let fwd_accel = ax * self.theta_rad.cos() + ay * self.theta_rad.sin();
let rls_est = self.rls.update(fwd_force, self.v_body_ms, fwd_accel);
self.vx_ms = (self.vx_ms + dt_s * ax).clamp(-2.3, 2.3);
self.vy_ms = (self.vy_ms + dt_s * ay).clamp(-2.3, 2.3);
self.v_body_ms = self.vx_ms.hypot(self.vy_ms);
self.omega_rads = vel_after_link.1;
self.x_m = (self.x_m + dt_s * self.vx_ms).clamp(1.0, 17.0);
self.y_m = (self.y_m + dt_s * self.vy_ms).clamp(1.0, 9.0);
self.theta_rad += dt_s * self.omega_rads;
if self.trail_xy.len() >= 140 {
self.trail_xy.remove(0);
}
self.trail_xy.push((self.x_m, self.y_m));
let braking_radius_m =
(self.v_body_ms * self.v_body_ms) / (2.0 * rls_est.certified_max_decel_ms2.max(0.35))
+ 0.28;
let active_patch_ops = (gate_rep.active_indices.len() as u64) * 256;
let bit_ops =
(mppi_res.rollout_bit_ops as u64) + active_patch_ops + (lut_ops as u64) * 32 + 1024;
self.cumulative_energy_pj = self.cumulative_energy_pj.saturating_add(bit_ops * 3);
let flags: u8 = u8::from(tank_rec.clamped)
| (u8::from(!self.link_online) << 1)
| (u8::from(self.heavy_payload) << 2)
| (1 << 3);
let mgtp = MgtpFrame::from_physical(
self.tick,
self.cumulative_energy_pj,
self.x_m,
self.y_m,
self.theta_rad,
self.v_body_ms,
self.omega_rads,
est_wrench[0],
est_wrench[1],
tank_rec.tank_energy_j,
gate_rep.active_pct_u8,
0,
if self.link_online { 0 } else { 2 },
flags,
);
let mgtp_wire = mgtp.encode();
let mgtp_crc32 =
u32::from_le_bytes([mgtp_wire[44], mgtp_wire[45], mgtp_wire[46], mgtp_wire[47]]);
StudioStepReport {
tick: self.tick,
pose: (self.x_m, self.y_m, self.theta_rad),
goal_xy: goal,
vel_cmd,
vel_applied: (self.v_body_ms, self.omega_rads),
rollout_paths: mppi_res.rollout_xy_paths,
min_mppi_cost: mppi_res.min_rollout_cost,
ess: mppi_res.effective_sample_size,
active_patches: gate_rep.active_indices,
skip_ratio: gate_rep.skip_ratio,
active_patch_pct: gate_rep.active_pct_u8,
true_mass_kg: true_mass,
est_mass_kg: rls_est.effective_mass_kg,
cert_decel_ms2: rls_est.certified_max_decel_ms2,
braking_radius_m,
contact_wrench_xy: est_wrench,
tank_energy_j: tank_rec.tank_energy_j,
valve_scale: tank_rec.valve_scale,
tank_clamped: tank_rec.clamped,
cfc_state: self.cfc_state,
tmac_y0: tmac_y[0],
mgtp_wire,
mgtp_crc32,
link_online: self.link_online,
missed_ticks: self.missed_ticks,
heavy_payload: self.heavy_payload,
bit_ops,
}
}
}
This is the exact Rust file compiled into the WASM module the page just loaded. Every line that runs on your device is here. The receipt is a function of this code, not a bespoke benchmark.
Zero-Heap Native Implementations
Identical deterministic physics across Rust #![no_std], Zig 0.17, and C++20.
Every primitive in the executable specification is verified against 162/162 cross-language golden conformance vectors and ships as standalone zero-allocation source in Rust #![no_std], Zig 0.17, and C++20 (-fno-exceptions -fno-rtti).
#![no_std] // crates/mgai-baremetal: 0 external crates, 0 heap alloc, <2 ULP pure-Rust math
use mgai_baremetal::{
MgtpFrame, MomentumTorqueObserver, PortHamiltonianTank,
pack_signs_to_nibbles, tmac_lut4_matvec_slice,
};
// 1. Dequantization-free 4-bit T-MAC Lookup-Table MatVec (0 weight multiplications!)
let mut nibs = [0_u8; 32];
pack_signs_to_nibbles(&binary_signs, 8, 16, &mut nibs);
let mut y = [0.0_f64; 8];
tmac_lut4_matvec_slice(&nibs, 8, 16, &sensor_x, Some(&row_scales), &mut y);
// 2. $0 Virtual Tactile Skin + Port-Hamiltonian Passivity Tank Valve
let mut touch = MomentumTorqueObserver::new([15.0, 15.0], 24.0);
let mut tank = PortHamiltonianTank::new(8.5, 0.25, 12.0, [1.2, 1.2], 0.82);
let wrench_n = touch.observe(&vel_xy, &prev_motor_force, dt_s, None);
let safe_step = tank.step(&cmd_force, &vel_xy, dt_s); // Guaranteed E(t) >= 0.25 J
// 3. Zero-Copy 48-Byte MGTP001 Binary DataTrack + IEEE 802.3 CRC-32
let wire_48b: [u8; 48] = MgtpFrame::from_physical(
tick, energy_pj, x_m, y_m, theta, v_ms, omega, wrench_n[0], wrench_n[1],
safe_step.tank_energy_j, active_patch_pct, 0, 0, flags,
).encode(); Subsystem Guarantees
Deterministic runtime & wire specification.
| System Layer | Kernel / Protocol | Deterministic Guarantee |
|---|---|---|
| Control & Inference Runtime | mgai-baremetal (Rust #![no_std], Zig 0.17, C++20) | Compile-time stack allocation, 0 heap alloc, <50 µs deterministic control tick. |
| Sub-1-Bit & LUT Matrix Compute | LittleBit-2 (0.25 bpw) + 4-bit LUT4 + FWHT | 16-entry register table lookups and butterfly adds with 0 weight multiplications. |
| Operator Cockpit Surface | mathground_view::studio (Direct WASM Canvas) | 60 FPS direct-surface rendering and pointer hit-testing in a single compiled frame. |
| Real-Time Telemetry & Fieldbus | 48B MGTP001 + 8B MIT-CAN QDD + 13B STS3215 | Naturally aligned binary frames with IEEE CRC-32 and passive velocity bleed on link loss. |
| Contact & Payload Adaptation | MomentumTorqueObserver + CerebellarRlsIdentifier + PortHamiltonianTank | Sensorless external wrench estimation, online mass identification, and bounded energy injection. |