Skip to content

SILVIA Core ApiNavigation Reference

Version: 3.1

Namespace: CognitiveCode.Silvia.Api


Autonomous Vehicle Guidance with Multi-Modal Sensor Fusion

SILVIA's Navigation API is a high-performance autonomous vehicle guidance system designed for drones, ground vehicles, watercraft, and submarines. It implements multi-modal sensor fusion (GPS, IMU, SLAM, compass), PID control, waypoint following, formation flight, and terrain following using a zero-allocation struct-based component architecture.

This is not just a navigation library. It's a complete autonomous vehicle control stack that transforms raw sensor data into precise vehicle actuation commands. From precision agriculture drones to tactical UAV swarms to autonomous delivery robots, SILVIA Navigation provides the sensor fusion, guidance algorithms, and control systems required for production autonomous vehicles.

Architectural Philosophy: Composition Over Hierarchy

Traditional autonomous vehicle systems use object-oriented hierarchies that create GC pressure and allocation overhead. SILVIA Navigation uses value-type component composition:

Component-Based Architecture:

  • All navigation components are structs (value types)
  • Zero heap allocations during navigation updates
  • Aggressive inlining for critical paths
  • Composition pattern with embedded components

Multi-Modal Sensor Fusion:

  • GPS Navigation - Geographic positioning and waypoint following
  • SLAM Navigation - Visual/LiDAR-based local positioning
  • Hybrid Mode - Weighted fusion based on sensor confidence
  • IMU Integration - Orientation and acceleration

Advanced Navigation Modes:

  • Manual - Direct control inputs
  • GPS - Geographic waypoint following
  • SLAM - Vision-based autonomous navigation
  • Hybrid - Multi-sensor fusion
  • Terrain Following - Automatic altitude adjustment
  • Formation Flight - Swarm coordination
  • Emergency - Fail-safe procedures

Vehicle Types & Capabilities

Supported Vehicles:

  • VehicleType.Drone - Quadcopters, fixed-wing UAVs
  • VehicleType.GroundVehicle - Rovers, autonomous cars
  • VehicleType.WaterCraft - Surface vessels, boats
  • VehicleType.Submarine - Underwater autonomous vehicles

Control Systems:

  • Position PID controller (X, Y, Z)
  • Attitude PID controller (Roll, Pitch, Yaw)
  • Waypoint follower with radius-based switching
  • Collision avoidance with obstacle detection
  • Battery management with low-power adaptation
  • Weather compensation (wind, air density)
  • Payload effects and center-of-mass adjustment

Modern Use Cases

1. Autonomous Delivery Drone with GPS Waypoints

Deploy delivery drone with automatic waypoint following and emergency procedures.

csharp
var nav = core.ApiNavigation();

// Create drone navigation entity
int droneId = nav.CreateNavigationEntity(
    VehicleType.Drone,
    maxSpeed: 15.0f,        // 15 m/s
    maxAcceleration: 5.0f,  // 5 m/s²
    collisionRadius: 2.0f   // 2 meter safety bubble
);

// Set GPS navigation mode
nav.SetNavigationMode(droneId, NavigationMode.GPS);

// Define delivery route
GeoCoordinate[] waypoints = new GeoCoordinate[] {
    new GeoCoordinate(37.7749, -122.4194, 50),  // Take-off
    new GeoCoordinate(37.7849, -122.4094, 100), // Cruise altitude
    new GeoCoordinate(37.7949, -122.3994, 100), // Waypoint
    new GeoCoordinate(37.8049, -122.3894, 50),  // Descent
    new GeoCoordinate(37.8049, -122.3894, 10)   // Landing
};
nav.SetWaypoints(droneId, waypoints);

// Update navigation loop (60 Hz)
void FixedUpdate() {
    nav.UpdateNavigation(Time.fixedDeltaTime);
    
    // Get current state
    NavigationState state = nav.GetNavigationState(droneId);
    core.ApiApp().SetTextOutput(
        $"Position: {state.Position}\n" +
        $"Velocity: {state.Velocity.Length()} m/s"
    );
}

2. UAV Swarm Formation Flight

Coordinate multiple drones in V-formation using relative positioning.

csharp
var nav = core.ApiNavigation();

// Create leader drone
int leaderId = nav.CreateNavigationEntity(VehicleType.Drone, maxSpeed: 20.0f);
nav.SetNavigationMode(leaderId, NavigationMode.GPS);

// Create follower drones in formation
int[] followerIds = new int[4];
for (int i = 0; i < 4; i++) {
    followerIds[i] = nav.CreateNavigationEntity(VehicleType.Drone, maxSpeed: 20.0f);
    
    // Enable formation flight
    float offsetX = (i % 2 == 0) ? -10.0f : 10.0f;  // Left/Right
    float offsetZ = -(i / 2 + 1) * 8.0f;           // Behind leader
    
    nav.EnableFormationFlight(
        followerIds[i],
        formationId: 1,
        positionInFormation: i + 1,
        offsetX: offsetX,
        offsetY: 0.0f,
        offsetZ: offsetZ
    );
}

// Leader navigates, followers maintain formation automatically
nav.SetTargetPosition(leaderId, 37.7849, -122.4094, 100);

3. Terrain-Following Drone for Mapping

Automatically maintain altitude above terrain while mapping.

csharp
var nav = core.ApiNavigation();

int mapperId = nav.CreateNavigationEntity(VehicleType.Drone, maxSpeed: 12.0f);

// Enable terrain following mode
nav.EnableTerrainFollowing(
    mapperId,
    desiredAltitude: 50.0f,    // 50m above terrain
    terrainClearance: 20.0f    // Minimum 20m clearance
);

// Update terrain data from LiDAR/altimeter
void ProcessTerrainSensor(float terrainHeight, Vector3 terrainNormal) {
    nav.UpdateTerrainData(
        mapperId,
        terrainHeight,
        terrainNormal.X,
        terrainNormal.Y,
        terrainNormal.Z
    );
    
    // Navigation automatically adjusts altitude
    nav.UpdateNavigation(Time.deltaTime);
}

4. Autonomous Ground Vehicle with Hybrid Navigation

Combine GPS and SLAM for robust indoor/outdoor navigation.

csharp
var nav = core.ApiNavigation();

int roverId = nav.CreateNavigationEntity(
    VehicleType.GroundVehicle,
    maxSpeed: 5.0f,
    maxAcceleration: 2.0f
);

// Use hybrid GPS + SLAM navigation
nav.SetNavigationMode(roverId, NavigationMode.Hybrid);

// Update GPS data (outdoor)
nav.UpdateGpsData(
    roverId,
    latitude: 37.7749,
    longitude: -122.4194,
    altitude: 10.0,
    accuracy: 2.5f,
    velocityX: 1.0f,
    velocityY: 0.0f,
    velocityZ: 0.5f
);

// Update SLAM data (indoor)
nav.UpdateSlamData(
    roverId,
    slamPosition: new Vector3(10.5f, 0.2f, 5.3f),
    slamOrientation: Quaternion.Identity,
    slamConfidence: 0.85f
);

// Hybrid mode automatically weights GPS vs SLAM based on confidence
nav.UpdateNavigation(Time.deltaTime);

5. Emergency Landing with Battery Management

Trigger emergency landing when battery is low.

csharp
var nav = core.ApiNavigation();

int droneId = nav.CreateNavigationEntity(VehicleType.Drone);

// Update battery status
nav.UpdateBatteryData(droneId, voltage: 11.2f, current: 5.5f);

// Check battery and trigger emergency if needed
void MonitorBattery(int entityId) {
    NavigationState state = nav.GetNavigationState(entityId);
    
    // Assuming battery voltage in custom data
    float voltage = GetBatteryVoltage();
    
    if (voltage < 11.0f) { // Critical threshold
        core.ApiApp().SetTextOutput("CRITICAL: Low battery, initiating emergency landing");
        nav.TriggerEmergency(entityId);
        
        // Emergency mode automatically hovers/descends
    }
}

6. Manual Control with Override

Switch between autonomous and manual control.

csharp
var nav = core.ApiNavigation();

int droneId = nav.CreateNavigationEntity(VehicleType.Drone);

// Autonomous GPS navigation
nav.SetNavigationMode(droneId, NavigationMode.GPS);
nav.SetTargetPosition(droneId, 37.7849, -122.4094, 100);

// Manual override from joystick
void OnManualInput(float joyX, float joyY, float joyThrottle) {
    nav.SetManualControl(
        droneId,
        thrustX: joyX,
        thrustY: 0.0f,
        thrustZ: joyY,
        throttle: joyThrottle
    );
    // Automatically switches to Manual mode
}

// Emergency stop button
void OnEmergencyStop() {
    nav.EmergencyStop(droneId); // Immediately zeros all thrust
}

Core Concepts

1. Navigation Entity System

Navigation entities are the core abstraction representing individual autonomous vehicles.

Entity Creation:

csharp
int entityId = nav.CreateNavigationEntity(
    vehicleType: VehicleType.Drone,
    maxSpeed: 15.0f,           // Maximum speed in m/s
    maxAcceleration: 5.0f,     // Maximum acceleration in m/s²
    collisionRadius: 2.0f      // Collision detection radius in meters
);

Entity Management:

csharp
// Get all active entities
int[] activeEntities = nav.GetActiveEntities();

// Get entity diagnostics
string diagnostics = nav.GetEntityDiagnostics(entityId);
core.ApiApp().SetTextOutput(diagnostics);

// Remove entity
bool removed = nav.RemoveEntity(entityId);

Configuration:

csharp
// Each entity has:
// - VehicleConfiguration (max speed, mass, PID gains, collision radius)
// - NavigationState (position, velocity, orientation, sensors)
// - ControlInputs (thrust, torque, throttle)
// - Navigation components (GPS, SLAM, PID controllers, etc.)

2. Navigation Modes

NavigationMode.Manual:

  • Direct control via SetManualControl()
  • No autonomous navigation
  • Useful for RC override

NavigationMode.GPS:

  • Geographic waypoint following
  • Uses Haversine formula for distance calculation
  • Automatic bearing computation

NavigationMode.SLAM:

  • Visual/LiDAR-based local navigation
  • Maintains local map origin
  • Suitable for indoor or GPS-denied environments

NavigationMode.Hybrid:

  • Weighted fusion of GPS and SLAM
  • Automatically balances based on sensor confidence
  • Seamless indoor/outdoor transitions

NavigationMode.TerrainFollowing:

  • Maintains altitude above terrain
  • Uses terrain normal for slope compensation
  • Ideal for mapping and surveying

NavigationMode.FormationFlight:

  • Maintains relative position to leader
  • Automatic formation offset calculation
  • Swarm coordination

NavigationMode.Emergency:

  • Fail-safe procedures
  • Hover or controlled descent
  • Triggered manually or by battery/sensor failures

3. Multi-Modal Sensor Fusion

GPS Sensor Data:

csharp
nav.UpdateGpsData(
    entityId,
    latitude: 37.7749,
    longitude: -122.4194,
    altitude: 100.0,
    accuracy: 2.5f,        // GPS accuracy in meters
    velocityX: 5.0f,       // GPS velocity components in m/s
    velocityY: 0.5f,
    velocityZ: 2.0f
);

IMU Sensor Data:

csharp
nav.UpdateImuData(
    entityId,
    accelX: 0.1f,    // Accelerometer in m/s²
    accelY: 9.8f,
    accelZ: 0.0f,
    gyroX: 0.0f,     // Gyroscope in rad/s
    gyroY: 0.05f,
    gyroZ: 0.0f
);

Compass Data:

csharp
nav.UpdateCompassData(
    entityId,
    heading: 45.0  // Compass heading in degrees
);

SLAM Data (Custom Integration):

csharp
// Assuming SLAM system provides position and orientation
Vector3 slamPosition = GetSLAMPosition();
Quaternion slamOrientation = GetSLAMOrientation();
float slamConfidence = GetSLAMConfidence();

nav.UpdateSlamData(
    entityId,
    slamPosition,
    slamOrientation,
    slamConfidence
);

Sensor Fusion Logic:

  • GPS + IMU → Fused position and velocity
  • Compass → Heading correction
  • SLAM → Indoor positioning when GPS unavailable
  • Hybrid mode → Weighted average based on confidence

4. PID Control System

Position PID Controller:

  • Controls X, Y, Z position
  • Output: Desired thrust vector
  • Configurable gains (Kp, Ki, Kd)

Attitude PID Controller:

  • Controls Roll, Pitch, Yaw
  • Output: Desired torque vector
  • Prevents overshoot and oscillation

PID Configuration:

csharp
// Position control (aggressive for responsiveness)
PidGains positionGains = new PidGains(
    Kp: 1.0f,   // Proportional gain
    Ki: 0.1f,   // Integral gain
    Kd: 0.5f    // Derivative gain
);

// Attitude control (higher gains for stability)
PidGains attitudeGains = new PidGains(
    Kp: 2.0f,
    Ki: 0.2f,
    Kd: 1.0f
);

// Applied during entity creation via VehicleConfiguration

Control Loop Flow:

1. Calculate position error: target - current
2. PID update → desired thrust vector
3. Calculate target orientation from thrust
4. Calculate attitude error: target orientation - current
5. PID update → desired torque vector
6. Apply thrust and torque to ControlInputs

5. Geographic Coordinate System

Coordinate Conversion:

csharp
// Geographic to Local (ENU: East-North-Up)
Vector3 local = nav.GeoToLocal(
    geoLat: 37.7749,
    geoLon: -122.4194,
    geoAlt: 100.0,
    originLat: 37.7700,
    originLon: -122.4100,
    originAlt: 0.0
);
// Returns: X=East, Y=Up, Z=North in meters

// Local to Geographic
GeoCoordinate geo = nav.LocalToGeo(
    localX: 500.0f,
    localY: 100.0f,
    localZ: 300.0f,
    originLat: 37.7700,
    originLon: -122.4100,
    originAlt: 0.0
);

Distance and Bearing:

csharp
// Haversine distance (great-circle)
double distance = nav.CalculateDistance(
    lat1: 37.7749,
    lon1: -122.4194,
    lat2: 37.8049,
    lon2: -122.3894
);
core.ApiApp().SetTextOutput($"Distance: {distance} meters");

// Initial bearing (compass direction)
double bearing = nav.CalculateBearing(
    lat1: 37.7749,
    lon1: -122.4194,
    lat2: 37.8049,
    lon2: -122.3894
);
core.ApiApp().SetTextOutput($"Bearing: {bearing}° (0=North, 90=East)");

6. Waypoint Management

Setting Waypoints:

csharp
GeoCoordinate[] waypoints = new GeoCoordinate[] {
    new GeoCoordinate(37.7749, -122.4194, 50),
    new GeoCoordinate(37.7849, -122.4094, 100),
    new GeoCoordinate(37.7949, -122.3994, 100),
    new GeoCoordinate(37.8049, -122.3894, 50)
};

nav.SetWaypoints(entityId, waypoints);

Waypoint Following Logic:

  • Waypoint radius: 5 meters (default)
  • Switches to next waypoint when within radius
  • Automatic bearing calculation to next waypoint
  • Converts geographic to local coordinates for control

Clearing Waypoints:

csharp
nav.ClearWaypoints(entityId);

7. Collision Avoidance

Obstacle Reporting:

csharp
// Report obstacle at local coordinates
nav.ReportObstacle(
    entityId,
    obstacleX: 10.0f,
    obstacleY: 0.0f,
    obstacleZ: 5.0f
);

// Avoidance vector automatically calculated
// Applied as additional thrust to avoid collision

Avoidance Logic:

  • Collision radius defined in VehicleConfiguration
  • Calculates repulsive force from obstacle
  • Decays over time (0.9x per update)
  • Added to control thrust vector

Clearing Obstacles:

csharp
nav.ClearObstacles(entityId);

8. Advanced Systems

Battery Management:

csharp
nav.UpdateBatteryData(
    entityId,
    voltage: 12.6f,  // Battery voltage
    current: 5.2f    // Current draw in amps
);

// System automatically:
// - Estimates remaining capacity
// - Reduces throttle when low battery
// - Can trigger emergency landing

Weather Compensation:

csharp
nav.UpdateWeatherConditions(
    entityId,
    windX: 2.0f,        // Wind velocity in m/s
    windY: 0.5f,
    windZ: 1.0f,
    airDensity: 1.225f, // Air density in kg/m³
    temperature: 15.0f  // Temperature in °C
);

// Automatically applies wind compensation to thrust

Payload Management:

csharp
nav.ConfigurePayload(
    entityId,
    payloadWeight: 2.5f,  // Payload weight in kg
    centerOfMassX: 0.0f,  // Center of mass offset
    centerOfMassY: -0.1f,
    centerOfMassZ: 0.0f
);

// Deploy payload mid-flight
nav.DeployPayload(entityId);
// System automatically adjusts for weight change

API Reference: ApiNavigation

Entity Management

CreateNavigationEntity(vehicleType, maxSpeed = 10.0f, maxAcceleration = 5.0f, collisionRadius = 2.0f)

Creates a new navigation entity for autonomous vehicle control.

Parameters:

  • vehicleType (VehicleType) - Type of vehicle (Drone, GroundVehicle, WaterCraft, Submarine)
  • maxSpeed (float, optional) - Maximum speed in m/s (default: 10.0)
  • maxAcceleration (float, optional) - Maximum acceleration in m/s² (default: 5.0)
  • collisionRadius (float, optional) - Collision detection radius in meters (default: 2.0)

Returns: int - Navigation entity handle/ID

Example:

csharp
int droneId = nav.CreateNavigationEntity(
    VehicleType.Drone,
    maxSpeed: 15.0f,
    maxAcceleration: 5.0f,
    collisionRadius: 2.5f
);

UpdateNavigation(deltaTime)

Updates navigation for all active entities.

Parameters:

  • deltaTime (float) - Time elapsed since last update in seconds

Behavior:

  • Clamped to 0.001-0.1 seconds for stability
  • Updates sensor fusion
  • Executes navigation mode logic
  • Updates control systems
  • Processes waypoints and collision avoidance

Example:

csharp
// Unity FixedUpdate (60 Hz)
void FixedUpdate() {
    nav.UpdateNavigation(Time.fixedDeltaTime);
}

// Manual timing
float deltaTime = 1.0f / 60.0f; // 60 Hz
nav.UpdateNavigation(deltaTime);

SetNavigationMode(entityId, mode)

Sets navigation mode for a vehicle.

Parameters:

  • entityId (int) - Navigation entity ID
  • mode (NavigationMode) - Navigation mode to use

Navigation Modes:

  • NavigationMode.Manual - Manual control inputs
  • NavigationMode.GPS - GPS waypoint following
  • NavigationMode.SLAM - Vision-based navigation
  • NavigationMode.Hybrid - GPS + SLAM fusion
  • NavigationMode.TerrainFollowing - Altitude adjustment
  • NavigationMode.FormationFlight - Swarm coordination
  • NavigationMode.Emergency - Fail-safe procedures

Example:

csharp
nav.SetNavigationMode(droneId, NavigationMode.GPS);

GetNavigationState(entityId)

Gets current navigation state.

Parameters:

  • entityId (int) - Navigation entity ID

Returns: NavigationState - Current navigation state

NavigationState Fields:

  • Position (Vector3) - Local position (X=East, Y=Up, Z=North)
  • Velocity (Vector3) - Velocity vector in m/s
  • Acceleration (Vector3) - Acceleration in m/s²
  • Orientation (Quaternion) - Orientation quaternion
  • AngularVelocity (Vector3) - Angular velocity in rad/s
  • GeoPosition (GeoCoordinate) - Geographic position
  • CompassHeading (double) - Compass heading in degrees
  • TimestampTicks (long) - High-precision timestamp

Example:

csharp
NavigationState state = nav.GetNavigationState(droneId);
string _state = $"Position: {state.Position}\n" +
                $"Speed: {state.Velocity.Length()} m/s\n" +
                $"Altitude: {state.Position.Y} m\n" +
                $"GPS: {state.GeoPosition.Latitude}, {state.GeoPosition.Longitude}";
core.ApiApp().SetTextOutput(_state);

// Get direction vectors
Vector3 forward = state.Forward();
Vector3 right = state.Right();
Vector3 up = state.Up();

RemoveEntity(entityId)

Removes a navigation entity.

Parameters:

  • entityId (int) - Entity ID to remove

Returns: bool - True if entity was removed successfully

Example:

csharp
bool removed = nav.RemoveEntity(droneId);

GetActiveEntities()

Gets all active navigation entity IDs.

Returns: int[] - Array of active entity IDs

Example:

csharp
int[] activeEntities = nav.GetActiveEntities();
core.ApiApp().SetTextOutput($"Active vehicles: {activeEntities.Length}");

string _states = "";
foreach (int entityId in activeEntities) {
    NavigationState state = nav.GetNavigationState(entityId);
    _states += $"Entity {entityId}: {state.Position}\n"
}
core.ApiApp().SetTextOutput(_states);

ResetNavigationSystem()

Resets navigation system (clears all entities and origin).

Example:

csharp
nav.ResetNavigationSystem();

Control Inputs

SetManualControl(entityId, thrustX, thrustY, thrustZ, throttle)

Sets manual control inputs for a vehicle.

Parameters:

  • entityId (int) - Navigation entity ID
  • thrustX (float) - Thrust vector X component (-1 to 1)
  • thrustY (float) - Thrust vector Y component (-1 to 1)
  • thrustZ (float) - Thrust vector Z component (-1 to 1)
  • throttle (float) - Throttle setting (0 to 1)

Behavior:

  • Automatically switches to Manual mode
  • Inputs clamped to valid ranges
  • Updates command timestamp

Example:

csharp
// Joystick input
float joyX = Input.GetAxis("Horizontal");   // -1 to 1
float joyY = Input.GetAxis("Vertical");     // -1 to 1
float joyThrottle = Input.GetAxis("Throttle"); // 0 to 1

nav.SetManualControl(droneId, joyX, 0.0f, joyY, joyThrottle);

EmergencyStop(entityId)

Triggers emergency stop for a vehicle.

Parameters:

  • entityId (int) - Navigation entity ID

Behavior:

  • Immediately zeros all thrust and torque
  • Sets emergency stop flag
  • Switches to Manual mode

Example:

csharp
// Emergency stop button
if (Input.GetKeyDown(KeyCode.Space)) {
    nav.EmergencyStop(droneId);
    core.ApiApp().SetTextOutput("EMERGENCY STOP ACTIVATED");
}

Waypoint Management

SetWaypoints(entityId, waypoints)

Sets waypoints for autonomous navigation.

Parameters:

  • entityId (int) - Navigation entity ID
  • waypoints (GeoCoordinate[]) - Array of geographic coordinates

Example:

csharp
GeoCoordinate[] waypoints = new GeoCoordinate[] {
    new GeoCoordinate(37.7749, -122.4194, 50),
    new GeoCoordinate(37.7849, -122.4094, 100),
    new GeoCoordinate(37.7949, -122.3994, 100)
};

nav.SetWaypoints(droneId, waypoints);

ClearWaypoints(entityId)

Clears all waypoints for a vehicle.

Parameters:

  • entityId (int) - Navigation entity ID

Example:

csharp
nav.ClearWaypoints(droneId);

SetTargetPosition(entityId, latitude, longitude, altitude)

Sets target position for navigation.

Parameters:

  • entityId (int) - Navigation entity ID
  • latitude (double) - Target latitude in degrees
  • longitude (double) - Target longitude in degrees
  • altitude (double) - Target altitude in meters

Example:

csharp
// Fly to specific location
nav.SetTargetPosition(droneId, 37.7749, -122.4194, 100.0);

Sensor Integration

UpdateGpsData(entityId, latitude, longitude, altitude, accuracy, velocityX, velocityY, velocityZ)

Updates GPS sensor data.

Parameters:

  • entityId (int) - Navigation entity ID
  • latitude (double) - GPS latitude in degrees
  • longitude (double) - GPS longitude in degrees
  • altitude (double) - GPS altitude in meters
  • accuracy (float) - GPS accuracy in meters
  • velocityX (float) - GPS velocity X component in m/s
  • velocityY (float) - GPS velocity Y component in m/s
  • velocityZ (float) - GPS velocity Z component in m/s

Behavior:

  • Sets global origin on first GPS reading
  • Marks GPS as valid if accuracy < 10m
  • Updates sensor timestamp

Example:

csharp
// GPS update from external sensor
nav.UpdateGpsData(
    droneId,
    latitude: gpsModule.Latitude,
    longitude: gpsModule.Longitude,
    altitude: gpsModule.Altitude,
    accuracy: gpsModule.Accuracy,
    velocityX: gpsModule.VelocityNorth,
    velocityY: gpsModule.VelocityUp,
    velocityZ: gpsModule.VelocityEast
);

UpdateImuData(entityId, accelX, accelY, accelZ, gyroX, gyroY, gyroZ)

Updates IMU sensor data.

Parameters:

  • entityId (int) - Navigation entity ID
  • accelX (float) - Accelerometer X in m/s²
  • accelY (float) - Accelerometer Y in m/s²
  • accelZ (float) - Accelerometer Z in m/s²
  • gyroX (float) - Gyroscope X in rad/s
  • gyroY (float) - Gyroscope Y in rad/s
  • gyroZ (float) - Gyroscope Z in rad/s

Example:

csharp
nav.UpdateImuData(
    droneId,
    accelX: imu.AccelX,
    accelY: imu.AccelY,
    accelZ: imu.AccelZ,
    gyroX: imu.GyroX,
    gyroY: imu.GyroY,
    gyroZ: imu.GyroZ
);

UpdateCompassData(entityId, heading)

Updates compass heading.

Parameters:

  • entityId (int) - Navigation entity ID
  • heading (double) - Compass heading in degrees (0=North, 90=East)

Example:

csharp
nav.UpdateCompassData(droneId, compass.Heading);

Collision Avoidance

ReportObstacle(entityId, obstacleX, obstacleY, obstacleZ)

Reports obstacle for collision avoidance.

Parameters:

  • entityId (int) - Navigation entity ID
  • obstacleX (float) - Obstacle X position in local coordinates
  • obstacleY (float) - Obstacle Y position in local coordinates
  • obstacleZ (float) - Obstacle Z position in local coordinates

Behavior:

  • Calculates repulsive avoidance vector
  • Applied as additional thrust
  • Decays over time

Example:

csharp
// Report obstacle detected by LiDAR
if (lidar.ObstacleDetected) {
    nav.ReportObstacle(
        droneId,
        lidar.ObstaclePosition.x,
        lidar.ObstaclePosition.y,
        lidar.ObstaclePosition.z
    );
}

ClearObstacles(entityId)

Clears all reported obstacles.

Parameters:

  • entityId (int) - Navigation entity ID

Example:

csharp
nav.ClearObstacles(droneId);

Advanced Navigation Modes

EnableTerrainFollowing(entityId, desiredAltitude, terrainClearance)

Enables terrain following navigation mode.

Parameters:

  • entityId (int) - Navigation entity ID
  • desiredAltitude (float) - Desired altitude above terrain in meters
  • terrainClearance (float) - Minimum clearance above terrain in meters

Example:

csharp
nav.EnableTerrainFollowing(droneId, desiredAltitude: 50.0f, terrainClearance: 20.0f);

EnableFormationFlight(entityId, formationId, positionInFormation, offsetX, offsetY, offsetZ)

Enables formation flight mode.

Parameters:

  • entityId (int) - Navigation entity ID
  • formationId (int) - Formation identifier
  • positionInFormation (int) - Position in formation (0 = leader)
  • offsetX (float) - Relative X offset from leader
  • offsetY (float) - Relative Y offset from leader
  • offsetZ (float) - Relative Z offset from leader

Example:

csharp
// V-formation, right wing position
nav.EnableFormationFlight(
    droneId,
    formationId: 1,
    positionInFormation: 2,
    offsetX: 10.0f,   // 10m to the right
    offsetY: 0.0f,
    offsetZ: -8.0f    // 8m behind
);

TriggerEmergency(entityId)

Triggers emergency mode.

Parameters:

  • entityId (int) - Navigation entity ID

Behavior:

  • Switches to Emergency navigation mode
  • Executes fail-safe procedures (hover or controlled descent)

Example:

csharp
if (criticalFailure) {
    nav.TriggerEmergency(droneId);
}

Vehicle Systems

UpdateBatteryData(entityId, voltage, current)

Updates battery sensor data.

Parameters:

  • entityId (int) - Navigation entity ID
  • voltage (float) - Battery voltage
  • current (float) - Battery current draw

Example:

csharp
nav.UpdateBatteryData(droneId, battery.Voltage, battery.Current);

UpdateWeatherConditions(entityId, windX, windY, windZ, airDensity, temperature)

Updates weather conditions.

Parameters:

  • entityId (int) - Navigation entity ID
  • windX (float) - Wind velocity X component
  • windY (float) - Wind velocity Y component
  • windZ (float) - Wind velocity Z component
  • airDensity (float) - Air density
  • temperature (float) - Temperature in Celsius

Example:

csharp
nav.UpdateWeatherConditions(
    droneId,
    windX: 2.5f,
    windY: 0.5f,
    windZ: 1.0f,
    airDensity: 1.225f,
    temperature: 15.0f
);

ConfigurePayload(entityId, payloadWeight, centerOfMassX, centerOfMassY, centerOfMassZ)

Configures payload for the vehicle.

Parameters:

  • entityId (int) - Navigation entity ID
  • payloadWeight (float) - Payload weight in kg
  • centerOfMassX (float) - Center of mass X offset
  • centerOfMassY (float) - Center of mass Y offset
  • centerOfMassZ (float) - Center of mass Z offset

Example:

csharp
nav.ConfigurePayload(
    droneId,
    payloadWeight: 2.5f,
    centerOfMassX: 0.0f,
    centerOfMassY: -0.1f,  // Payload hangs below
    centerOfMassZ: 0.0f
);

DeployPayload(entityId)

Deploys payload.

Parameters:

  • entityId (int) - Navigation entity ID

Behavior:

  • Marks payload as deployed
  • System automatically adjusts for weight change

Example:

csharp
// Deploy package at delivery location
if (atDeliveryLocation) {
    nav.DeployPayload(droneId);
    core.ApiApp().SetTextOutput("Package deployed");
}

UpdateTerrainData(entityId, terrainHeight, normalX, normalY, normalZ)

Updates terrain information for terrain following.

Parameters:

  • entityId (int) - Navigation entity ID
  • terrainHeight (float) - Terrain height at current position
  • normalX (float) - Terrain surface normal X
  • normalY (float) - Terrain surface normal Y
  • normalZ (float) - Terrain surface normal Z

Example:

csharp
// From LiDAR/altimeter
nav.UpdateTerrainData(
    droneId,
    terrainHeight: lidar.GroundHeight,
    normalX: terrainNormal.x,
    normalY: terrainNormal.y,
    normalZ: terrainNormal.z
);

Coordinate Conversion

CalculateDistance(lat1, lon1, lat2, lon2)

Calculates distance between two geographic coordinates using Haversine formula.

Parameters:

  • lat1 (double) - Latitude of first point in degrees
  • lon1 (double) - Longitude of first point in degrees
  • lat2 (double) - Latitude of second point in degrees
  • lon2 (double) - Longitude of second point in degrees

Returns: double - Distance in meters

Example:

csharp
double distance = nav.CalculateDistance(37.7749, -122.4194, 37.8049, -122.3894);
core.ApiApp().SetTextOutput($"Distance: {distance:F2} meters");

CalculateBearing(lat1, lon1, lat2, lon2)

Calculates bearing from one geographic coordinate to another.

Parameters:

  • lat1 (double) - Latitude of starting point in degrees
  • lon1 (double) - Longitude of starting point in degrees
  • lat2 (double) - Latitude of target point in degrees
  • lon2 (double) - Longitude of target point in degrees

Returns: double - Bearing in degrees (0 = North, 90 = East)

Example:

csharp
double bearing = nav.CalculateBearing(37.7749, -122.4194, 37.8049, -122.3894);
core.ApiApp().SetTextOutput($"Fly heading: {bearing:F1}°");

GeoToLocal(geoLat, geoLon, geoAlt, originLat, originLon, originAlt)

Converts geographic coordinates to local Cartesian coordinates.

Parameters:

  • geoLat (double) - Geographic latitude in degrees
  • geoLon (double) - Geographic longitude in degrees
  • geoAlt (double) - Geographic altitude in meters
  • originLat (double) - Origin latitude in degrees
  • originLon (double) - Origin longitude in degrees
  • originAlt (double) - Origin altitude in meters

Returns: Vector3 - Local position (X=East, Y=Up, Z=North)

Example:

csharp
Vector3 local = nav.GeoToLocal(
    geoLat: 37.7749,
    geoLon: -122.4194,
    geoAlt: 100.0,
    originLat: 37.7700,
    originLon: -122.4100,
    originAlt: 0.0
);
core.ApiApp().SetTextOutput($"Local position: {local}");

LocalToGeo(localX, localY, localZ, originLat, originLon, originAlt)

Converts local Cartesian coordinates to geographic coordinates.

Parameters:

  • localX (float) - Local X coordinate (East) in meters
  • localY (float) - Local Y coordinate (Up) in meters
  • localZ (float) - Local Z coordinate (North) in meters
  • originLat (double) - Origin latitude in degrees
  • originLon (double) - Origin longitude in degrees
  • originAlt (double) - Origin altitude in meters

Returns: GeoCoordinate - Geographic coordinate

Example:

csharp
GeoCoordinate geo = nav.LocalToGeo(
    localX: 500.0f,
    localY: 100.0f,
    localZ: 300.0f,
    originLat: 37.7700,
    originLon: -122.4100,
    originAlt: 0.0
);
core.ApiApp().SetTextOutput($"GPS: {geo.Latitude}, {geo.Longitude}, Alt: {geo.Altitude}m");

Utility Functions

WrapAngle(angle)

Wraps angle to -180 to 180 degree range.

Parameters:

  • angle (float) - Input angle in degrees

Returns: float - Wrapped angle in degrees

Example:

csharp
float wrapped = nav.WrapAngle(370.0f);  // Returns 10.0
float wrapped2 = nav.WrapAngle(-190.0f); // Returns 170.0

HeadingToQuaternion(headingDegrees)

Converts heading angle to quaternion rotation.

Parameters:

  • headingDegrees (double) - Heading angle in degrees

Returns: Quaternion - Quaternion representing the rotation

Example:

csharp
Quaternion rotation = nav.HeadingToQuaternion(45.0);
// Rotation for 45° heading (northeast)

IsNavigationAvailable()

Checks if navigation system is available.

Returns: bool - True if navigation system is operational

Example:

csharp
if (nav.IsNavigationAvailable()) {
    core.ApiApp().SetTextOutput("Navigation system online");
}

GetNavigationStatus()

Gets navigation system status.

Returns: string - Status string describing navigation system state

Example:

csharp
string status = nav.GetNavigationStatus();
core.ApiApp().SetTextOutput(status);
// "Navigation system operational - 3 active entities, Global origin: set, Total entities: 5"

GetEntityDiagnostics(entityId)

Gets navigation diagnostics for an entity.

Parameters:

  • entityId (int) - Entity ID

Returns: string - Diagnostic information string

Example:

csharp
string diagnostics = nav.GetEntityDiagnostics(droneId);
core.ApiApp().SetTextOutput(diagnostics);
// "Entity 1 - Mode: GPS, Active: True
//  Position: (10.00, 50.00, 20.00)
//  Velocity: (5.00, 0.50, 2.00)
//  Target: (100.00, 100.00, 50.00)
//  Sensors: GPS=True, IMU=True, Compass=True"

Advanced Patterns

Pattern 1: Multi-Sensor Fusion for Robust Navigation

csharp
void UpdateNavigationSensors(int entityId) {
    // GPS (outdoor)
    if (gpsModule.IsValid) {
        nav.UpdateGpsData(
            entityId,
            gpsModule.Latitude,
            gpsModule.Longitude,
            gpsModule.Altitude,
            gpsModule.Accuracy,
            gpsModule.VelocityNorth,
            gpsModule.VelocityUp,
            gpsModule.VelocityEast
        );
    }
    
    // IMU (always available)
    nav.UpdateImuData(
        entityId,
        imu.AccelX, imu.AccelY, imu.AccelZ,
        imu.GyroX, imu.GyroY, imu.GyroZ
    );
    
    // Compass (always available)
    nav.UpdateCompassData(entityId, compass.Heading);
    
    // SLAM (indoor or GPS-denied)
    if (slamModule.IsValid) {
        nav.UpdateSlamData(
            entityId,
            slamModule.Position,
            slamModule.Orientation,
            slamModule.Confidence
        );
    }
    
    // Hybrid mode automatically fuses all sensors
    nav.SetNavigationMode(entityId, NavigationMode.Hybrid);
}

Pattern 2: Precision Landing with Terrain Awareness

csharp
void PrecisionLanding(int entityId, GeoCoordinate landingZone) {
    // Approach phase
    nav.SetTargetPosition(
        entityId,
        landingZone.Latitude,
        landingZone.Longitude,
        50.0 // Approach altitude
    );
    
    // Enable terrain following for descent
    nav.EnableTerrainFollowing(entityId, desiredAltitude: 10.0f, terrainClearance: 5.0f);
    
    // Monitor approach
    NavigationState state = nav.GetNavigationState(entityId);
    double distanceToTarget = nav.CalculateDistance(
        state.GeoPosition.Latitude,
        state.GeoPosition.Longitude,
        landingZone.Latitude,
        landingZone.Longitude
    );
    
    // Final descent when close
    if (distanceToTarget < 2.0) {
        nav.SetTargetPosition(
            entityId,
            landingZone.Latitude,
            landingZone.Longitude,
            0.0 // Ground level
        );
    }
}

Pattern 3: Swarm Coordination with Formation Control

csharp
class SwarmController {
    private int leaderId;
    private List<int> followerIds = new List<int>();
    
    void InitializeSwarm(int swarmSize) {
        // Create leader
        leaderId = nav.CreateNavigationEntity(VehicleType.Drone, maxSpeed: 20.0f);
        nav.SetNavigationMode(leaderId, NavigationMode.GPS);
        
        // Create followers in formation
        float spacing = 10.0f;
        for (int i = 0; i < swarmSize - 1; i++) {
            int followerId = nav.CreateNavigationEntity(VehicleType.Drone, maxSpeed: 20.0f);
            
            // V-formation offsets
            float offsetX = (i % 2 == 0) ? -spacing : spacing;
            float offsetZ = -(i / 2 + 1) * spacing * 0.8f;
            
            nav.EnableFormationFlight(
                followerId,
                formationId: 1,
                positionInFormation: i + 1,
                offsetX: offsetX,
                offsetY: 0.0f,
                offsetZ: offsetZ
            );
            
            followerIds.Add(followerId);
        }
    }
    
    void NavigateSwarm(GeoCoordinate destination) {
        // Leader navigates, followers maintain formation
        nav.SetTargetPosition(
            leaderId,
            destination.Latitude,
            destination.Longitude,
            destination.Altitude
        );
    }
}

Pattern 4: Emergency Procedures with Battery Monitoring

csharp
void MonitorVehicleHealth(int entityId) {
    // Update battery
    nav.UpdateBatteryData(entityId, battery.Voltage, battery.Current);
    
    // Check critical thresholds
    if (battery.Voltage < 11.0f) {
        core.ApiApp().SetTextOutput("CRITICAL: Battery voltage low, initiating emergency landing");
        nav.TriggerEmergency(entityId);
        
        // Find nearest safe landing zone
        GeoCoordinate nearestLZ = FindNearestLandingZone();
        nav.SetTargetPosition(entityId, nearestLZ.Latitude, nearestLZ.Longitude, 0.0);
    }
    else if (battery.Voltage < 11.5f) {
        core.ApiApp().SetTextOutput("WARNING: Battery voltage low, reducing performance");
        // System automatically reduces throttle in control loop
    }
    
    // Monitor GPS health
    NavigationState state = nav.GetNavigationState(entityId);
    if (!state.Sensors.GpsValid && nav.GetNavigationMode(entityId) == NavigationMode.GPS) {
        core.ApiApp().SetTextOutput("WARNING: GPS lost, switching to SLAM");
        nav.SetNavigationMode(entityId, NavigationMode.SLAM);
    }
}

Pattern 5: Adaptive Control Based on Environment

csharp
void AdaptiveNavigationControl(int entityId) {
    NavigationState state = nav.GetNavigationState(entityId);
    
    // Detect environment and switch modes
    if (state.Sensors.GpsValid && state.Sensors.GpsAccuracy < 5.0f) {
        // Good GPS, use GPS navigation
        if (nav.GetNavigationMode(entityId) != NavigationMode.GPS) {
            nav.SetNavigationMode(entityId, NavigationMode.GPS);
            core.ApiApp().SetTextOutput("Switched to GPS navigation (good signal)");
        }
    }
    else if (state.Sensors.SlamValid && state.Sensors.SlamConfidence > 0.8f) {
        // GPS poor, SLAM strong, use SLAM
        if (nav.GetNavigationMode(entityId) != NavigationMode.SLAM) {
            nav.SetNavigationMode(entityId, NavigationMode.SLAM);
            core.ApiApp().SetTextOutput("Switched to SLAM navigation (GPS weak)");
        }
    }
    else if (state.Sensors.GpsValid && state.Sensors.SlamValid) {
        // Both available, use hybrid fusion
        if (nav.GetNavigationMode(entityId) != NavigationMode.Hybrid) {
            nav.SetNavigationMode(entityId, NavigationMode.Hybrid);
            core.ApiApp().SetTextOutput("Switched to Hybrid navigation (multi-sensor fusion)");
        }
    }
    
    // Update weather compensation
    if (windSensor.Available) {
        nav.UpdateWeatherConditions(
            entityId,
            windSensor.WindX,
            windSensor.WindY,
            windSensor.WindZ,
            airDensitySensor.Density,
            temperatureSensor.Temperature
        );
    }
}

Best Practices

1. Always Update Navigation Regularly

csharp
// Unity: Use FixedUpdate for consistent timing
void FixedUpdate() {
    nav.UpdateNavigation(Time.fixedDeltaTime);
}

// Non-Unity: Manual timing loop
float targetDeltaTime = 1.0f / 60.0f; // 60 Hz
nav.UpdateNavigation(targetDeltaTime);

2. Validate Sensor Data Before Updating

csharp
void UpdateSensors(int entityId) {
    // Only update GPS if valid
    if (gpsModule.IsValid && gpsModule.Accuracy < 10.0f) {
        nav.UpdateGpsData(entityId, /* ... */);
    }
    
    // Always update IMU (typically always available)
    nav.UpdateImuData(entityId, /* ... */);
    
    // Update SLAM if tracking is good
    if (slamModule.IsTracking && slamModule.Confidence > 0.7f) {
        nav.UpdateSlamData(entityId, /* ... */);
    }
}

3. Handle Mode Transitions Gracefully

csharp
void SafeModeSwitch(int entityId, NavigationMode newMode) {
    NavigationMode currentMode = GetCurrentMode(entityId);
    
    if (currentMode == newMode) return;
    
    // Clear waypoints when switching to manual
    if (newMode == NavigationMode.Manual) {
        nav.ClearWaypoints(entityId);
    }
    
    // Set waypoints when switching to GPS
    if (newMode == NavigationMode.GPS && currentMode == NavigationMode.Manual) {
        GeoCoordinate[] waypoints = GetMissionWaypoints();
        nav.SetWaypoints(entityId, waypoints);
    }
    
    nav.SetNavigationMode(entityId, newMode);
    core.ApiApp().SetTextOutput($"Mode switched: {currentMode} → {newMode}");
}

4. Monitor Navigation State Continuously

csharp
void MonitorNavigationHealth(int entityId) {
    NavigationState state = nav.GetNavigationState(entityId);
    
    // Check velocity limits
    float speed = state.Velocity.Length();
    if (speed > vehicleMaxSpeed * 1.1f) {
        core.ApiApp().SetTextOutput($"WARNING: Overspeed detected: {speed:F1} m/s");
    }
    
    // Check altitude
    if (state.Position.Y < minSafeAltitude) {
        core.ApiApp().SetTextOutput($"WARNING: Low altitude: {state.Position.Y:F1} m");
    }
    
    // Check sensor health
    if (!state.Sensors.GpsValid && !state.Sensors.SlamValid) {
        core.ApiApp().SetTextOutput("CRITICAL: No positioning sensors available");
        nav.TriggerEmergency(entityId);
    }
}

5. Use Proper Coordinate System Conversions

csharp
// Always set origin before converting coordinates
GeoCoordinate globalOrigin = new GeoCoordinate(37.7700, -122.4100, 0.0);

// Convert target from GPS to local for visualization
Vector3 targetLocal = nav.GeoToLocal(
    targetGPS.Latitude,
    targetGPS.Longitude,
    targetGPS.Altitude,
    globalOrigin.Latitude,
    globalOrigin.Longitude,
    globalOrigin.Altitude
);

// Convert local position back to GPS for logging
GeoCoordinate currentGPS = nav.LocalToGeo(
    state.Position.X,
    state.Position.Y,
    state.Position.Z,
    globalOrigin.Latitude,
    globalOrigin.Longitude,
    globalOrigin.Altitude
);

6. Implement Robust Error Recovery

csharp
void ErrorRecovery(int entityId, Exception error) {
    core.ApiApp().SetTextOutput($"Navigation error: {error.Message}");
    
    // Attempt recovery
    try {
        // Stop current motion
        nav.EmergencyStop(entityId);
        
        // Clear potentially corrupt waypoints
        nav.ClearWaypoints(entityId);
        nav.ClearObstacles(entityId);
        
        // Reset to manual mode
        nav.SetNavigationMode(entityId, NavigationMode.Manual);
        
        // Hover in place
        nav.SetManualControl(entityId, 0.0f, 0.0f, 0.0f, 0.5f);
        
        core.ApiApp().SetTextOutput("Recovery successful, manual control enabled");
    }
    catch (Exception recoveryError) {
        core.ApiApp().SetErrorOutput($"CRITICAL: Recovery failed: {recoveryError.Message}");
        // Last resort: trigger emergency procedures
        nav.TriggerEmergency(entityId);
    }
}

Performance Characteristics

Update Frequency

  • Recommended: 60 Hz (16.7ms) for drones
  • Minimum: 30 Hz (33ms) for ground vehicles
  • Maximum: 200 Hz (5ms) for high-performance systems

Latency

  • Sensor Fusion: <1ms
  • PID Control: <1ms
  • Waypoint Following: <2ms
  • Total Update: <5ms (typical)

Memory Footprint

  • Per Entity: ~2KB (struct-based)
  • No GC Allocations: Zero-allocation design
  • Scalability: 100+ entities on modern hardware

Remarks

SILVIA's Navigation API delivers production-grade autonomous vehicle guidance with multi-modal sensor fusion, advanced control systems, and zero-allocation performance. From delivery drones to tactical UAV swarms to autonomous rovers, Navigation provides the precision, reliability, and safety required for real-world autonomous systems.

Key Advantages:

  1. Multi-Modal Fusion - GPS, IMU, SLAM, Compass integration
  2. Advanced Modes - Terrain following, formation flight, hybrid navigation
  3. PID Control - Precise position and attitude control
  4. Zero-Allocation - Struct-based components, no GC pressure
  5. Safety First - Emergency procedures, battery monitoring, fail-safes
  6. Platform Agnostic - Works with any sensor hardware via simple integration

© Copyright Cognitive Code Corp. 2007-6

SILVIA is a registered Trademark of Cognitive Code Corp.

SILVIA is a registered Trademark of Cognitive Code Corp.