CRM64Pro GDK v0.20.0
A free cross-platform game development kit built on top of SDL 3.0
Loading...
Searching...
No Matches
Scene modules

Description

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

Scene subsystems and shared Scene API types.

The parent Scene group contains shared enums and small data structures used by Scene, SceneMgr and Scene layers. Concrete classes are documented in the Scene Layer, Scene, and Scene Manager subgroups.

Overview

The Scene module is the 2D world runtime advanced with Scene::update() and drawn with Scene::render() from the application's main-thread game loop. Its unified layer architecture integrates tile maps, high-performance entity/object layers, and dynamic image layers into one 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.
  • Deferred object lifecycle: Thread-safe addObject() and closeObject() requests are applied at frame synchronization points.
  • 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 independently filtered shape and name debug overlays.
  • 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.
  • Debug Overlays: Independent Scene/layer flags plus per-object-type AABB, shape, name, and trigger visualization.
  • Event Driven: Comprehensive callback system (onUpdate, onRender, trigger callbacks) for custom game logic.
  • Asset Management: Seamless loading from disk or CDC archives, including CDCv2 archives using lightweight confidentiality / non-authenticated encrypted storage.
  • 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).

Particle collision callbacks

Register Scene::setOnParticleCollisionEvent() when particle impacts affect gameplay. The emitter must bind an object collision layer, and target objects must enable c64scn_blocks_particles. For a C64Portal, this role is active only while the portal is closed. First-lifetime object hits are collected only while the callback is set and are dispatched after simulation as one event per emitter and target object per update. Decorative particles pay no hit-collection cost when the callback is empty.

Layer architecture

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

Tile LayersGrid-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 fast region queries, frustum culling, and precise collision detection. Supports geometric shapes, triggers, and dynamic visual sprites.
Image LayersSingle-image rendering. Perfect for parallax backgrounds, skies, or foreground overlays. Supports tiling and scrolling.
Custom LayersUser-defined rendering and logic. Extend the engine by inheriting from any layer type and implementing custom behaviors.

Threading

Scene frame processing specializes the default Threading conventions and uses the main thread:

  • Frame calls: Scene::update() and Scene::render() must run sequentially on the main thread. They must not overlap each other or another call on the same Scene.
  • Internal tasks: Scene::update() can batch independent particle emitters on internal workers. Workers simulate only frozen emitter-local state. Scene layers, object transforms, collision bindings, callbacks and rendering remain main-thread work. The call waits for every worker before returning.
  • 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.
  • Other access: Layer and object state, queries, callbacks, and borrowed pointers are main-thread-only unless their API explicitly states otherwise.

TMX compatibility

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

TMX Versionv1.0 to v1.10 (Orthogonal orientation, Right-Down render order).
Data encodingCSV, Base64 (uncompressed or zlib compressed).
Global settingsinfinite is ignored. backgroundcolor is loaded, rendered within the Scene viewport, and preserved when saving.
C64SCENE ExtensionsNative map format v4.0. Layer IDs start with 1. Custom properties (c64scn_*) configure scene metadata, persisted lighting, light/occluder objects, and effects. v3.0 did not support lighting or effects, EditorC64 automatically upgrades v3 CDC maps to v4.
TemplatesSupports Tiled object templates (.tx) with optional external <tileset source="..."> and template instances in TMX object layers.
Object rotationTile and geometric objects support rotation (including negative angles), cached rotated AABB, precise rotated hit-testing, and rotated shape rendering.

CDC and native C64SCENE loads are strict and atomic: unsupported render order or missing required content closes the partial Scene and returns an error. Ordinary external TMX files remain lenient and may return a Scene while reporting skipped content as warnings.

C64SCENE v4 properties

All native properties use the c64scn_ prefix. They are stored in the <properties> node of the indicated TMX element. Runtime SceneObject properties are strings. On save, recognized C64SCENE properties use TMX bool, int, float, or color types where applicable; unrecognized custom properties remain strings.

TMX scopePropertyDescription
Mapc64scn_versionRequired native format marker; v4.0 uses value 40.
Mapc64scn_nameScene name override.
Mapc64scn_creation_dateCreation timestamp metadata.
Mapc64scn_modification_dateModification timestamp metadata.
Mapc64scn_viewport_x, c64scn_viewport_yViewport origin in screen pixels.
Mapc64scn_viewport_width, c64scn_viewport_heightViewport size in pixels.
Mapc64scn_lighting_ambientAmbient light colour as #RRGGBBAA.
Mapc64scn_lighting_ambient_intensityAmbient intensity from 0.0 to 1.0.
Mapc64scn_lighting_enabledEnables Scene lighting interpretation and rendering.
Mapc64scn_effects_enabledPersisted effects enable state.
Layerc64scn_position_x, c64scn_position_yLayer world position.
Layerc64scn_speed_x, c64scn_speed_yAuto-scroll speed per axis.
Layerc64scn_autoscrollEnables automatic camera scrolling.
Layerc64scn_updateEnables logical updates when nonzero; accepted on load only.
Layerc64scn_smoothscrollEnables smooth scroll rendering.
Layerc64scn_pausePauses layer updates.
TileSetc64scn_alphamodTileSet image alpha modulation; accepted on load only.
Tile layerc64scn_cellgridcolorDebug cell-grid colour in 0xRRGGBBAA form.
Object layerc64scn_spatialgridcellsizeHEGA spatial-grid cell size in pixels.
Object layerc64scn_draworder_modeObject render order: index, topdown, feet, z, or z_feet.
Objectc64scn_shape_colorGeometric debug colour as #RRGGBBAA. It colours the optional object shape overlay and does not tint a particle effect.
Objectc64scn_zInteger depth key for z and z_feet object-layer ordering. For a C64Particle, it orders the complete Scene object and its effect.
Object (C64Particle)c64scn_particleNamed C64_PARTICLE asset used to clone an independent runtime emitter owned by the object. Takes precedence over preset properties.
Object (C64Particle)c64scn_particle_presetBuilt-in preset template used only when no particle asset is set.
Object (C64Particle)c64scn_particle_autoplay, c64scn_particle_followControls automatic playback and whether the emitter follows the object.
Object (C64Particle)c64scn_particle_offset_x, c64scn_particle_offset_yAdds a world-pixel offset to the object's X/Y emitter anchor when follow is enabled. It does not create or move a second Scene object.
Object (C64Particle)c64scn_particle_offscreen_update_rateOptional integer update rate per second while the live effect bounds are outside the viewport. Missing or 0 keeps full-rate updates. Positive values must be at least 1. This optimization is ignored for effects with collision, sub-emitters, or a simulation scale above 1.
Object (C64Particle)c64scn_particle_collision_tile_layerName of a tile layer used for particle collision. Value 0 is empty; any non-zero tile makes its complete cell solid. Tile image transparency and Tiled per-tile collision geometry are ignored.
Object (C64Particle)c64scn_particle_collision_object_layerName of an object layer used for particle collision. It may be used together with the tile collision layer.
Objectc64scn_blocks_particlesWhen true, the object's rectangle, ellipse, point, polygon, polyline or tile shape is compiled into shared Physics geometry for particle collision. The particle emitter must select this object's layer through c64scn_particle_collision_object_layer. Moving or resizing the object updates only its own geometry. On a C64Portal, the role is active only while closed.
Object (C64Light)c64scn_light_range_pxRequired positive light radius in world pixels. An absent or invalid value disables the light.
Object (C64Light)c64scn_light_intensityLight intensity, clamped to 0.0 through 1.0. The default is 1.0; an invalid value disables the light.
Object (C64Light)c64scn_light_colorLight colour as #RRGGBBAA. The default and invalid-value fallback is opaque white.
Object (C64Light)c64scn_light_shadowsEnables light occlusion shadows. The default is true.
Object (C64Light)c64scn_light_angle_degSpot cone angle in degrees. Values greater than 0 and below 360 create a spotlight directed by the object's interpolated rotation; absent or invalid values use a point light.
Object (C64Light)c64scn_light_animationLight animation: none, pulse, flicker, or candle. Absent or invalid values use none; the TMX object ID varies deterministic phase and noise.
Object (C64Light)c64scn_light_animation_rateAnimation rate passed to GFXLight. Zero or negative values disable animation; the default is 1.0.
Object (C64Light)c64scn_light_animation_amount, c64scn_light_animation_radius_amountIntensity and radius animation amounts, clamped to 0.0 through 1.0. Defaults are 0.25 and 0.0.
Object (C64Light)c64scn_light_secondary_colorAnimation low-point colour as #RRGGBBAA. Absent, invalid, or #00000000 values reuse the primary colour.
Object (C64Occluder or C64Portal)c64scn_occludes_lightWhen true, uses rectangle, circle, polygon or polyline geometry as a light occluder. Tiled circles are equal-width and equal-height ellipse shapes; non-circular ellipses are not interpreted. On a C64Portal, the role is active only while closed.
Object (C64Portal)c64scn_portal_closedControls whether the portal's configured blocking roles are active. Closed portals can occlude light and block particles; open portals do neither. The default is true.
Object (C64Occluder or C64Portal)c64scn_movement_costReserved pathfinding cost from 0 to 255: 0 is free/default movement, 1 through 254 add increasing traversal cost, and 255 is impassable. Scene core preserves but does not currently interpret it. A portal's cost is intended to apply only while closed.

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 independent Scene overlays and per-object-type AABB, shape, name and trigger overlays 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::sceneMgr()
Note
The Scene Manager is a singleton, automatically created once Main is instantiated. You can get a reference to this manager using Main::sceneMgr() 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
 Shared base classes and context for Scene layers [v26.08.00].
 Scene
 Scene runtime for layered 2D worlds.
 Scene Manager
 Scene Manager for lifecycle and asset management.

Classes

struct  CRM64Pro::SceneCameraParams
 Camera configuration parameters. More...

Enumerations

enum  CRM64Pro::eSceneLayerFeature : Uint32 {
  CRM64Pro::SLF_NONE = 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_NONE = 0 , CRM64Pro::SDO_OBJECT_AABB = 1 , CRM64Pro::SDO_OBJECT_SHAPE = 2 , CRM64Pro::SDO_OBJECT_NAME = 4 ,
  CRM64Pro::SDO_TRIGGER_ZONES = 8 , CRM64Pro::SDO_TILE_CELLGRID = 16 , CRM64Pro::SDO_CAMERA_DEADZONE = 32
}
 Scene debug overlay visualization flags. More...
enum  CRM64Pro::eSceneDebugObjectType : Uint32 {
  CRM64Pro::SDOT_NONE = 0 , CRM64Pro::SDOT_STANDARD = 1 , CRM64Pro::SDOT_LIGHT = 2 , CRM64Pro::SDOT_OCCLUDER = 4 ,
  CRM64Pro::SDOT_PORTAL = 8 , CRM64Pro::SDOT_PARTICLE = 16 , CRM64Pro::SDOT_ALL = SDOT_STANDARD | SDOT_LIGHT | SDOT_OCCLUDER | SDOT_PORTAL | SDOT_PARTICLE
}
 Scene object categories used by object debug overlays. More...
enum  CRM64Pro::eSceneTileSetType : Sint32 { CRM64Pro::STST_NULL = -1 , CRM64Pro::STST_TILESET = 0 , CRM64Pro::STST_COLLECTION = 1 }
 Specifies how the TileSet is organized. More...
enum  CRM64Pro::eSceneStorageMode : Sint32 { CRM64Pro::SSM_DISK , CRM64Pro::SSM_CDC , CRM64Pro::SSM_INTERNAL }
 Specifies where the tileset data is physically stored. More...
enum  CRM64Pro::eSceneShapeType : Sint32 {
  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 : Sint32 {
  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 : Sint32 {
  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

Features for Scene layers.

These flags can be combined using bitwise operators.

Enumerator
SLF_NONE 

No layer features are enabled. 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

Scene debug overlay visualization flags.

Object visualization flags are configured with Scene::setDebugObjectOverlay(). Scene and layer visualization flags are configured with Scene::setDebugOverlay().

Enumerator
SDO_NONE 

No debug visualization.

SDO_OBJECT_AABB 

Draw object AABBs for selected object types.

SDO_OBJECT_SHAPE 

Draw geometric shapes for selected object types.

SDO_OBJECT_NAME 

Draw names for selected object types.

SDO_TRIGGER_ZONES 

Draw trigger zone bounds for selected object types.

SDO_TILE_CELLGRID 

Draw tile cell grid overlays for rendered tile layers.

SDO_CAMERA_DEADZONE 

Draw camera dead-zone rectangles for rendered dead-zone camera layers.

◆ eSceneDebugObjectType

Scene object categories used by object debug overlays.

These flags can be combined so each object visualization can target an independent set of object categories.

Enumerator
SDOT_NONE 

No object categories.

SDOT_STANDARD 

Standard and user-defined object types.

SDOT_LIGHT 

C64Light objects.

SDOT_OCCLUDER 

C64Occluder objects.

SDOT_PORTAL 

C64Portal objects.

SDOT_PARTICLE 

C64Particle objects.

SDOT_ALL 

All object categories.

◆ 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

Specifies where the tileset data is physically stored.

Enumerator
SSM_DISK 

Standard file on the physical disk.

SSM_CDC 

Inside a CRM64Pro::Archive (CDC) file.

SSM_INTERNAL 

Created from an in-memory CRM64Pro object (Tile or Image).

◆ 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

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

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 "c64scn_z" (or "z"), then index.

SORO_Z_FEET 

Draw by z first, then feet (y + height).

◆ eSceneTriggerEventType

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

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::ptAutoScrollSpeed), then optional 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::ptScreenAnchor.

SCM_OFFSET 

Damped tracking plus dynamic offset callback (mouse/stick/cinematic bias).