openstranded-map-tool 0.2.1

Convert Stranded II .s2 map files to .osmap (OpenStranded MAP) format
Documentation
// openstranded-map-tool — convert Stranded II .s2 maps to .osmap format
// Copyright (C) 2026  OpenStranded contributors
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

//! Convert parsed `.s2` data into the `.osmap` format.

use std::collections::HashMap;

use crate::types::*;

/// Blitz3D world-unit constant used to scale terrain vertices.
/// `ScaleEntity ter, Cworld_size, Cworld_height, Cworld_size`
const CWORLD_SIZE: f32 = 64.0;
/// Blitz3D terrain height constant.
const CWORLD_HEIGHT: f32 = 3200.0;

/// Parse a FRAP (Free Rotation And Position) extension value.
///
/// The original game stores `"f"` extensions with value `"y,pitch,roll"` where:
/// - `y`     — absolute Y position in Blitz3D world units
/// - `pitch` — pitch rotation in degrees
/// - `roll`  — roll rotation in degrees
///
/// Returns `(y_blitz3d, pitch_deg, roll_deg)` or `None` if parsing fails.
fn parse_frap_value(value: &str) -> Option<(f32, f32, f32)> {
    let parts: Vec<&str> = value.split(',').collect();
    if parts.len() >= 3 {
        let y = parts[0].trim().parse().ok()?;
        let pitch = parts[1].trim().parse().unwrap_or(0.0);
        let roll = parts[2].trim().parse().unwrap_or(0.0);
        Some((y, pitch, roll))
    } else {
        None
    }
}

/// Convert a parsed `.s2` map into an `.osmap` (engine convention).
///
/// # Coordinate conversion
///
/// Blitz3D terrain setup:
///   `CreateTerrain(ter_size)` — grid `0..ter_size` in both X and Z
///   `ScaleEntity ter, Cworld_size, Cworld_height, Cworld_size` — vertex spacing = 64 world units
///   `PositionEntity ter, -(64*ter_size/2), -(Cworld_height/2), -(64*ter_size/2)` — centre at origin
///
/// So `EntityX(h)` returns a **centred world coordinate** in the range `−ter_size×32 .. +ter_size×32`.
///
/// `.osmap` stores positions in **grid-cell units**:
///   - same orientation as the engine terrain mesh: +X right, +Z = north (= forward)
///   - X and Z range = `−ter_size/2 .. +ter_size/2` (grid cells, identical to engine's grid)
///   - Y = engine world Y (from `norm_to_world`)
///
/// Because the Blitz3D terrain is already centred, we simply divide by Cworld_size
/// to get grid-cell units.  No additional centering subtraction is needed,
/// and Z is NOT negated (both the original and the engine use +Z forward).
///
/// The engine scales grid-cell XZ to world units by multiplying with the
/// map's step factor (`step = 64.0 / terrain_size`).
/// For a 33×33 grid (terrain_size=32): step=2.0, world spans −32 .. +32.
pub fn s2_to_osmap(s2: S2Map, source_filename: &str) -> OpenStrandedMap {
    let terrain_size = s2.terrain_size;

    // Heightmap stored in natural row-major order: `[z * stride + x]`
    // = height at grid (x, z).  No Z flip — the terrain mesh and entities
    // both use the same +Z = north convention.
    let terrain = TerrainData {
        size: terrain_size,
        heights: s2.heights.clone(),
        seaground_level: -2.0,
    };

    let colormap = if s2.colormap_dim > 0 {
        Some(ColormapData {
            dim: s2.colormap_dim,
            pixels: s2.colormap.clone(),
        })
    } else {
        None
    };

    let grass = if !s2.grass.is_empty() {
        Some(GrassData {
            dim: s2.colormap_dim + 1,
            values: s2.grass.clone(),
        })
    } else {
        None
    };

    // ── Convert entities ────────────────────────────────────────────
    // Position conversion from .s2 (Blitz3D world units) to .osmap (grid‑cell units):
    //
    //   s2 EntityX()  returns centred world X  ∈ [−ter_size×32, +ter_size×32]
    //   → grid cell   osmap_x = s2_x / CWORLD_SIZE  ∈ [−ter_size/2, +ter_size/2]
    //
    //   Z is in the same orientation (both systems use +Z = north):
    //   osmap_z = s2_z / CWORLD_SIZE   (NO negation — both +Z = north)
    //
    //   Y is converted from Blitz3D world Y to engine world Y:
    //   engine_y = (s2_y / CWORLD_HEIGHT + 0.5 − 0.35) × 60.0
    //
    // For objects: the .s2 does not store Y; height is sampled from the
    // unflipped heightmap using original s2_x/s2_z, then converted.
    let mut entities: Vec<MapEntity> = Vec::new();
    let engine_y_from_s2 = |s2_y: f32| -> f32 {
        (s2_y / CWORLD_HEIGHT + 0.5 - 0.35) * 60.0
    };

    for obj in &s2.objects {
        // Default Y from terrain height (objects don't store Y in .s2)
        let h_raw = sample_height(&terrain.heights, terrain_size, obj.x, obj.z);
        let mut y = (h_raw - 0.35) * 60.0;

        // Collect extensions for this object
        let mut extensions = extract_extensions_for_parent(&s2.extensions, 1, obj.id);

        // Apply FRAP (Free Rotation And Position) if present.
        // The "f" extension overrides the object's Y position and rotation
        // (pitch, roll) — see load_map_extensions in e_load_map.bb.
        // After applying, the raw "f" extension is removed so the data is
        // not duplicated (position + rotation fields are the source of truth).
        let mut rotation_pitch = 0.0;
        let mut rotation_roll = 0.0;
        if let Some(frap_val) = extensions.get("f") {
            if let Some((frap_y, pitch_deg, roll_deg)) = parse_frap_value(frap_val) {
                // Convert Y from Blitz3D world units to engine coordinates
                y = engine_y_from_s2(frap_y);
                rotation_pitch = deg_to_rad(pitch_deg);
                rotation_roll = deg_to_rad(roll_deg);
            }
        }
        extensions.remove("f"); // applied above — no longer needed as raw extension

        entities.push(MapEntity {
            class: "object".into(),
            type_id: obj.typ,
            id: obj.id,
            position: (obj.x / CWORLD_SIZE, y, obj.z / CWORLD_SIZE),
            rotation_yaw: deg_to_rad(obj.yaw),
            rotation_pitch,
            rotation_roll,
            health: obj.health,
            health_max: obj.health_max,
            amount: 0,
            parent_id: 0,
            parent_class: 0,
            links: vec![],
            build_progress: 0,
            states: vec![],
            script: None,
            unit_data: None,
            extensions,
        });
    }

    for unit in &s2.units {
        let y = engine_y_from_s2(unit.y);
        entities.push(MapEntity {
            class: "unit".into(),
            type_id: unit.typ,
            id: unit.id,
            position: (unit.x / CWORLD_SIZE, y, unit.z / CWORLD_SIZE),
            rotation_yaw: deg_to_rad(unit.yaw),
            rotation_pitch: 0.0,
            rotation_roll: 0.0,
            health: unit.health,
            health_max: unit.health_max,
            amount: 0,
            parent_id: 0,
            parent_class: 0,
            links: vec![],
            build_progress: 0,
            states: vec![],
            script: None,
            unit_data: Some(UnitData {
                hunger: unit.hunger,
                thirst: unit.thirst,
                exhaustion: unit.exhaustion,
                ai_center_x: unit.ai_center_x / CWORLD_SIZE,
                ai_center_z: unit.ai_center_z / CWORLD_SIZE,
                day_timer: 0.0,
            }),
            extensions: extract_extensions_for_parent(&s2.extensions, 2, unit.id),
        });
    }

    for item in &s2.items {
        let y = engine_y_from_s2(item.y);
        entities.push(MapEntity {
            class: "item".into(),
            type_id: item.typ,
            id: item.id,
            position: (item.x / CWORLD_SIZE, y, item.z / CWORLD_SIZE),
            rotation_yaw: deg_to_rad(item.yaw),
            rotation_pitch: 0.0,
            rotation_roll: 0.0,
            health: item.health,
            health_max: 0.0,
            amount: item.count,
            parent_id: item.parent_id,
            parent_class: item.parent_class,
            links: vec![],
            build_progress: 0,
            states: vec![],
            script: None,
            unit_data: None,
            extensions: extract_extensions_for_parent(&s2.extensions, 3, item.id),
        });
    }

    for info in &s2.infos {
        let y = engine_y_from_s2(info.y);
        entities.push(MapEntity {
            class: "info".into(),
            type_id: info.typ as u32,
            id: info.id,
            position: (info.x / CWORLD_SIZE, y, info.z / CWORLD_SIZE),
            rotation_yaw: deg_to_rad(info.yaw),
            rotation_pitch: 0.0,
            rotation_roll: 0.0,
            health: 0.0,
            health_max: 0.0,
            amount: 0,
            parent_id: 0,
            parent_class: 0,
            links: vec![],
            build_progress: 0,
            states: vec![],
            script: Some(info.vars.clone()),
            unit_data: None,
            extensions: extract_extensions_for_parent(&s2.extensions, 4, info.id),
        });
    }

    // Build environment map
    let mut environment = HashMap::new();
    environment.insert("day".into(), s2.env_vars.day.to_string());
    environment.insert("hour".into(), s2.env_vars.hour.to_string());
    environment.insert("minute".into(), s2.env_vars.minute.to_string());
    environment.insert("freezetime".into(), s2.env_vars.freezetime.to_string());
    environment.insert("skybox".into(), s2.env_vars.skybox);
    environment.insert("multiplayer".into(), s2.env_vars.multiplayer.to_string());
    environment.insert("climate".into(), s2.env_vars.climate.to_string());
    environment.insert("music".into(), s2.env_vars.music);
    let briefing = s2.env_vars.briefing.clone();
    let decoded_pw = s2.password.decoded.clone();
    environment.insert("briefing".into(), s2.env_vars.briefing);
    environment.insert("fog_r".into(), s2.env_vars.fog[0].to_string());
    environment.insert("fog_g".into(), s2.env_vars.fog[1].to_string());
    environment.insert("fog_b".into(), s2.env_vars.fog[2].to_string());
    environment.insert("fog_mode".into(), s2.env_vars.fog[3].to_string());
    if !decoded_pw.is_empty() {
        environment.insert("password".into(), decoded_pw);
    }

    // Player spawn Y at terrain centre (computed before `terrain` is moved)
    let spawn_pos = spawn_center_engine_y(terrain_size, &terrain.heights);

    // Collect scripts from infos and briefing
    let mut scripts: Vec<ScriptData> = Vec::new();
    for info in &s2.infos {
        if !info.vars.is_empty() {
            scripts.push(ScriptData {
                text: info.vars.clone(),
                entity_id: info.id,
            });
        }
    }
    if !briefing.is_empty() {
        scripts.push(ScriptData {
            text: briefing,
            entity_id: 0,
        });
    }

    OpenStrandedMap {
        meta: MapMeta {
            name: source_filename.trim_end_matches(".s2").to_string(),
            engine_version: env!("CARGO_PKG_VERSION").to_string(),
            map_version: "0.2.0".to_string(),
            source_file: source_filename.to_string(),
            s2_header: Some(s2.header),
            created_at: String::new(),
        },
        terrain,
        entities,
        player_spawn: Some(PlayerSpawn {
            position: spawn_pos,
            rotation_yaw: 0.0,
        }),
        environment,
        colormap,
        grass,
        password: s2.password.decoded.clone(),
        scripts,
    }
}

/// Compute player-spawn position at terrain centre.
/// Returns `(0, ground_y, 0)` in grid-cell coords — engine adds eye height.
fn spawn_center_engine_y(terrain_size: u32, heights: &[f32]) -> (f32, f32, f32) {
    let mid = terrain_size as usize / 2;
    let stride = (terrain_size + 1) as usize;
    let centre_h = heights.get(mid * stride + mid).copied().unwrap_or(0.35);
    let y = (centre_h - 0.35) * 60.0; // norm_to_world
    (0.0, y, 0.0) // ground Y — engine adds EYE_HEIGHT
}

/// Sample height from the heightmap at Blitz3D world position (x, z).
///
/// `x` and `z` are Blitz3D centred world coordinates (range `±ter_size×32`).
/// We convert to grid indices by dividing by `CWORLD_SIZE = 64` and adding
/// half_grid (shifting from centred to 0‑based grid coordinates).
fn sample_height(heights: &[f32], terrain_size: u32, x: f32, z: f32) -> f32 {
    if heights.is_empty() {
        return 0.0;
    }
    let half = terrain_size as f32 / 2.0;
    let gx = (x / CWORLD_SIZE + half).clamp(0.0, terrain_size as f32);
    let gz = (z / CWORLD_SIZE + half).clamp(0.0, terrain_size as f32);
    let ix = gx.round() as usize;
    let iz = gz.round() as usize;
    let idx = iz * (terrain_size as usize + 1) + ix;
    if idx < heights.len() {
        heights[idx]
    } else {
        0.0
    }
}

/// Convert degrees to radians.
fn deg_to_rad(deg: f32) -> f32 {
    deg * std::f32::consts::PI / 180.0
}

/// Extract extensions for a given parent class+id as key-value map.
fn extract_extensions_for_parent(
    extensions: &[S2Extension],
    parent_class: u8,
    parent_id: u32,
) -> HashMap<String, String> {
    let mut map = HashMap::new();
    for ext in extensions {
        if ext.parent_class == parent_class && ext.parent_id == parent_id {
            let key = if ext.key.is_empty() {
                format!("mode_{}", ext.mode)
            } else {
                ext.key.clone()
            };
            map.insert(key.clone(), ext.value.clone());
            if !ext.stuff.is_empty() {
                map.insert(format!("{}_stuff", key), ext.stuff.clone());
            }
        }
    }
    map
}