# AGENTS.md - Project Instructions

## Overall principles

**IMPORTANT - Auto-Reload**: Claude must ALWAYS reload and re-read this AGENTS.md file when resuming a conversation or when the conversation context is cleared/reset.
This ensure Claude has access to the most current project guidelines and avoids outdated instructions from previous conversations.

You are a senior C++ developer and expert in video game development.

## Project Overview

Solarus is a free and open-source 2D game engine written in C++ (C++17) designed for creating 16-bit style Action-RPG games. The engine runs games scripted in Lua, separating the performance-critical engine code (C++) from game logic (Lua scripts).

**Key Components:**
- `libsolarus` - Core C++ engine library
- `solarus-run` - CLI executable to run Solarus games (quests)
- Editor and Launcher - Qt6-based GUI applications (in separate directories)

**Quest Structure:** Games are called "quests" and are self-contained packages in `data/` directories or `data.solarus.zip` archives containing maps, sprites, tilesets, music, sounds, Lua scripts, and dialogs.

## Build Commands

### Configuration

Use CMake to configure the build. From the repository root:

```bash
mkdir build
cd build
cmake .. -G "Ninja"
```

**Important CMake Options:**
- `SOLARUS_USE_LUAJIT` - Use LuaJIT instead of vanilla Lua (default: ON)
- `SOLARUS_GL_ES` - Enable OpenGL ES implementation (default: OFF)
- `SOLARUS_TESTS_INSTALL` - Install quest testing tools (default: OFF)
- `CMAKE_INSTALL_PREFIX` - Installation directory prefix

### Building

From the build directory:

```bash
ninja
```

Generates `libsolarus` (shared library) and `solarus-run` (executable).

### Running Tests

```bash
ctest -V
```

Or use the test script:

```bash
./tools/run_tests.sh
```

Individual test executables are in `build/tests/` after building.

### Running a Quest

```bash
./solarus-run path/to/quest
```

The quest path can be:
- A directory containing a `data/` subdirectory
- A directory containing `data.solarus` or `data.solarus.zip` archive
- An archive file containing quest data

### Documentation

The documentation uses MkDocs. From the `doc/` directory:

```bash
# Install dependencies
pip install -r requirements.txt

# Serve locally
mkdocs serve

# Build to ./public
mkdocs build --site-dir public
```

## Architecture

### Core Components

The engine follows a layered, component-based architecture:

**Layer 1: Core System** ([src/core](src/core), [include/solarus/core](include/solarus/core))
- `MainLoop` - Central game loop managing timing and state
- `Game` - Running game instance with maps, hero, equipment, savegame
- `Map` - Individual game scenes/levels with entities and tilesets
- `ResourceProvider` - Caching system for loaded resources
- `CurrentQuest` - Quest/game data management
- `Savegame` - Player progress persistence
- `System` - Low-level platform abstractions

**Layer 2: Entity System** ([src/entities](src/entities), [include/solarus/entities](include/solarus/entities))
- `Entity` - Abstract base class for all map objects
- `Entities` - Manager using Quadtree spatial partitioning for efficient collision detection
- `Hero` - Player character with sophisticated state machine
- 60+ entity types: Enemies, NPCs, Tiles, Doors, Chests, Switches, etc.
- Layer-based rendering system for depth

**Layer 3: Hero State Machine** ([src/hero](src/hero), [include/solarus/hero](include/solarus/hero))
- `HeroState` - Abstract state base class
- 29+ concrete states: FreeState, RunningState, SwimmingState, JumpingState, SwordSwingingState, PushingState, CarryingState, CustomState, etc.
- `HeroSprites` - Hero animation management

**Layer 4: Movement System** ([src/movements](src/movements), [include/solarus/movements](include/solarus/movements))
- `Movement` - Base class for reusable movement behaviors
- Concrete movements: StraightMovement, CircleMovement, PathMovement, TargetMovement, PlayerMovement, RandomMovement, JumpMovement
- PathFinding with A* algorithm support

**Layer 5: Graphics System** ([src/graphics](src/graphics), [include/solarus/graphics](include/solarus/graphics))
- `Drawable` - Base drawable interface
- `Surface` - 2D texture/render target
- `Sprite` - Animated sprites with animation sets
- `TextSurface` - Text rendering
- `Shader` - Custom shader support
- `Video` - Window/screen management
- `Renderer` - Abstraction over SDL and OpenGL renderers
- Software pixel filters (HQ2x, HQ3x, Scale2x)

**Layer 6: Audio System** ([src/audio](src/audio), [include/solarus/audio](include/solarus/audio))
- `MusicSystem` - Background music management
- `Sound` - Sound effect playback
- `SoundBuffer` - Audio data caching
- Multiple format support via decoders: OggDecoder, ItDecoder (MOD tracker), SpcDecoder (SNES)

**Layer 7: Lua Integration** ([src/lua](src/lua), [include/solarus/lua](include/solarus/lua))
- `LuaContext` - Main Lua state manager bridging C++ to Lua
- `ExportableToLua` - Base class for C++ objects exposed to Lua
- Complete API modules: sol.main, sol.audio, sol.video, sol.input, sol.game, sol.map, sol.item, sol.sprite, sol.surface, etc.

### Execution Flow

```
main() → MainLoop construction
  ↓
MainLoop initializes: LuaContext, ResourceProvider, Video, Audio, Input
  ↓
Load quest properties and main.lua script
  ↓
MainLoop.run() - 60 FPS game loop:
  - Process input events
  - Update: Game → Map(s) → Entities → States/Movements
  - Check collisions (Quadtree spatial queries)
  - Render to screen
```

### Data Flow

```
Quest (data directory/archive)
  → MainLoop creates Game
    → Game loads Map(s)
      → Map contains Entities collection
        → Entities include Hero, Enemies, Tiles, etc.
          → Each entity has optional Movement and Sprites
            → Lua scripts control behavior
              → Render to Surfaces → Screen
```

### Design Patterns

- **State Pattern**: Hero behavior (29+ states)
- **Strategy Pattern**: Movement behaviors
- **Observer Pattern**: Event notifications (notify_* methods)
- **Spatial Indexing**: Quadtree for entity collision queries
- **Resource Caching**: ResourceProvider pattern
- **Bridge Pattern**: Lua/C++ integration via LuaContext

## Development Guidelines

### Code Organization

- **Engine code (C++)**: [src/](src/) and [include/solarus/](include/solarus/)
- **CLI tool**: [cli/](cli/)
- **Tests**: [tests/](tests/)
- **Third-party libraries**: [third_party/](third_party/) (snes_spc, glad, hqx)
- **Documentation**: [doc/](doc/)
- **Build configuration**: [cmake/](cmake/)

### Adding New Features

When adding features to the engine:

1. **C++ Implementation**: Add to appropriate layer in [src/](src/) and [include/solarus/](include/solarus/)
2. **Lua Bindings**: Expose to Lua in [src/lua/](src/lua/) if needed for quest scripting
3. **Tests**: Add unit tests in [tests/src/tests/](tests/src/tests/)
4. **Documentation**: Update Lua API docs in [doc/docs/lua-api/](doc/docs/lua-api/)

### Working with Entities

All map entities inherit from the `Entity` base class. Key lifecycle methods:
- `notify_created()` - Called when entity is added to map
- `update()` - Called every frame (60 FPS)
- `draw_on_map()` - Rendering callback
- `notify_collision()` - Collision detection
- `notify_destroying()` - Cleanup before removal

Entities are managed by the `Entities` class which uses a Quadtree for spatial partitioning. Always use the provided query methods rather than iterating all entities.

### Lua/C++ Bridge

The `LuaContext` class manages all Lua interactions. C++ classes exposed to Lua should:
- Inherit from `ExportableToLua<T>`
- Register their Lua methods in the appropriate `LuaContext::register_*_module()` function
- Use `LuaTools` helper functions for type conversions

### Testing

Tests are built using a custom testing framework. To add a test:
1. Create a `.cpp` file in [tests/src/tests/](tests/src/tests/)
2. Include `"tools/TestEnvironment.h"`
3. Tests are automatically discovered and run by CTest

## Repository Management

This repository uses the **Gitflow workflow**:

- `dev` - Development branch for next minor release
- `vX.Y` - Development branches for all `X.Y.*` patch releases
- `release-X.Y.Z` - Short-term branches that finalize releases
- `vX.Y.Z` - Tags for releases
- `master` - Contains all releases

**Important**: Version numbers do NOT strictly follow Semantic Versioning. Refer to the [migration guides](https://docs.solarus-games.org/tutorials/migration/introduction/) when upgrading.

## Platform-Specific Notes

### Windows (MSYS2)

See [compilation.MSYS2.md](compilation.MSYS2.md) for detailed Windows build instructions.

**Important:** Do NOT invoke `ninja` or `ctest` directly from a non-MSYS2 shell (Git Bash, PowerShell, cmd). The ucrt64 toolchain requires the MSYS2 environment for correct DLL resolution. Wrap all build commands with the MSYS2 shell launcher:

```bash
<MSYS2_INSTALL_DIR>/msys2_shell.cmd -ucrt64 -defterm -no-start -c "cd <BUILD_DIR> && ninja 2>&1"
```

> **Local setup:** If you are using an AI agent locally on Windows, create an `AGENTS.local.md` file (gitignored) with your machine-specific MSYS2 paths and build commands. See `AGENTS.local.md.example` or refer to the auto-reload note above.

### macOS

```bash
# Install dependencies via Homebrew
brew install cmake ninja sdl2 sdl2_image sdl2_ttf luajit lua@5.1 libvorbis libmodplug physfs glm openal-soft

# Configure for Apple Silicon
cmake -DSOLARUS_ARCH=arm64 ..

# Or for Intel x86_64 (requires x86_64 dependencies)
cmake -DSOLARUS_ARCH=x86_64 ..
```

## Key Dependencies

**Build Requirements:**
- CMake (3.10+)
- C++17 compiler (GCC 4.8.1+, Clang 3.4+)
- pkg-config

**Runtime Libraries:**
- SDL2 (2.0.18+), SDL2_image, SDL2_ttf
- OpenGL or OpenGL ES
- OpenAL
- Vorbisfile, Ogg
- ModPlug (0.8.8.4+)
- Lua 5.1 or LuaJIT 2.0 (LuaJIT recommended)
- PhysFS

**Embedded Libraries:**
- snes_spc - Nintendo SNES music decoder
- glad - OpenGL loader
- hqx - Graphics scaling filters

## Additional Resources

- Official website: https://www.solarus-games.org
- Documentation: https://docs.solarus-games.org
- API Reference: https://docs.solarus-games.org/lua-api/
