Skip to main content

vibe/capability_schema/
geo_terrain_node_entries.rs

1//! Procedural terrain DAG node capability schemas (GEO-S2 / R2-V).
2//!
3//! Provides machine schema definitions for all 30 `Terrain.*` host capability
4//! operations covering noise generators, 14 landform primitives, modifiers,
5//! selectors, combiners, and DAG compilation.
6
7use super::{EffectClass, HonestyLabel, SchemaArg, SchemaEntry};
8
9/// Effect classification for VibeScript 0.2 capability operations.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11pub enum Effect {
12    Pure,
13    Compute,
14    Cold,
15    Async,
16    External,
17}
18
19impl Effect {
20    pub const fn as_str(&self) -> &'static str {
21        match self {
22            Self::Pure => "pure", Self::Compute => "compute", Self::Cold => "cold",
23            Self::Async => "async", Self::External => "external",
24        }
25    }
26}
27
28/// Parameter type for terrain DAG operations.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30pub enum ParamType {
31    F64, I64, U64, Bool, Str, Record, List, FieldRef, GeometryRef,
32}
33
34impl ParamType {
35    pub const fn as_str(&self) -> &'static str {
36        match self {
37            Self::F64 => "f64", Self::I64 => "i64", Self::U64 => "u64",
38            Self::Bool => "bool", Self::Str => "string", Self::Record => "Record",
39            Self::List => "List", Self::FieldRef => "FieldRef", Self::GeometryRef => "GeometryRef",
40        }
41    }
42}
43
44/// Parameter schema descriptor.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub struct ParamSchema {
47    pub name: &'static str,
48    pub param_type: ParamType,
49    pub required: bool,
50    pub description: &'static str,
51}
52
53const fn p(name: &'static str, ty: ParamType, req: bool, desc: &'static str) -> ParamSchema {
54    ParamSchema { name, param_type: ty, required: req, description: desc }
55}
56
57/// Operation schema descriptor for terrain DAG nodes.
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub struct OperationSchema {
60    pub invoke_id: &'static str,
61    pub effect: Effect,
62    pub params: &'static [ParamSchema],
63    pub returns: &'static str,
64    pub description: &'static str,
65}
66
67const fn pure_field_op(id: &'static str, desc: &'static str, params: &'static [ParamSchema]) -> OperationSchema {
68    OperationSchema { invoke_id: id, effect: Effect::Pure, params, returns: "FieldRef", description: desc }
69}
70
71/// The 14 primitive landforms supported by `Terrain.primitive_landform`.
72pub const PRIMITIVE_LANDFORMS: &[&str] = &[
73    "Mountain", "Volcano", "Caldera", "Canyon", "DuneSea", "FaultBlock", "Escarpment",
74    "ImpactCrater", "Archipelago", "RidgeLine", "Plateau", "TiltedStrata", "KarstTower",
75    "GlacialCirque",
76];
77
78/// Returns `true` if `landform` matches any of the 14 registered primitive landforms.
79pub fn is_valid_landform(landform: &str) -> bool {
80    PRIMITIVE_LANDFORMS.iter().any(|&k| k == landform)
81}
82
83/// Canonical sequence of all 30 Terrain capability invoke IDs.
84pub const GEO_TERRAIN_INVOKE_IDS: &[&str] = &[
85    "Terrain.perlin", "Terrain.simplex", "Terrain.voronoi", "Terrain.gabor", "Terrain.wavelet",
86    "Terrain.fbm", "Terrain.ridged", "Terrain.billow", "Terrain.hybrid_multi", "Terrain.swiss_turbulence",
87    "Terrain.primitive_landform", "Terrain.terrace", "Terrain.stratify", "Terrain.fold",
88    "Terrain.curve", "Terrain.autolevel", "Terrain.histogram_equalize", "Terrain.filter_morphology",
89    "Terrain.curvature_map", "Terrain.select_height", "Terrain.select_slope", "Terrain.select_aspect",
90    "Terrain.select_convexity", "Terrain.select_flow", "Terrain.select_ao", "Terrain.select_rock_treeline",
91    "Terrain.combine", "Terrain.domain_warp", "Terrain.post_process", "Terrain.bake_dag",
92];
93
94/// Canonical sequence of all 30 Terrain DAG operations.
95pub const GEO_TERRAIN_NODE_OPERATIONS: &[OperationSchema] = &[
96    pure_field_op("Terrain.perlin", "Generates coherent 2D/3D Perlin gradient noise field.", &[
97        p("seed", ParamType::U64, true, "RNG seed"), p("frequency", ParamType::F64, true, "Frequency"), p("octaves", ParamType::U64, true, "Octave count"), p("persistence", ParamType::F64, true, "Persistence"), p("lacunarity", ParamType::F64, true, "Lacunarity"),
98    ]),
99    pure_field_op("Terrain.simplex", "Generates Simplex continuous gradient noise field with reduced directional artifacts.", &[
100        p("seed", ParamType::U64, true, "RNG seed"), p("frequency", ParamType::F64, true, "Frequency"), p("octaves", ParamType::U64, true, "Octave count"), p("persistence", ParamType::F64, true, "Persistence"),
101    ]),
102    pure_field_op("Terrain.voronoi", "Generates Voronoi/cellular cellular feature field with selectable metric.", &[
103        p("seed", ParamType::U64, true, "RNG seed"), p("frequency", ParamType::F64, true, "Frequency"), p("jitter", ParamType::F64, true, "Cell jitter"), p("distance_metric", ParamType::Str, true, "Distance metric: Euclidean, Manhattan, Chebyshev"),
104    ]),
105    pure_field_op("Terrain.gabor", "Generates anisotropic Gabor noise kernel for oriented geological strata patterns.", &[
106        p("seed", ParamType::U64, true, "RNG seed"), p("frequency", ParamType::F64, true, "Frequency"), p("orientation_deg", ParamType::F64, true, "Strike angle"), p("bandwidth", ParamType::F64, true, "Bandwidth"),
107    ]),
108    pure_field_op("Terrain.wavelet", "Generates band-limited wavelet noise without aliasing across spatial scales.", &[
109        p("seed", ParamType::U64, true, "RNG seed"), p("scale", ParamType::F64, true, "Wavelet scale"), p("band_count", ParamType::U64, true, "Sub-band count"),
110    ]),
111    pure_field_op("Terrain.fbm", "Evaluates standard Fractional Brownian Motion multi-octave spectral synthesis.", &[
112        p("noise_type", ParamType::Str, true, "Basis noise"), p("octaves", ParamType::U64, true, "Octave count"), p("lacunarity", ParamType::F64, true, "Lacunarity"), p("gain", ParamType::F64, true, "Gain / persistence"),
113    ]),
114    pure_field_op("Terrain.ridged", "Evaluates ridged multifractal noise producing sharp mountain crests and ridges.", &[
115        p("noise_type", ParamType::Str, true, "Basis noise"), p("octaves", ParamType::U64, true, "Octave count"), p("lacunarity", ParamType::F64, true, "Lacunarity"), p("gain", ParamType::F64, true, "Gain"), p("offset", ParamType::F64, true, "Ridge offset"),
116    ]),
117    pure_field_op("Terrain.billow", "Evaluates billow noise producing puffy, rounded boulder or cloud-like forms.", &[
118        p("noise_type", ParamType::Str, true, "Basis noise"), p("octaves", ParamType::U64, true, "Octave count"), p("lacunarity", ParamType::F64, true, "Lacunarity"), p("gain", ParamType::F64, true, "Gain"),
119    ]),
120    pure_field_op("Terrain.hybrid_multi", "Generates hybrid multifractal terrain varying roughness across elevation bands.", &[
121        p("octaves", ParamType::U64, true, "Octaves"), p("roughness", ParamType::F64, true, "Roughness H"), p("lacunarity", ParamType::F64, true, "Lacunarity"), p("offset", ParamType::F64, true, "Zero-offset"),
122    ]),
123    pure_field_op("Terrain.swiss_turbulence", "Swiss turbulence procedural generator with derivative warping for alpine peaks.", &[
124        p("octaves", ParamType::U64, true, "Octaves"), p("lacunarity", ParamType::F64, true, "Lacunarity"), p("gain", ParamType::F64, true, "Gain"), p("warp_factor", ParamType::F64, true, "Turbulence warp factor"),
125    ]),
126    pure_field_op("Terrain.primitive_landform", "Evaluates one of 14 procedural landform primitives (Mountain, Volcano, Caldera, Canyon, DuneSea, FaultBlock, Escarpment, ImpactCrater, Archipelago, RidgeLine, Plateau, TiltedStrata, KarstTower, GlacialCirque).", &[
127        p("landform", ParamType::Str, true, "Landform identifier"), p("params", ParamType::Record, true, "Landform morphological parameters"),
128    ]),
129    pure_field_op("Terrain.terrace", "Applies geological terracing with step quantization and slope blending.", &[
130        p("input", ParamType::FieldRef, true, "Input elevation field"), p("levels", ParamType::U64, true, "Terrace count"), p("smoothness", ParamType::F64, true, "Edge smoothing factor"), p("variability", ParamType::F64, true, "Step height variation"),
131    ]),
132    pure_field_op("Terrain.stratify", "Modulates elevation into alternating soft and hard sedimentary strata layers.", &[
133        p("input", ParamType::FieldRef, true, "Input field"), p("strata_count", ParamType::U64, true, "Strata layer count"), p("sharpness", ParamType::F64, true, "Differential erosion sharpness"),
134    ]),
135    pure_field_op("Terrain.fold", "Applies geological tectonic folding (anticline/syncline) along a structural axis.", &[
136        p("input", ParamType::FieldRef, true, "Input field"), p("wavelength", ParamType::F64, true, "Fold wavelength in meters"), p("axial_strike_deg", ParamType::F64, true, "Axial plane strike angle"), p("vergence", ParamType::F64, true, "Fold asymmetry / vergence"),
137    ]),
138    pure_field_op("Terrain.curve", "Remaps elevation profile through a piecewise monotonic spline curve.", &[
139        p("input", ParamType::FieldRef, true, "Input field"), p("control_points", ParamType::List, true, "Spline knots [x, y]"),
140    ]),
141    pure_field_op("Terrain.autolevel", "Normalizes field elevation to target minimum and maximum altitude range.", &[
142        p("input", ParamType::FieldRef, true, "Input field"), p("target_min", ParamType::F64, true, "Target min altitude"), p("target_max", ParamType::F64, true, "Target max altitude"),
143    ]),
144    pure_field_op("Terrain.histogram_equalize", "Performs cumulative histogram equalization to redistribute elevation contrast.", &[
145        p("input", ParamType::FieldRef, true, "Input field"), p("bins", ParamType::U64, true, "Histogram bin count"), p("blend", ParamType::F64, true, "Equalization blend fraction"),
146    ]),
147    pure_field_op("Terrain.filter_morphology", "Performs mathematical morphology operations (erosion, dilation, opening, closing).", &[
148        p("input", ParamType::FieldRef, true, "Input field"), p("op", ParamType::Str, true, "Operation: erode, dilate, open, close"), p("radius_m", ParamType::F64, true, "Structuring element radius in meters"),
149    ]),
150    pure_field_op("Terrain.curvature_map", "Computes differential terrain surface curvature (mean, Gaussian, profile, plan).", &[
151        p("input", ParamType::FieldRef, true, "Input field"), p("scale_m", ParamType::F64, true, "Finite difference sampling radius in meters"),
152    ]),
153    pure_field_op("Terrain.select_height", "Generates an elevation threshold selection mask with smooth boundary falloff.", &[
154        p("input", ParamType::FieldRef, true, "Input field"), p("min_alt_m", ParamType::F64, true, "Minimum altitude in meters"), p("max_alt_m", ParamType::F64, true, "Maximum altitude in meters"), p("falloff_m", ParamType::F64, true, "Boundary falloff width in meters"),
155    ]),
156    pure_field_op("Terrain.select_slope", "Generates a terrain surface slope selection mask in degrees with smooth margins.", &[
157        p("input", ParamType::FieldRef, true, "Input field"), p("min_deg", ParamType::F64, true, "Minimum slope in degrees"), p("max_deg", ParamType::F64, true, "Maximum slope in degrees"), p("falloff_deg", ParamType::F64, true, "Margin falloff in degrees"),
158    ]),
159    pure_field_op("Terrain.select_aspect", "Generates a directional slope aspect selection mask (azimuth) with tolerance.", &[
160        p("input", ParamType::FieldRef, true, "Input field"), p("azimuth_deg", ParamType::F64, true, "Target azimuth in degrees (0=N, 90=E)"), p("tolerance_deg", ParamType::F64, true, "Angular tolerance width in degrees"),
161    ]),
162    pure_field_op("Terrain.select_convexity", "Selects ridges (positive convexity) or valleys (negative convexity) across terrain.", &[
163        p("input", ParamType::FieldRef, true, "Input field"), p("radius_m", ParamType::F64, true, "Neighborhood radius in meters"), p("threshold", ParamType::F64, true, "Convexity threshold"),
164    ]),
165    pure_field_op("Terrain.select_flow", "Generates hydrological upslope contributing accumulation mask from D8 flow routing.", &[
166        p("input", ParamType::FieldRef, true, "Input field"), p("threshold_area_m2", ParamType::F64, true, "Flow accumulation threshold area in m2"),
167    ]),
168    pure_field_op("Terrain.select_ao", "Computes horizon-based ambient occlusion mask for crevice sediment accumulation.", &[
169        p("input", ParamType::FieldRef, true, "Input field"), p("samples", ParamType::U64, true, "Ray sample count"), p("radius_m", ParamType::F64, true, "Occlusion search radius in meters"),
170    ]),
171    pure_field_op("Terrain.select_rock_treeline", "Selects exposed alpine rocky terrain based on altitude treeline and slope threshold.", &[
172        p("input", ParamType::FieldRef, true, "Input field"), p("treeline_alt_m", ParamType::F64, true, "Ecological treeline altitude in meters"), p("slope_limit_deg", ParamType::F64, true, "Subalpine rocky slope threshold in degrees"),
173    ]),
174    pure_field_op("Terrain.combine", "Combines two terrain fields via mathematical blending (add, sub, mul, min, max, lerp).", &[
175        p("a", ParamType::FieldRef, true, "First input field"), p("b", ParamType::FieldRef, true, "Second input field"), p("blend_mode", ParamType::Str, true, "Blend mode: add, sub, mul, min, max, lerp"), p("factor", ParamType::F64, true, "Blend weight or lerp alpha"),
176    ]),
177    pure_field_op("Terrain.domain_warp", "Warps terrain domain coordinates by a 2D vector offset displacement field.", &[
178        p("input", ParamType::FieldRef, true, "Input field to displace"), p("warp_field", ParamType::FieldRef, true, "Vector offset or scalar warp field"), p("strength", ParamType::F64, true, "Displacement magnitude in meters"),
179    ]),
180    pure_field_op("Terrain.post_process", "Chains an ordered list of post-processing filter stages across the terrain field.", &[
181        p("input", ParamType::FieldRef, true, "Input field"), p("steps", ParamType::List, true, "List of filter stage descriptor records"),
182    ]),
183    OperationSchema {
184        invoke_id: "Terrain.bake_dag", effect: Effect::Compute, returns: "Record",
185        description: "Executes and bakes a procedural terrain DAG into an evaluated elevation container.",
186        params: &[
187            p("root_node", ParamType::FieldRef, true, "Root output field of the terrain DAG"),
188            p("bounds", ParamType::Record, true, "Bounding box record: min_x, min_y, max_x, max_y"),
189            p("resolution_m", ParamType::F64, true, "Sampling grid cell resolution in meters"),
190            p("format", ParamType::Str, true, "Target container format (m64_georaster, f32_grid, heightmap_raw)"),
191        ],
192    },
193];
194
195/// Looks up a terrain DAG node operation schema by its canonical invoke ID.
196pub fn lookup_geo_terrain_node_operation(invoke_id: &str) -> Option<&'static OperationSchema> {
197    GEO_TERRAIN_NODE_OPERATIONS.iter().find(|op| op.invoke_id == invoke_id)
198}
199
200/// Returns the 30 `Terrain.*` host capability schema entries for the catalog.
201pub fn entries() -> Vec<SchemaEntry> {
202    GEO_TERRAIN_NODE_OPERATIONS
203        .iter()
204        .map(|op| {
205            let effect_class = match op.effect {
206                Effect::Pure => EffectClass::Pure,
207                Effect::Compute => EffectClass::Read,
208                Effect::Cold => EffectClass::Read,
209                Effect::Async | Effect::External => EffectClass::External,
210            };
211            let mut entry = SchemaEntry::new(
212                op.invoke_id,
213                effect_class,
214                HonestyLabel::Always,
215                op.returns,
216            )
217            .with_description(op.description);
218            for p in op.params {
219                entry = entry.with_arg(
220                    SchemaArg::new(p.name, p.param_type.as_str(), p.required)
221                        .with_description(p.description),
222                );
223            }
224            entry
225        })
226        .collect()
227}
228
229#[cfg(test)]
230mod tests {
231    use super::*;
232
233    #[test]
234    fn test_terrain_operations_count_and_uniqueness() {
235        assert_eq!(GEO_TERRAIN_NODE_OPERATIONS.len(), 30);
236        assert_eq!(GEO_TERRAIN_INVOKE_IDS.len(), 30);
237        for (i, op) in GEO_TERRAIN_NODE_OPERATIONS.iter().enumerate() {
238            assert_eq!(op.invoke_id, GEO_TERRAIN_INVOKE_IDS[i]);
239            assert!(op.invoke_id.starts_with("Terrain."));
240            assert!(!op.returns.is_empty());
241            assert!(!op.description.is_empty());
242        }
243        let mut ids: Vec<&str> = GEO_TERRAIN_INVOKE_IDS.to_vec();
244        ids.sort();
245        ids.dedup();
246        assert_eq!(ids.len(), 30, "All 30 Terrain invoke IDs must be unique");
247    }
248
249    #[test]
250    fn test_primitive_landforms_complete() {
251        assert_eq!(PRIMITIVE_LANDFORMS.len(), 14);
252        for name in PRIMITIVE_LANDFORMS {
253            assert!(is_valid_landform(name), "Primitive landform '{name}' must be valid");
254        }
255        assert!(!is_valid_landform("FlatPlains"));
256    }
257
258    #[test]
259    fn test_bake_dag_is_compute_and_constructors_are_pure() {
260        let bake = lookup_geo_terrain_node_operation("Terrain.bake_dag")
261            .expect("Terrain.bake_dag must be registered");
262        assert_eq!(bake.effect, Effect::Compute);
263        assert_eq!(bake.returns, "Record");
264
265        for op in GEO_TERRAIN_NODE_OPERATIONS {
266            if op.invoke_id != "Terrain.bake_dag" {
267                assert_eq!(op.effect, Effect::Pure, "Op {} must have Effect::Pure", op.invoke_id);
268            }
269        }
270    }
271
272    #[test]
273    fn test_lookup_and_entries_conversion() {
274        assert!(lookup_geo_terrain_node_operation("Terrain.swiss_turbulence").is_some());
275        assert!(lookup_geo_terrain_node_operation("Terrain.unknown").is_none());
276
277        let converted = entries();
278        assert_eq!(converted.len(), 30);
279        for (i, entry) in converted.iter().enumerate() {
280            assert_eq!(entry.id, GEO_TERRAIN_INVOKE_IDS[i]);
281            assert_eq!(entry.honesty, HonestyLabel::Always);
282        }
283    }
284
285    #[test]
286    fn test_terrain_dag_fixture_exists() {
287        let manifest_dir = env!("CARGO_MANIFEST_DIR");
288        let fixture_path = std::path::Path::new(manifest_dir)
289            .join("fixtures")
290            .join("geography")
291            .join("terrain_dag_pipeline.vibe");
292        assert!(
293            fixture_path.exists(),
294            "Fixture terrain_dag_pipeline.vibe must exist at {:?}",
295            fixture_path
296        );
297    }
298}