Skip to main content

vibe/physics/
fields.rs

1//! Ambient Fields — spatial-physical field declarations and samplers.
2//!
3//! Represents physical quantities defined over manifold space (pressure, temperature,
4//! EM / IOR medium, acoustic impedance, chemical species) without consuming 10D tensor axes.
5//!
6//! Reference: `docs/plans/vibe-design/20260819_fields-materials-and-creator-physics.md` §2.1.
7
8use crate::ast::{FieldRepresentation, FieldSupport};
9
10/// Physical quantity kind of an ambient field.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub enum FieldQuantity {
13    Pressure,
14    Temperature,
15    GravityPotential,
16    OpticalMedium,
17    AcousticImpedance,
18    ChemicalSpecies(String),
19    Custom(String),
20}
21
22impl FieldQuantity {
23    /// `iri` form.
24    pub fn as_iri(&self) -> &str {
25        match self {
26            Self::Pressure => "http://qudt.org/vocab/quantitykind/Pressure",
27            Self::Temperature => "http://qudt.org/vocab/quantitykind/ThermodynamicTemperature",
28            Self::GravityPotential => "http://qudt.org/vocab/quantitykind/GravitationalPotential",
29            Self::OpticalMedium => "https://qualiadb.org/schema/field/OpticalRefractiveIndex",
30            Self::AcousticImpedance => "http://qudt.org/vocab/quantitykind/AcousticImpedance",
31            Self::ChemicalSpecies(s) => s.as_str(),
32            Self::Custom(c) => c.as_str(),
33        }
34    }
35}
36
37/// Standardized unit of measurement for field samples.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub enum FieldUnit {
40    KiloPascal,
41    Pascal,
42    Kelvin,
43    Celsius,
44    MetresPerSecondSquared,
45    JoulesPerKilogram,
46    Dimensionless,
47    PascalSecondPerMetre,
48    MolePerCubicMetre,
49    Custom(String),
50}
51
52impl FieldUnit {
53    /// `iri` form.
54    pub fn as_iri(&self) -> &str {
55        match self {
56            Self::KiloPascal => "http://qudt.org/vocab/unit/KiloPA",
57            Self::Pascal => "http://qudt.org/vocab/unit/PA",
58            Self::Kelvin => "http://qudt.org/vocab/unit/K",
59            Self::Celsius => "http://qudt.org/vocab/unit/DEG_C",
60            Self::MetresPerSecondSquared => "http://qudt.org/vocab/unit/M-PER-SEC2",
61            Self::JoulesPerKilogram => "http://qudt.org/vocab/unit/J-PER-KILO",
62            Self::Dimensionless => "http://qudt.org/vocab/unit/UNITLESS",
63            Self::PascalSecondPerMetre => "http://qudt.org/vocab/unit/PA-SEC-PER-M",
64            Self::MolePerCubicMetre => "http://qudt.org/vocab/unit/MOL-PER-M3",
65            Self::Custom(s) => s.as_str(),
66        }
67    }
68}
69
70/// Analytic field model parameterization.
71#[derive(Debug, Clone, PartialEq)]
72pub enum AnalyticFieldProfile {
73    /// Uniform scalar value throughout space.
74    Uniform(f64),
75    /// Barometric exponential gradient along Z: P(z) = P0 * exp(-z / scale_height).
76    BarometricGradient { p0: f64, scale_height: f64 },
77    /// Radial inverse-square point source (e.g. thermal / acoustic source at origin).
78    RadialSource {
79        origin: [f64; 3],
80        intensity: f64,
81        falloff: f64,
82    },
83    /// Linear directional gradient: V(p) = base + dot(p, direction) * slope.
84    LinearGradient {
85        base: f64,
86        direction: [f64; 3],
87        slope: f64,
88    },
89}
90
91/// Ambient Field Declaration.
92#[derive(Debug, Clone, PartialEq)]
93pub struct FieldDeclaration {
94    /// Unique Field IRI (e.g. `did:q42:field:ambient_pressure`).
95    pub id: String,
96    /// Physical quantity kind.
97    pub quantity: FieldQuantity,
98    /// Standardized unit.
99    pub unit: FieldUnit,
100    /// Spatial distribution support.
101    pub support: FieldSupport,
102    /// Underlying representation.
103    pub representation: FieldRepresentation,
104    /// Analytical profile when representation is Analytic.
105    pub profile: AnalyticFieldProfile,
106}
107
108impl FieldDeclaration {
109    /// Create standard atmospheric sea-level pressure field (101.325 kPa at z=0, scale height 8500m).
110    pub fn standard_atmosphere() -> Self {
111        Self {
112            id: "did:q42:field:standard_atmosphere".to_string(),
113            quantity: FieldQuantity::Pressure,
114            unit: FieldUnit::KiloPascal,
115            support: FieldSupport::Region,
116            representation: FieldRepresentation::Analytic,
117            profile: AnalyticFieldProfile::BarometricGradient {
118                p0: 101.325,
119                scale_height: 8500.0,
120            },
121        }
122    }
123
124    /// Create room-temperature thermal field (293.15 K uniform).
125    pub fn ambient_room_temperature() -> Self {
126        Self {
127            id: "did:q42:field:room_temperature".to_string(),
128            quantity: FieldQuantity::Temperature,
129            unit: FieldUnit::Kelvin,
130            support: FieldSupport::Region,
131            representation: FieldRepresentation::Analytic,
132            profile: AnalyticFieldProfile::Uniform(293.15),
133        }
134    }
135
136    /// Create a water solvent presence field (H2O concentration mol/m³).
137    pub fn water_solvent(concentration: f64) -> Self {
138        Self {
139            id: "did:q42:field:aqueous_medium".to_string(),
140            quantity: FieldQuantity::ChemicalSpecies("did:q42:species:H2O".to_string()),
141            unit: FieldUnit::MolePerCubicMetre,
142            support: FieldSupport::Region,
143            representation: FieldRepresentation::Analytic,
144            profile: AnalyticFieldProfile::Uniform(concentration),
145        }
146    }
147
148    /// Sample the field value at a 3D position [x, y, z].
149    #[inline]
150    pub fn sample_at(&self, position: &[f64]) -> f64 {
151        let x = position.first().copied().unwrap_or(0.0);
152        let y = position.get(1).copied().unwrap_or(0.0);
153        let z = position.get(2).copied().unwrap_or(0.0);
154
155        match &self.profile {
156            AnalyticFieldProfile::Uniform(v) => *v,
157            AnalyticFieldProfile::BarometricGradient { p0, scale_height } => {
158                if *scale_height > 0.0 {
159                    p0 * (-z / scale_height).exp()
160                } else {
161                    *p0
162                }
163            }
164            AnalyticFieldProfile::RadialSource {
165                origin,
166                intensity,
167                falloff,
168            } => {
169                let dx = x - origin[0];
170                let dy = y - origin[1];
171                let dz = z - origin[2];
172                let r_sq = dx * dx + dy * dy + dz * dz;
173                intensity / (1.0 + falloff * r_sq)
174            }
175            AnalyticFieldProfile::LinearGradient {
176                base,
177                direction,
178                slope,
179            } => {
180                let proj = x * direction[0] + y * direction[1] + z * direction[2];
181                base + proj * slope
182            }
183        }
184    }
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190
191    #[test]
192    fn test_barometric_pressure_sampling() {
193        let atm = FieldDeclaration::standard_atmosphere();
194        let sea_level = atm.sample_at(&[0.0, 0.0, 0.0]);
195        assert!((sea_level - 101.325).abs() < 1e-4);
196
197        let summit = atm.sample_at(&[0.0, 0.0, 8500.0]);
198        // At 1 scale height, P = P0 * e^(-1) ≈ 101.325 * 0.367879 = 37.275 kPa
199        assert!((summit - (101.325 * (-1.0f64).exp())).abs() < 1e-3);
200    }
201
202    #[test]
203    fn test_radial_source_sampling() {
204        let thermal = FieldDeclaration {
205            id: "did:q42:field:heat_source".to_string(),
206            quantity: FieldQuantity::Temperature,
207            unit: FieldUnit::Kelvin,
208            support: FieldSupport::Point,
209            representation: FieldRepresentation::Analytic,
210            profile: AnalyticFieldProfile::RadialSource {
211                origin: [0.0, 0.0, 0.0],
212                intensity: 1000.0,
213                falloff: 0.1,
214            },
215        };
216
217        let at_origin = thermal.sample_at(&[0.0, 0.0, 0.0]);
218        assert_eq!(at_origin, 1000.0);
219
220        let at_dist = thermal.sample_at(&[3.0, 0.0, 0.0]); // r^2 = 9
221        assert!((at_dist - (1000.0 / (1.0 + 0.9))).abs() < 1e-3);
222    }
223}