Skip to main content

vibe/capability_schema/
geo_viewport_entries.rs

1//! Planetary Viewport and Multi-Scale Terrain Rendering Schemas (GEO-S10 / R10-V).
2//!
3//! Provides machine schema definitions for 10 `WebizenGeo.*` host capability invocations
4//! covering capped polyline and earcut polygon GPU tessellation, continuous distance-dependent
5//! LOD (CDLOD) quadtree node selection, crack-free vertical terrain skirts, MVT vector tile
6//! zoom styling, curved centerline label placement, screen-space R-tree label collision resolution,
7//! planetary sky atmosphere Rayleigh/Mie limb scattering, Gerstner wave displacement with foam,
8//! and hypsometric elevation contour shading with screen-coordinate feature picking.
9
10use super::{EffectClass, HonestyLabel, SchemaArg, SchemaEntry};
11
12/// CapabilitySchemaEntry alias for uniform catalog representation.
13pub type CapabilitySchemaEntry = SchemaEntry;
14
15/// Effect classification for VibeScript 0.2 capability operations.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17pub enum Effect {
18    Pure, Compute, Cold, Async, External,
19}
20
21impl Effect {
22    pub const fn as_str(&self) -> &'static str {
23        match self {
24            Self::Pure => "pure", Self::Compute => "compute", Self::Cold => "cold",
25            Self::Async => "async", Self::External => "external",
26        }
27    }
28}
29
30/// Tag alias for effect classification.
31pub type EffectTag = Effect;
32
33/// Execution intent class for Webizen planetary viewport operations.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
35pub enum ExecutionClass { PureCpu, InteractiveViewport, AsyncHost }
36
37/// Determinism guarantee levels for planetary viewport operations.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
39pub enum DeterminismGuarantee { BitExactParity, PlatformAgnostic, DeterministicDigest }
40
41/// Semantic unit classification for viewport measurements.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
43pub enum SemanticUnit { Dimensionless, Meters, Radians, Degrees, Seconds, Bytes, Pixels }
44
45/// Value type classification for schema parameters.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
47pub enum ValueType { F32, F64, U32, U64, I32, I64, Bool, Str, Record, List, FieldRef, GeometryRef }
48
49/// Style profile for viewport rendering passes.
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
51pub enum StyleProfile { CdlodTerrain, MvtVector, SkyAtmosphere, WaterSurface, HypsometricContour }
52
53/// Style support level for viewport rendering targets.
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
55pub enum StyleSupportLevel { Core, Optional, Emulated }
56
57#[allow(non_snake_case)]
58pub mod complex_Validation { pub use super::ComplexDecl; }
59pub mod host { pub use super::EffectTag; }
60pub mod intent { pub use super::{DeterminismGuarantee, ExecutionClass}; }
61pub mod semantic_types { pub use super::{SemanticUnit, ValueType}; }
62pub mod styles { pub use super::{StyleProfile, StyleSupportLevel}; }
63
64/// Parameter type for Webizen planetary viewport operations.
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
66pub enum ParamType {
67    F64, I64, U64, Bool, Str, Record, List, FieldRef, GeometryRef,
68}
69
70impl ParamType {
71    pub const fn as_str(&self) -> &'static str {
72        match self {
73            Self::F64 => "f64", Self::I64 => "i64", Self::U64 => "u64", Self::Bool => "bool",
74            Self::Str => "string", Self::Record => "Record", Self::List => "List",
75            Self::FieldRef => "FieldRef", Self::GeometryRef => "GeometryRef",
76        }
77    }
78}
79
80/// Parameter schema descriptor.
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub struct ParamSchema {
83    pub name: &'static str,
84    pub param_type: ParamType,
85    pub required: bool,
86    pub description: &'static str,
87}
88
89const fn p(name: &'static str, ty: ParamType, req: bool, desc: &'static str) -> ParamSchema {
90    ParamSchema { name, param_type: ty, required: req, description: desc }
91}
92
93/// Operation schema specification for Webizen Geo viewport capability operations.
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub struct GeoViewportSpec {
96    pub invoke_id: &'static str,
97    pub call_path: &'static str,
98    pub effect: Effect,
99    pub params: &'static [ParamSchema],
100    pub returns: &'static str,
101    pub description: &'static str,
102}
103
104const fn spec(
105    invoke_id: &'static str, call_path: &'static str, effect: Effect,
106    returns: &'static str, description: &'static str, params: &'static [ParamSchema],
107) -> GeoViewportSpec {
108    GeoViewportSpec { invoke_id, call_path, effect, params, returns, description }
109}
110
111/// Declarative specification for a Planetary Viewport Complex.
112#[derive(Debug, Clone, PartialEq)]
113pub struct ComplexDecl {
114    pub name: String,
115    pub complex_id: String,
116    pub states: Vec<String>,
117    pub transitions: Vec<String>,
118    pub invariants: Vec<String>,
119    pub initial_state: String,
120    pub target_state: String,
121}
122
123impl ComplexDecl {
124    pub fn new(
125        name: impl Into<String>, complex_id: impl Into<String>, states: Vec<String>,
126        transitions: Vec<String>, invariants: Vec<String>,
127        initial_state: impl Into<String>, target_state: impl Into<String>,
128    ) -> Self {
129        Self {
130            name: name.into(), complex_id: complex_id.into(), states, transitions,
131            invariants, initial_state: initial_state.into(), target_state: target_state.into(),
132        }
133    }
134
135    pub fn validate(&self) -> Result<(), &'static str> {
136        if self.name.is_empty() { return Err("name must not be empty"); }
137        if self.complex_id.is_empty() { return Err("complex_id must not be empty"); }
138        if self.states.is_empty() { return Err("states must not be empty"); }
139        if self.transitions.is_empty() { return Err("transitions must not be empty"); }
140        if !self.states.contains(&self.initial_state) { return Err("initial_state not in states"); }
141        if !self.states.contains(&self.target_state) { return Err("target_state not in states"); }
142        Ok(())
143    }
144}
145
146/// Convenience alias for `ComplexDecl`.
147pub type PlanetaryViewportComplexDecl = ComplexDecl;
148
149/// Constructs the declarative `PlanetaryViewportComplex` specification.
150pub fn planetary_viewport_complex_decl() -> ComplexDecl {
151    ComplexDecl::new(
152        "PlanetaryViewportComplex",
153        "urn:qualia:topology:planetary-viewport",
154        vec![
155            "GeodesyAndTerrainReady".into(),
156            "CdlodMeshAndSkirtsBuilt".into(),
157            "VectorTilesAndLabelsPlaced".into(),
158            "AtmosphereAndWaterShaded".into(),
159            "InteractiveFramePresented".into(),
160        ],
161        vec![
162            "subdivide_cdlod_and_skirts".into(),
163            "place_mvt_curved_labels".into(),
164            "shade_atmosphere_water_contours".into(),
165            "present_and_pick_feature".into(),
166        ],
167        vec![
168            "SeamlessCdlodSkirts".into(),
169            "ZeroLabelCollisions".into(),
170            "AtmosphereLimbConservation".into(),
171            "DeterministicPickParity".into(),
172        ],
173        "GeodesyAndTerrainReady",
174        "InteractiveFramePresented",
175    )
176}
177
178/// Canonical sequence of all 10 Webizen Geo viewport invoke IDs.
179pub const GEO_VIEWPORT_INVOKE_IDS: &[&str] = &[
180    "WebizenGeo.tessellate_polyline_capped",
181    "WebizenGeo.tessellate_polygon_earcut",
182    "WebizenGeo.select_cdlod_quadtree",
183    "WebizenGeo.build_terrain_skirts",
184    "WebizenGeo.eval_mvt_style_zoom",
185    "WebizenGeo.layout_curved_centerline_labels",
186    "WebizenGeo.solve_label_collisions",
187    "WebizenGeo.eval_sky_atmosphere_limb",
188    "WebizenGeo.eval_water_wave_foam",
189    "WebizenGeo.shade_hypsometric_and_pick",
190];
191
192/// Canonical sequence of all 10 Webizen Geo viewport raw specs.
193pub const GEO_VIEWPORT_RAW: &[GeoViewportSpec] = &[
194    // 1. Tessellate capped 2D/3D polylines
195    spec("WebizenGeo.tessellate_polyline_capped", "webizen_geo.tessellate_polyline_capped", Effect::Compute, "Record",
196        "Tessellates 2D/3D polylines into vertex and index buffers with miter, bevel, or round joints and butt, square, or round end caps.", &[
197            p("polyline_vertices", ParamType::List, true, "Sequence of polyline vertex coordinates [[x, y, z], ...]"),
198            p("width_m", ParamType::F64, true, "Stroke width in world meters or screen pixels"),
199            p("joint_style", ParamType::Str, false, "Join style: miter, bevel, or round"),
200            p("cap_style", ParamType::Str, false, "End cap style: butt, square, or round"),
201            p("miter_limit", ParamType::F64, false, "Maximum miter ratio before falling back to bevel join"),
202        ]),
203    // 2. Tessellate polygons with earcut
204    spec("WebizenGeo.tessellate_polygon_earcut", "webizen_geo.tessellate_polygon_earcut", Effect::Compute, "Record",
205        "Tessellates planar or geodetic 2D polygons with optional interior hole rings into triangle indices using robust earcut.", &[
206            p("exterior_ring", ParamType::List, true, "Exterior polygon boundary ring coordinates [[x, y], ...]"),
207            p("interior_rings", ParamType::List, false, "List of interior hole boundary rings [[[x, y], ...], ...]"),
208            p("winding_rule", ParamType::Str, false, "Winding orientation check: clockwise or counter_clockwise"),
209        ]),
210    // 3. Select CDLOD terrain quadtree nodes
211    spec("WebizenGeo.select_cdlod_quadtree", "webizen_geo.select_cdlod_quadtree", Effect::Compute, "Record",
212        "Selects continuous distance-dependent LOD (CDLOD) terrain quadtree nodes based on camera frustum and morph ranges.", &[
213            p("camera_position", ParamType::List, true, "Camera position in world/geodetic coordinates [x, y, z]"),
214            p("frustum_planes", ParamType::List, true, "Camera view frustum bounding planes [[nx, ny, nz, d], ...]"),
215            p("terrain_bounds", ParamType::Record, true, "Root terrain bounding box {min_x, min_y, max_x, max_y, min_z, max_z}"),
216            p("max_lod_level", ParamType::U64, false, "Maximum quadtree subdivision depth level"),
217            p("morph_factor", ParamType::F64, false, "CDLOD morph range transition overlap factor"),
218        ]),
219    // 4. Build vertical terrain skirts
220    spec("WebizenGeo.build_terrain_skirts", "webizen_geo.build_terrain_skirts", Effect::Compute, "Record",
221        "Constructs vertical perimeter skirt mesh triangles along tile borders to seal cracks between adjacent CDLOD LOD levels.", &[
222            p("tile_vertices", ParamType::List, true, "Border vertices of terrain tile grid"),
223            p("skirt_depth_m", ParamType::F64, true, "Downward extrusion depth of perimeter skirt in meters"),
224            p("boundary_edges", ParamType::Record, false, "Bitmask or flags for north, south, east, and west perimeter seams"),
225        ]),
226    // 5. Evaluate MVT styling at zoom
227    spec("WebizenGeo.eval_mvt_style_zoom", "webizen_geo.eval_mvt_style_zoom", Effect::Pure, "Record",
228        "Evaluates Mapbox/MapLibre vector tile (MVT) styling expressions, layer filters, and zoom-interpolated symbology rules.", &[
229            p("feature_properties", ParamType::Record, true, "MVT feature attributes and metadata properties"),
230            p("zoom_level", ParamType::F64, true, "Active viewport continuous zoom level"),
231            p("style_rules", ParamType::Record, true, "Layer stylesheet filter expressions and visual styling rules"),
232        ]),
233    // 6. Layout curved centerline labels
234    spec("WebizenGeo.layout_curved_centerline_labels", "webizen_geo.layout_curved_centerline_labels", Effect::Compute, "Record",
235        "Calculates smooth curved baseline text glyph positions, orientations, and curvature limits along road/river centerlines.", &[
236            p("centerline_points", ParamType::List, true, "Path polyline points [[x, y], ...] defining label centerline"),
237            p("label_text", ParamType::Str, true, "Text string to format and lay out along centerline"),
238            p("glyph_font_metrics", ParamType::Record, true, "Font advance, ascender, and glyph bounding box metrics"),
239            p("max_angle_delta_rad", ParamType::F64, false, "Maximum permitted angular change per glyph before label rejection"),
240        ]),
241    // 7. Solve label collisions
242    spec("WebizenGeo.solve_label_collisions", "webizen_geo.solve_label_collisions", Effect::Compute, "Record",
243        "Resolves screen-space 2D label and icon bounding box collisions using priority ranking and spatial R-tree packing.", &[
244            p("candidate_labels", ParamType::List, true, "List of candidate label bounding boxes [{id, bbox, priority, anchor}, ...]"),
245            p("viewport_extent", ParamType::Record, true, "Screen-space viewport bounds {width_px, height_px}"),
246            p("decay_rate", ParamType::F64, false, "Temporal opacity fade transition rate for newly placed or occluded labels"),
247        ]),
248    // 8. Evaluate sky atmosphere limb
249    spec("WebizenGeo.eval_sky_atmosphere_limb", "webizen_geo.eval_sky_atmosphere_limb", Effect::Pure, "Record",
250        "Evaluates planetary atmospheric limb radiance, Rayleigh and Mie scattering, ozone absorption, and solar disk illumination.", &[
251            p("camera_altitude_m", ParamType::F64, true, "Observer altitude above planetary ellipsoid in meters"),
252            p("sun_direction", ParamType::List, true, "Normalized solar directional vector [x, y, z]"),
253            p("view_vector", ParamType::List, true, "Normalized view direction vector [x, y, z]"),
254            p("atmosphere_params", ParamType::Record, false, "Scale heights, Rayleigh/Mie scattering coefficients, and ozone absorption"),
255        ]),
256    // 9. Evaluate Gerstner water wave and foam
257    spec("WebizenGeo.eval_water_wave_foam", "webizen_geo.eval_water_wave_foam", Effect::Compute, "Record",
258        "Evaluates multi-octave Gerstner ocean/lake wave displacement, surface normal vectors, and shoreline foam turbulence.", &[
259            p("world_coordinates", ParamType::List, true, "Sample locations on water plane [[x, y], ...]"),
260            p("time_seconds", ParamType::F64, true, "Elapsed simulation time in seconds"),
261            p("wind_vector", ParamType::List, true, "Wind direction and speed vector [vx, vy]"),
262            p("wave_octaves", ParamType::List, false, "Gerstner wave parameter harmonics [{amplitude, wavelength, speed, steepness}, ...]"),
263        ]),
264    // 10. Shade hypsometric contours and pick
265    spec("WebizenGeo.shade_hypsometric_and_pick", "webizen_geo.shade_hypsometric_and_pick", Effect::Compute, "Record",
266        "Performs hypsometric elevation tinting with contour line generation and screen-coordinate GPU feature picking query.", &[
267            p("elevation_field", ParamType::FieldRef, true, "Terrain elevation field reference or raster surface"),
268            p("color_ramp", ParamType::List, true, "Hypsometric elevation gradient color stops [{elevation_m, color_rgba}, ...]"),
269            p("contour_interval_m", ParamType::F64, false, "Major/minor contour line elevation step in meters"),
270            p("pick_screen_coord", ParamType::Record, false, "Screen cursor coordinates {x, y} for interactive feature identification"),
271        ]),
272];
273
274/// Returns the 10 capability schema entries for the catalog.
275pub fn geo_viewport_entries() -> Vec<CapabilitySchemaEntry> {
276    GEO_VIEWPORT_RAW.iter().map(|s| {
277        let effect_class = match s.effect {
278            Effect::Pure => EffectClass::Pure,
279            Effect::Compute | Effect::Cold => EffectClass::Read,
280            Effect::Async | Effect::External => EffectClass::External,
281        };
282        let mut entry = SchemaEntry::new(s.invoke_id, effect_class, HonestyLabel::Always, s.returns)
283            .with_description(s.description);
284        for p in s.params {
285            entry = entry.with_arg(SchemaArg::new(p.name, p.param_type.as_str(), p.required).with_description(p.description));
286        }
287        entry
288    }).collect()
289}
290
291/// Standard entrypoint matching the `entries()` convention across all capability modules.
292pub fn entries() -> Vec<SchemaEntry> {
293    geo_viewport_entries()
294}
295
296/// Looks up a capability schema entry by either invoke ID or lowercase call path.
297pub fn lookup_geo_viewport_entry(call_path: &str) -> Option<CapabilitySchemaEntry> {
298    let s = GEO_VIEWPORT_RAW.iter().find(|s| s.call_path == call_path || s.invoke_id == call_path)?;
299    let effect_class = match s.effect {
300        Effect::Pure => EffectClass::Pure,
301        Effect::Compute | Effect::Cold => EffectClass::Read,
302        Effect::Async | Effect::External => EffectClass::External,
303    };
304    let mut entry = SchemaEntry::new(s.invoke_id, effect_class, HonestyLabel::Always, s.returns)
305        .with_description(s.description);
306    for p in s.params {
307        entry = entry.with_arg(SchemaArg::new(p.name, p.param_type.as_str(), p.required).with_description(p.description));
308    }
309    Some(entry)
310}
311
312/// Looks up raw operation specification by invoke ID or call path.
313pub fn lookup_geo_viewport_spec(call_path: &str) -> Option<&'static GeoViewportSpec> {
314    GEO_VIEWPORT_RAW.iter().find(|s| s.call_path == call_path || s.invoke_id == call_path)
315}
316
317#[cfg(test)]
318mod tests {
319    use super::*;
320
321    #[test]
322    fn test_geo_viewport_count_and_uniqueness() {
323        assert_eq!(GEO_VIEWPORT_RAW.len(), 10);
324        assert_eq!(GEO_VIEWPORT_INVOKE_IDS.len(), 10);
325        for (i, spec) in GEO_VIEWPORT_RAW.iter().enumerate() {
326            assert_eq!(spec.invoke_id, GEO_VIEWPORT_INVOKE_IDS[i]);
327            assert!(spec.invoke_id.starts_with("WebizenGeo."));
328            assert!(spec.call_path.starts_with("webizen_geo."));
329            assert!(!spec.returns.is_empty());
330            assert!(!spec.description.is_empty());
331        }
332        let mut ids: Vec<&str> = GEO_VIEWPORT_INVOKE_IDS.to_vec();
333        ids.sort();
334        ids.dedup();
335        assert_eq!(ids.len(), 10, "All 10 invoke IDs must be unique");
336
337        let mut paths: Vec<&str> = GEO_VIEWPORT_RAW.iter().map(|s| s.call_path).collect();
338        paths.sort();
339        paths.dedup();
340        assert_eq!(paths.len(), 10, "All 10 call paths must be unique");
341    }
342
343    #[test]
344    fn test_entries_conversion_and_lookup() {
345        for id in GEO_VIEWPORT_INVOKE_IDS {
346            assert!(lookup_geo_viewport_entry(id).is_some());
347        }
348        for spec in GEO_VIEWPORT_RAW {
349            assert!(lookup_geo_viewport_entry(spec.call_path).is_some());
350        }
351        assert!(lookup_geo_viewport_entry("WebizenGeo.unknown_call").is_none());
352
353        let converted = geo_viewport_entries();
354        assert_eq!(converted.len(), 10);
355        for (i, entry) in converted.iter().enumerate() {
356            assert_eq!(entry.id, GEO_VIEWPORT_INVOKE_IDS[i]);
357            assert_eq!(entry.honesty, HonestyLabel::Always);
358        }
359
360        let alias_entries = entries();
361        assert_eq!(alias_entries.len(), 10);
362
363        let spec_ref = lookup_geo_viewport_spec("webizen_geo.select_cdlod_quadtree");
364        assert!(spec_ref.is_some());
365        assert_eq!(spec_ref.unwrap().invoke_id, "WebizenGeo.select_cdlod_quadtree");
366    }
367
368    #[test]
369    fn test_planetary_viewport_complex_decl_validation() {
370        let decl = planetary_viewport_complex_decl();
371        assert!(decl.validate().is_ok());
372        assert_eq!(decl.name, "PlanetaryViewportComplex");
373        assert_eq!(decl.complex_id, "urn:qualia:topology:planetary-viewport");
374        assert_eq!(decl.states.len(), 5);
375        assert_eq!(decl.transitions.len(), 4);
376        assert_eq!(decl.invariants.len(), 4);
377        assert_eq!(decl.initial_state, "GeodesyAndTerrainReady");
378        assert_eq!(decl.target_state, "InteractiveFramePresented");
379
380        let bad_initial = ComplexDecl::new("C", "id", vec!["A".into()], vec!["t".into()], vec![], "NonExistent", "A");
381        assert!(bad_initial.validate().is_err());
382
383        let bad_target = ComplexDecl::new("C", "id", vec!["A".into()], vec!["t".into()], vec![], "A", "NonExistent");
384        assert!(bad_target.validate().is_err());
385
386        let empty_name = ComplexDecl::new("", "id", vec!["A".into()], vec!["t".into()], vec![], "A", "A");
387        assert!(empty_name.validate().is_err());
388    }
389
390    #[test]
391    fn test_kosciuszko_e2e_authoring_fixture_exists() {
392        let manifest_dir = env!("CARGO_MANIFEST_DIR");
393        let fixture_path = std::path::Path::new(manifest_dir)
394            .join("fixtures")
395            .join("geography")
396            .join("kosciuszko_e2e_authoring.vibe");
397        assert!(
398            fixture_path.exists(),
399            "Fixture kosciuszko_e2e_authoring.vibe must exist at {:?}",
400            fixture_path
401        );
402    }
403}