Skip to content

Lua sections need revision: This page contains removed v5 APIs or old runtime examples. Do not use its Lua examples for current development. Start with Platform v1.

Core Engine Lifecycle & Main Loop Deep-Dive

This document provides a comprehensive breakdown of the Cataclysm: Cleanwater Bomb (CCB) game engine control flow—from process bootstrapping, multi-phase content loading, world initialization to the per-turn main loop and atomic persistence.


1. Global Lifecycle Sequence Diagram

sequenceDiagram
    autonumber
    participant Boot as 🚀 main.cpp (Bootstrap)
    participant Loader as 📦 DynamicDataLoader
    participant LuaVM as 🌙 Lua 0.1 Runtime
    participant Game as 🎮 game (Singleton)
    participant World as 🗺️ map / overmap
    participant UI as 🖥️ UI / Render Pipeline

    Note over Boot: 1. Bootstrap & Subsystem Initialization
    Boot->>Boot: Init logger, SDL2/Curses, i18n, CLI args
    Boot->>Loader: Load core data & active mod definitions
    Loader->>LuaVM: Discover and transactionally stage main.lua

    Note over Game: 2. World Initialization & Game Load
    Boot->>Game: game::init() / Load saved game
    Game->>World: Load overmap & 3D submap grid
    Game->>LuaVM: Emit "game_load" lifecycle event

    Note over Game,UI: 3. Core Main Turn Loop
    loop Every Turn / Action (game::process_turn)
        UI->>Game: Capture user input (input_manager)
        Game->>Game: Dispatch player action (handle_action) & consume AP
        Game->>Game: Advance active entities (Creatures, NPCs, Monsters)
        Game->>World: Environment simulation (finite water, weather, scents)
        Game->>LuaVM: Broadcast turn events & evaluate Hook interceptors
        Game->>UI: Request UI frame refresh (ui_adaptor::redraw)
    end

    Note over Game: 4. Persistence & Clean Shutdown
    Game->>World: Serialize map & entity states (atomic savegame write)
    Game->>LuaVM: Trigger "game_save" and Lua VM cleanup
    Game->>Boot: Release SDL2, audio, and threadpool resources

2. Phase 1: Bootstrap & Multi-Phase Loading Pipeline

Execution begins in src/main.cpp: 1. Low-Level Runtimes: Initialize debug.cpp logging, crash handlers, graphics/audio contexts (SDL2/OpenGL or Curses), and gettext translations. 2. Content Ingestion: - DynamicDataLoader parses core and mod definitions in topological order. - The Lua 0.1 VM initializes namespaces (game.*, map.*, player.*, events.*). - Mod main.lua entry points are executed in a staged transactional sandbox with atomic rollback on syntax/semantic errors.


3. Phase 2: Action-Point Turn Loop (game::process_turn)

CCB is a semi-discrete turn-based simulation driven by Action Points (AP / Moves):

void game::do_turn() {
    while( is_game_running() ) {
        if( avatar.get_moves() <= 0 ) {
            handle_user_input(); // Block for player action
        }

        avatar.process_turn(); // Tick avatar stats, pain, stamina

        for( monster &critter : active_monsters ) {
            critter.process_turn();
            if( critter.get_moves() > 0 ) {
                critter.move(); // Execute monster AI
            }
        }

        map.process_fields();        // Fire, smoke, gas diffusion
        weather.process();           // Precipitation and wind
        finite_water.simulate_step();// Fluid dynamics step

        catalua_events::emit_turn_end( calendar::turn );
        ui_adaptor::redraw_all();
    }
}

4. Phase 3: Physics & Environmental Simulation

  • Finite Water Dynamics: Fluid mass is conserved. Water flows across gradients, pooling in depressions, and responding to drainage and pumps.
  • 3D Shadowcasting: Calculates illumination and line-of-sight across 3D octants with multi-$z$-level raycast propagation.

5. Phase 4: Atomic Persistence & Cleanup

  • Atomic File Writes: Save files are written to .tmp scratch files and atomically renamed only after CRC verification.
  • Lua State Serialization: Custom mod state tables stored via state.character or state.world are serialized into the save stream.