| CRM64Pro GDK v0.15.0 A free cross-platform game development kit built on top of SDL 3.0

Loading...
Searching...
No Matches
Scene module

## Description

Advanced 2D scene and game world management system [v26.02.0].

Logic module containing the Scene subsystems: the layers and core.

### Overview

The Scene module is a comprehensive 2D world management system designed for building complex, high-performance game environments. It acts as the backbone of the game loop, featuring a unified layer architecture that seamlessly integrates standard Tile Maps, high-performance Entity/Object layers, and dynamic Image layers into a single cohesive rendering and logic pipeline.

Fully compatible with the industry-standard Tiled level editor (TMX format), it bridges the gap between level design and runtime execution. Developers can visually construct their worlds while leveraging advanced engine features such as Hybrid Entity-Grid Architecture (HEGA), object factory-driven entity creation, and authoritative world-state persistence back to TMX/TSX resources.

### Key features

- Unified Layer System: Mix Tile, Object, Image, and Custom layers in any Z-order configuration with per-layer cameras and rendering rules.
- HEGA System: A Hybrid Entity-Grid Architecture providing high-performance spatial partitioning for managing and querying thousands of active game objects.
- Camera & Cinematic Control: Built-in camera systems supporting dead-zones, target following, smooth interpolation, and sub-pixel precision rendering.
- Thread-Safe Lifecycle: Robust deferred object addition and removal (Command Buffer pattern).
- Tiled Integration: Native support for TMX maps, TSX tilesets, Animations, Collections, and Templates.
- Game Runtime API: Object factory integration, spatial object management, and fast region queries for gameplay logic.
- Template Support: TMX object templates (.tx) are supported for loading and saving, including external tileset references.
- Rotation-Aware Shapes: Tile and geometric object shapes support rotated AABB, precise rotated hit tests, and rotated debug rendering.
- Flexible Scrolling: Per-layer parallax scrolling, auto-scrolling, and infinite looping with axis-aware clamp behavior on repeat axes.
- Trigger System: Native object trigger zones with enter/stay/exit events, cross-layer checks, type-hash filtering, and cooldown support.
- Unified Debug Overlays: Engine-level debug flags for object AABB, trigger zones, tile cell grid, and camera dead-zone visualization.
- Event Driven: Comprehensive callback system (onUpdate, onRender, trigger callbacks) for custom game logic.
- Asset Management: Seamless loading from disk or encrypted CDC archives.
- World Persistence: Save live world modifications back to TMX (and CDC) to preserve runtime state changes.
- Extensible: Support for user-defined layers via class inheritance and runtime injection (addLayer).

### Trigger callbacks

Trigger events are dispatched in three scopes, in this order:

1. Object scope: `SceneObject::setOnTriggerEvent()`
2. Layer scope: `SceneLayerObject::setOnTriggerEvent()`
3. Global scope: `Scene::setOnTriggerEvent()`

Use object scope for local object behavior, layer scope for domain-level systems, and global scope for cross-cutting systems (analytics, quest bus, debug overlays).

### Layer architecture

The engine supports three distinct layer types, all inheriting from a common base:

Tile Layers | Grid-based mapping. Supports multiple tilesets, animations, and efficient rendering. Ideal for terrain and static environments.
Object Layers (HEGA) | Advanced entity management system. Uses HEGA spatial hashing for ultra-fast region queries, frustum culling, and precise collision detection. Supports geometric shapes, triggers, and dynamic visual sprites.
Image Layers | Single-image rendering. Perfect for parallax backgrounds, skies, or foreground overlays. Supports tiling and scrolling.
Custom Layers | User-defined rendering and logic. Extend the engine by inheriting from any layer type and implementing custom behaviors.

### Thread safety

The Scene is designed for modern, multi-threaded game architectures:

- Object Management: `addObject()` and `closeObject()` are thread-safe and use an internal Command Buffer. Requests are queued under a high-performance lock and applied at a safe synchronization point at the end of each layer's update logic.
- Iterator Safety: Because structural changes (adding/removing objects) are deferred, it is perfectly safe to spawn or destroy entities from within `update()` callbacks or collision queries without fear of iterator invalidation.
- Logic/Render Separation: The internal state is synchronized to allow rendering to occur while the next logic frame is being processed (when `iMTFriendly` is enabled).

### TMX compatibility

The Scene is designed for compatibility with Tiled (TMX format).

TMX Version | v1.0 to v1.10 (Orthogonal orientation, Right-Down render order).
Data encoding | CSV, Base64 (uncompressed or zlib compressed).
Global settings | 'infinite' and 'backgroundcolor' are ignored.
C64SCENE Extensions | Embedded map (v3.0). Layer IDs start with 1. Custom properties (c64te_*) configure engine-specific features.
Templates | Supports Tiled object templates (.tx) with optional external <tileset source="..."> and template instances in TMX object layers.
Object rotation | Tile and geometric objects support rotation (including negative angles), cached rotated AABB, precise rotated hit-testing, and rotated shape rendering.

#### Layer Z-Order and IDs

There is a fundamental difference between Tiled and the CRM64Pro Scene regarding layer ordering:

- In Tiled: The render order is determined by the node sequence in the TMX file (the order in the layer list). The `id` attribute is purely informational.
- In CRM64Pro: The render order is determined strictly by the numerical Layer ID. The engine renders Layer 1, then Layer 2, and so on.

Important: When designing in Tiled, ensure that your layers' `id` attributes follow an increasing numerical sequence that matches your desired visual stacking (e.g., Background=1, Ground=2, Foreground=3). If the TMX file contains non-sequential IDs or IDs that do not match the XML node order, the render order in the engine will differ from Tiled.

#### Supported TMX structure

- <map>
  - <editorsettings> (ignored)
  - <group> (ignored)
  - <properties> [0,1]
  - <tileset> [1,n]
    - <tileoffset> (ignored)
    - <grid> (ignored)
    - <terraintype> (ignored)
    - <transformations> (ignored)
    - <wangsets> (ignored)
    - <image>
    - <tile>
      - <properties> (ignored)
      - <image>
      - <animation>
      - <frame>
  - <layer> [1,n]
    - <chunk> (ignored)
    - <data> (CSV/Base64 supported)
    - <tile>
  - <objectgroup>
    - <text> (ignored)
    - <object>
    - <ellipse>
    - <point>
    - <polygon>
    - <polyline>
  - <imagelayer>

### Manager type

This is a standard manager: objects are not shared and must be unique using its name as the key. You cannot create an object with the same name as another one already created.

### Naming security

Resource names are restricted to prevent collisions with system assets. The characters '#' and '@' are reserved for internal engine use. Any attempt to create or rename a resource starting with these characters will be rejected (returning a negative error code).

### Best practices

- Use parallax scrolling with grouped layers to create depth effects in side-scrolling games
- Enable smooth scroll rendering for fluid movement in scrolling games
- Use the onUpdateEnd and onRenderEnd events to add custom game logic per layer
- Use unified debug overlays (tile cell grid, object AABB, trigger zones, camera dead-zone) during development
- Store tilesets in CDC archives for organized asset management
- When using Tiled, ensure maps use orthogonal orientation and right-down render order
- Access the manager exclusively through Main::ISceneMgr()

Note
  The Scene Manager is a singleton, automatically created once Main is instantiated. You can get a reference to this manager using Main::ISceneMgr() method.
  The Scene Manager is automatically released when Main::Terminate() is called. At this time, any resource still loaded will be released, avoiding resource leaks.

## Topics
| Scene Layer base
| Data classes for Scene Layer management [v26.02.0].
| Scene
| Scene objects for 2D tile-based game development.
| Scene Manager
| Scene Manager for lifecycle and asset management.

## Classes
struct | CRM64Pro::SceneCameraParams
| Camera configuration parameters. More...

## Enumerations
enum | CRM64Pro::eSceneLayerFeature : Uint32 { CRM64Pro::SLF_DISABLE = 0 , CRM64Pro::SLF_REPEATX = 1 , CRM64Pro::SLF_REPEATY = 2 , CRM64Pro::SLF_UPDATE = 8 , CRM64Pro::SLF_RENDER = 32 , CRM64Pro::SLF_SMOOTHSCROLL = 64 , CRM64Pro::SLF_PAUSE = 256 }
| Features for Scene layers. More...
enum | CRM64Pro::eSceneDebugOverlay : Uint32 { CRM64Pro::SDO_DISABLE = 0 , CRM64Pro::SDO_OBJECT_AABB = 1 , CRM64Pro::SDO_TILE_CELLGRID = 2 , CRM64Pro::SDO_TRIGGER_ZONES = 4 , CRM64Pro::SDO_CAMERA_DEADZONE = 8 }
| Scene unified debug overlay flags. More...
enum | CRM64Pro::eSceneTileSetType { CRM64Pro::STST_NULL = -1 , CRM64Pro::STST_TILESET = 0 , CRM64Pro::STST_COLLECTION = 1 }
| Specifies how the TileSet is organized. More...
enum | CRM64Pro::eSceneStorageMode { CRM64Pro::SSM_DISK , CRM64Pro::SSM_CDC , CRM64Pro::SSM_INTERNAL }
| Specifies where the tileset data is physically stored. More...
enum | CRM64Pro::eSceneShapeType { CRM64Pro::SST_RECTANGLE = 0 , CRM64Pro::SST_ELLIPSE , CRM64Pro::SST_POINT , CRM64Pro::SST_POLYGON , CRM64Pro::SST_POLYLINE , CRM64Pro::SST_TILE }
| Specifies the geometric shape type of a SceneObject. More...
enum | CRM64Pro::eSceneLayerType { CRM64Pro::SLT_EMPTY = 0 , CRM64Pro::SLT_TILE , CRM64Pro::SLT_OBJECT , CRM64Pro::SLT_IMAGE , CRM64Pro::SLT_USER_START = 8 }
| Specifies the type of a Scene layer. More...
enum | CRM64Pro::eSceneObjectRenderOrder { CRM64Pro::SORO_INDEX = 0 , CRM64Pro::SORO_TOPDOWN , CRM64Pro::SORO_FEET , CRM64Pro::SORO_Z , CRM64Pro::SORO_Z_FEET }
| Specifies object rendering order policy for SceneLayerObject. More...
enum | CRM64Pro::eSceneTriggerEventType : Uint32 { CRM64Pro::STET_ENTER = 0 , CRM64Pro::STET_STAY , CRM64Pro::STET_EXIT }
| Trigger event type. More...
enum | CRM64Pro::eSceneCameraMode : Uint32 { CRM64Pro::SCM_MANUAL = 0 , CRM64Pro::SCM_AUTOSCROLL , CRM64Pro::SCM_SNAP , CRM64Pro::SCM_SMOOTH , CRM64Pro::SCM_DEADZONE , CRM64Pro::SCM_OFFSET }
| Camera controller modes for a Scene layer. More...

## Enumeration Type Documentation

## ◆ eSceneLayerFeature

enum CRM64Pro::eSceneLayerFeature : Uint32

Features for Scene layers.

These flags can be combined using bitwise operators.

Enumerator
SLF_DISABLE | Disable layer and remove all features. Default value.
SLF_REPEATX | Enable the layer image to be repeated along the X-axis.
SLF_REPEATY | Enable the layer image to be repeated along the Y-axis.
SLF_UPDATE | Enable the updating feature. Check update() for further details.
SLF_RENDER | Enable the rendering feature. Enabling this flag also enables ::SLF_UPDATE. Disabling render does not disable update.
SLF_SMOOTHSCROLL | Enable the smooth rendering feature. Check render() for further details.
SLF_PAUSE | Pause the layer. Engine-driven movement/interpolation are frozen for this layer. Scene::update()/render() should still be called to keep global timing and rendering flow consistent.

## ◆ eSceneDebugOverlay

enum CRM64Pro::eSceneDebugOverlay : Uint32

Scene unified debug overlay flags.

Enumerator
SDO_DISABLE | No debug overlay.
SDO_OBJECT_AABB | Draw object AABBs for rendered object layers.
SDO_TILE_CELLGRID | Draw tile cell grid overlay for rendered tile layers.
SDO_TRIGGER_ZONES | Draw trigger zone bounds for rendered object layers.
SDO_CAMERA_DEADZONE | Draw camera dead-zone rectangle for rendered dead-zone camera layers.

## ◆ eSceneTileSetType

enum CRM64Pro::eSceneTileSetType

Specifies how the TileSet is organized.

Enumerator
STST_NULL | Default value when no TileSet is loaded.
STST_TILESET | A standard TileSet based on a Tile (tileset mode).
STST_COLLECTION | A collection of tiles where each tile is a Tile (no tileset mode).

## ◆ eSceneStorageMode

enum CRM64Pro::eSceneStorageMode

Specifies where the tileset data is physically stored.

Enumerator
SSM_DISK | Standard file on the physical disk.
SSM_CDC | Inside a CRM64Pro::ArchiveCDC file.
SSM_INTERNAL | Created from an in-memory CRM64Pro object (Tile or Image).

## ◆ eSceneShapeType

enum CRM64Pro::eSceneShapeType

Specifies the geometric shape type of a SceneObject.

Enumerator
SST_RECTANGLE | Default rectangular area defined by x, y, width, height.
SST_ELLIPSE | Ellipse or circle area.
SST_POINT | Single point with width=0 and height=0.
SST_POLYGON | Closed polygon shape defined by vertices.
SST_POLYLINE | Open polyline path defined by vertices.
SST_TILE | Object has a GID and is rendered using a tile from a tileset.

## ◆ eSceneLayerType

enum CRM64Pro::eSceneLayerType

Specifies the type of a Scene layer.

Enumerator
SLT_EMPTY | Layer slot exists but has no type-specific data assigned.
SLT_TILE | Layer contains tile data (SceneLayerTile).
SLT_OBJECT | Layer contains game objects (SceneLayerObject).
SLT_IMAGE | Layer displays an image (SceneLayerImage).
SLT_USER_START | Start of user-defined layer types.

## ◆ eSceneObjectRenderOrder

enum CRM64Pro::eSceneObjectRenderOrder

Specifies object rendering order policy for SceneLayerObject.

Enumerator
SORO_INDEX | Draw by insertion/index order.
SORO_TOPDOWN | Draw by top Y coordinate (TMX topdown compatible).
SORO_FEET | Draw by bottom Y (y + height).
SORO_Z | Draw by integer property "c64te_z" (or "z"), then index.
SORO_Z_FEET | Draw by z first, then feet (y + height).

## ◆ eSceneTriggerEventType

enum CRM64Pro::eSceneTriggerEventType : Uint32

Trigger event type.

Enumerator
STET_ENTER | Fired when overlap starts.
STET_STAY | Fired once after configured delay while overlap remains.
STET_EXIT | Fired when overlap ends.

## ◆ eSceneCameraMode

enum CRM64Pro::eSceneCameraMode : Uint32

Camera controller modes for a Scene layer.

Camera processing is evaluated during Scene::update() and applied to the selected layer position. The selected layer remains the "camera authority" and linked parallax layers continue to be updated.

Note
  Target-based modes require a valid camera target (setCameraTarget()). ::SCM_AUTOSCROLL does not require target binding.

Enumerator
SCM_MANUAL | Manual mode. Camera is controlled only through setLayerPosition()/setCameraPosition().
SCM_AUTOSCROLL | Automatic scrolling by velocity (SceneCameraParams::pAutoScrollSpeed), then optional damping/clamping.
SCM_SNAP | Instant target tracking each logic tick (no damping, no deadzone behavior).
SCM_SMOOTH | Damped target tracking using SceneCameraParams::fDamping.
SCM_DEADZONE | Damped deadzone tracking; deadzone is centered on SceneCameraParams::pScreenAnchor.
SCM_OFFSET | Damped tracking plus dynamic offset callback (mouse/stick/cinematic bias).