Jazz2::LevelHandler class

Level handler of a local game session.

Concrete state handler that runs a single-player or local-multiplayer level: it loads the level descriptor, owns the tile map, event map and collision broad-phase, spawns and updates actors and players, drives rendering, lighting and audio, and serializes resumable state.

Base classes

class ILevelHandler
Base interface of a level handler.
class IStateHandler
Base interface of a state handler, only one handler runs at a time.
class IResumable
Base interface of a resumable object.
class ITileMapOwner
Interface used to notify tile map owner of various events.

Derived classes

class MpLevelHandler
Level handler of a multiplayer game session (online or local splitscreen).

Constructors, destructors, conversion operators

LevelHandler(IRootController* root)
Creates a new instance.
~LevelHandler() override

Public functions

auto Initialize(const LevelInitialization& levelInit) -> bool override
Initializes the level handler from LevelInitialization.
auto Initialize(Stream& src, std::uint16_t version) -> bool override
Initializes the level handler from resumable state.
auto EventSpawner() -> Events::EventSpawner* override
Returns event spawner for the level.
auto EventMap() -> Events::EventMap* override
Returns event map for the level.
auto TileMap() -> Tiles::TileMap* override
Returns tile map for the level.
auto GetDifficulty() const -> GameDifficulty override
Return current difficulty.
auto IsLocalSession() const -> bool override
Returns true if the level handler is on a local session.
auto IsServer() const -> bool override
Returns true if the level handler is on a server or a local session.
auto IsPausable() const -> bool override
Returns true if the level handler is pausable.
auto IsReforged() const -> bool override
Returns true if Reforged Gameplay is enabled.
auto CanActivateSugarRush() const -> bool override
Returns true if sugar rush can be activated.
auto CanEventDisappear(EventType eventType) const -> bool override
Returns true if event can be safely despawned.
auto CanPlayersCollide() const -> bool override
Returns true if players can collide with each other.
auto GetLevelBounds() const -> Recti override
Returns level bounds including camera limits.
auto GetElapsedFrames() const -> float override
Returns number of elapsed frames.
auto GetGravity() const -> float override
Returns current gravity force.
auto GetWaterLevel() const -> float override
Returns current water level.
auto GetHurtInvulnerableTime() const -> float override
Returns default invulnerable time when a player is hurt.
auto GetActiveBossHealth(std::int32_t& health, std::int32_t& maxHealth) const -> bool override
Returns true if a boss health bar should be shown, together with the boss' health.
auto GetActors() const -> ArrayView<const std::shared_ptr<Actors::ActorBase>> override
Returns list of actors (objects).
auto GetPlayers() const -> ArrayView<Actors::Player* const> override
Returns list of players.
auto FindPlayerToStandOn(Actors::Player* player, float timeMult) -> Actors::ActorBase* override
Returns the player actor player is standing/landing on (one-way platform check), or nullptr.
auto GetLevelName() const -> StringView
Returns the internal name (path) of the current level.
auto GetLevelDisplayName() const -> StringView
Returns the display (title) name of the current level.
void SetLevelDisplayName(StringView value)
Overrides the display (title) name of the current level.
auto GetDefaultAmbientLight() const -> float override
Returns default ambient light intensity.
auto GetAmbientLight(Actors::Player* player) const -> float override
Returns current ambient light intensity.
void SetAmbientLight(Actors::Player* player, float value) override
Sets current ambient light intensity.
auto GetViewSize() const -> Vector2i override
Returns viewport size of the handler.
void OnBeginFrame() override
Called at the beginning of each frame.
void OnEndFrame() override
Called at the end of each frame.
void OnInitializeViewport(std::int32_t width, std::int32_t height) override
Called when the viewport needs to be initialized (e.g., when the resolution is changed).
auto OnConsoleCommand(StringView line) -> bool virtual
Called when a console command is entered.
void OnKeyPressed(const KeyboardEvent& event) override
Called when a key is pressed.
void OnKeyReleased(const KeyboardEvent& event) override
Called when a key is released.
void OnTextInput(const TextInputEvent& event) override
Called when a text input is detected.
void OnTouchEvent(const TouchEvent& event) override
Called when a touch event is triggered.
void AddActor(std::shared_ptr<Actors::ActorBase> actor) override
Adds an actor (object) to the level.
auto PlaySfx(Actors::ActorBase* self, StringView identifier, AudioBuffer* buffer, const Vector3f& pos, bool sourceRelative, float gain, float pitch) -> std::shared_ptr<AudioBufferPlayer> override
Plays a sound effect for a given actor (object).
auto PlayCommonSfx(StringView identifier, const Vector3f& pos, float gain = 1.0f, float pitch = 1.0f) -> std::shared_ptr<AudioBufferPlayer> override
Plays a common sound effect.
void WarpCameraToTarget(Actors::ActorBase* actor, bool fast = false) override
Warps a camera to its assigned target.
auto IsPositionEmpty(Actors::ActorBase* self, const AABBf& aabb, Tiles::TileCollisionParams& params, Actors::ActorBase** collider) -> bool override
Returns true if a specified AABB is empty.
void FindCollisionActorsByAABB(const Actors::ActorBase* self, const AABBf& aabb, Function<bool(Actors::ActorBase*)>&& callback) override
Calls the callback function for all colliding objects with specified AABB.
void FindCollisionActorsByRadius(float x, float y, float radius, Function<bool(Actors::ActorBase*)>&& callback) override
Calls the callback function for all colliding objects with specified circle.
void GetCollidingPlayers(const AABBf& aabb, Function<bool(Actors::ActorBase*)>&& callback) override
Calls the callback function for all colliding players with specified AABB.
void BroadcastTriggeredEvent(Actors::ActorBase* initiator, EventType eventType, std::uint8_t* eventParams) override
Broadcasts specified event to all other actors.
void BeginLevelChange(Actors::ActorBase* initiator, ExitType exitType, StringView nextLevel = {}) override
Starts transition to change current level.
auto CanTakeLevelExit(ExitType exitType, StringView nextLevel) const -> bool override
Returns true if a level exit of the specified type leading to the specified level can be taken.
void SendPacket(const Actors::ActorBase* self, ArrayView<const std::uint8_t> data) override
Sends a packet to the other side of a non-local session.
void HandleBossActivated(Actors::Bosses::BossBase* boss, Actors::ActorBase* initiator = nullptr) override
Called when a boss is activated.
void HandleLevelChange(LevelInitialization&& levelInit) override
Called when the level is changed.
void HandleGameOver(Actors::Player* player) override
Called when the game is over.
auto HandlePlayerDied(Actors::Player* player) -> bool override
Called when a player dies.
void HandlePlayerWarped(Actors::Player* player, Vector2f prevPos, WarpFlags flags) override
Called when a player warps.
void HandlePlayerCoins(Actors::Player* player, std::int32_t prevCount, std::int32_t newCount) override
Called when a player collects or losts coins.
void HandlePlayerGems(Actors::Player* player, std::uint8_t gemType, std::int32_t prevCount, std::int32_t newCount) override
Called when a player collects or losts gems.
void SetCheckpoint(Actors::Player* player, Vector2f pos) override
Sets checkpoint for a given player.
void RollbackToCheckpoint(Actors::Player* player) override
Rolls back to the last checkpoint for a given player.
void HandleActivateSugarRush(Actors::Player* player) override
Called when a player activates sugar rush.
void HandleCreateParticleDebrisOnPerish(const Actors::ActorBase* self, Actors::ParticleDebrisEffect effect, Vector2f speed) override
Called when an object creates a particle debris on perish.
void HandleCreateSpriteDebris(const Actors::ActorBase* self, AnimState state, std::int32_t count) override
Called when an object creates a sprite debris.
void ShowLevelText(StringView text, Actors::ActorBase* initiator = nullptr) override
Shows a text notification.
auto GetLevelText(std::uint32_t textId, std::int32_t index = -1, std::uint32_t delimiter = 0) -> StringView override
Returns a level text.
void OverrideLevelText(std::uint32_t textId, StringView value) override
Override specified level text.
auto GetCameraPos(Actors::Player* player) const -> Vector2f override
Returns camera position of a given player.
void LimitCameraView(Actors::Player* player, Vector2f playerPos, std::int32_t left, std::int32_t width) override
Limits camera viewport for a given player.
void OverrideCameraView(Actors::Player* player, float x, float y, bool topLeft = false) override
Override camera viewport for a given player.
void ShakeCameraView(Actors::Player* player, float duration) override
Shake camera for a given player.
void ShakeCameraViewNear(Vector2f pos, float duration) override
Shake camera for all players near a given position.
auto GetTrigger(std::uint8_t triggerId) -> bool override
Returns state of a given trigger in the tile map.
void SetTrigger(std::uint8_t triggerId, bool newState) override
Sets state of a given trigger in the tile map.
void SetWeather(WeatherType type, std::uint8_t intensity) override
Sets current level weather.
auto BeginPlayMusic(StringView path, bool setDefault = false, bool forceReload = false) -> bool override
Plays specified music.
auto PlayerActionPressed(Actors::Player* player, PlayerAction action, bool includeGamepads = true) -> bool override
Returns true if player action is pressed.
auto PlayerActionPressed(Actors::Player* player, PlayerAction action, bool includeGamepads, bool& isGamepad) -> bool override
auto PlayerActionHit(Actors::Player* player, PlayerAction action, bool includeGamepads = true) -> bool override
Returns true if player action is hit (newly pressed).
auto PlayerActionHit(Actors::Player* player, PlayerAction action, bool includeGamepads, bool& isGamepad) -> bool override
auto PlayerHorizontalMovement(Actors::Player* player) -> float override
Returns value of desired horizontal player movement.
auto PlayerVerticalMovement(Actors::Player* player) -> float override
Returns value of desired vertical player movement.
void PlayerExecuteRumble(Actors::Player* player, StringView rumbleEffect) override
Executes a rumble effect.
auto SerializeResumableToStream(Stream& dest) -> bool override
Serializes object state to a stream.
void OnAdvanceDestructibleTileAnimation(std::int32_t tx, std::int32_t ty, std::int32_t amount) override
Called when a destructible tile animation is advanced.
void OnTileFrozen(std::int32_t x, std::int32_t y) override
Called when a tile is frozen.

Protected types

struct PlayerInput
Describes current input state of a player.

Protected static functions

static auto IsReturnLevel(StringView levelName) -> bool
Returns true if the specified level is a special level.

Protected functions

void InvokeAsync(Function<void()>&& callback)
Invokes the specified callback asynchronously, usually at the end of current frame.
void AttachComponents(LevelDescriptor&& descriptor) virtual
Attaches all required level components to the handler.
auto CreateHUD() -> std::unique_ptr<UI::HUD> virtual
Creates HUD.
void SpawnPlayers(const LevelInitialization& levelInit) virtual
Spawns all players.
auto CreateResumablePlayer(std::int32_t index) -> std::shared_ptr<Actors::Player> virtual
Creates a player instance while restoring a resumable state from a stream (one per serialized player).
auto IsCheatingAllowed(Actors::Player* player) -> bool virtual
Returns true if cheats are enabled for the specified player, nullptr refers to the local console.
void OnInitialized() virtual
Called after the level is loaded and all players were spawned.
void BeforeActorDestroyed(Actors::ActorBase* actor) virtual
Called before an actor (object) is destroyed.
void ProcessEvents(float timeMult) virtual
Processes events.
void ProcessQueuedNextLevel() virtual
Processes transition to the next level if queued.
void PrepareNextLevelInitialization(LevelInitialization& levelInit) virtual
Prepares LevelInitialization for transition to the next level.
auto CanUseLevelStateSnapshots() const -> bool virtual
Returns true if actors can be stored in level state snapshots.
auto ResolveNextLevelName(ExitType exitType, StringView nextLevel) const -> String
Returns full name of the level that follows after the level is exited with the specified exit type.
auto GetPlayerViewportBounds(std::int32_t w, std::int32_t h, std::int32_t index) -> Recti
Returns player viewport bounds.
void ProcessWeather(float timeMult)
Processes weather.
void ResolveCollisions(float timeMult)
Resolves collisions.
void AssignViewport(Actors::Player* player)
Assigns viewport.
void UnassignViewport(Actors::Player* player)
Unassigns viewport.
void CommitViewports()
Commits changes in assigned viewports.
auto GetActiveOverlayPass() -> Rendering::UpscaleRenderPassWithClipping&
Returns the upscale pass that hosts the HUD and in-game menu (the native-resolution overlay pass when the scene is supersampled, otherwise the scene pass).
auto GetHudParentNode() -> SceneNode*
Returns the scene node that the HUD and other overlay UI should attach to.
void InitializeCamera(Rendering::PlayerViewport& viewport)
Initializes camera for specified viewport.
void UpdatePressedActions()
Updates pressed actions.
void UpdateRichPresence()
Updates rich presence.
void InitializeRumbleEffects()
Initializes common rumble effects.
auto RegisterRumbleEffect(StringView name) -> RumbleDescription*
Registers a rumple effect.
void PauseGame() virtual
Pauses the game.
void ResumeGame() virtual
Resumes the paused game.
void ShowConsole() virtual
Shows the in-game console.
void HideConsole() virtual
Hides the in-game console.
auto ApplyCheat(StringView line, ArrayView<Actors::Player* const> targets) -> bool
Applies the cheat matching the specified command to the specified players.

Constants

static std::int32_t DefaultWidth constexpr
Default width of viewport (see Rendering::UpscaleRenderPass::DefaultViewWidth).
static std::int32_t DefaultHeight constexpr
Default height of viewport.
static std::int32_t ActivateTileRange constexpr
Range of tile activation, in tiles either side of a player.

Function documentation

Jazz2::LevelHandler::LevelHandler(IRootController* root)

Creates a new instance.

Parameters
root Root controller that owns the handler

bool Jazz2::LevelHandler::GetActiveBossHealth(std::int32_t& health, std::int32_t& maxHealth) const override

Returns true if a boss health bar should be shown, together with the boss' health.

Online clients never own the boss actor (boss activation is server-side only), so multiplayer reports the health synchronized from the server instead of reading the local boss actor.

Actors::ActorBase* Jazz2::LevelHandler::FindPlayerToStandOn(Actors::Player* player, float timeMult) override

Returns the player actor player is standing/landing on (one-way platform check), or nullptr.

Shared by local splitscreen co-op and online sessions to let players stand on top of each other. Local sessions search the player list; online sessions also search remote players on clients.

bool Jazz2::LevelHandler::CanTakeLevelExit(ExitType exitType, StringView nextLevel) const override

Returns true if a level exit of the specified type leading to the specified level can be taken.

A special level returns back to the level it was entered from once it's completed, and it cannot be entered from there again (see LevelInitialization::ReturnLevelState).

bool Jazz2::LevelHandler::PlayerActionPressed(Actors::Player* player, PlayerAction action, bool includeGamepads, bool& isGamepad) override

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

bool Jazz2::LevelHandler::PlayerActionHit(Actors::Player* player, PlayerAction action, bool includeGamepads, bool& isGamepad) override

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

static bool Jazz2::LevelHandler::IsReturnLevel(StringView levelName) protected

Returns true if the specified level is a special level.

A special level specifies itself as its next level, it has no successor of its own and returns back to the level it was entered from once completed (e.g., "Gargoyle's Lair" from "Medieval Kineval").

bool Jazz2::LevelHandler::CanUseLevelStateSnapshots() const virtual protected

Returns true if actors can be stored in level state snapshots.

Snapshots make it possible to roll back all actors to the last checkpoint, to resume them from a saved state and to return from a special level to the exact state the previous level was left in.

bool Jazz2::LevelHandler::ApplyCheat(StringView line, ArrayView<Actors::Player* const> targets) protected

Applies the cheat matching the specified command to the specified players.

Parameters
line Command to look up
targets Players the cheat is applied to, pass an empty view to only check whether line is a cheat
Returns true if line is a known cheat command

The command is not validated against IsCheatingAllowed, the caller is responsible for it.

Variable documentation

static std::int32_t Jazz2::LevelHandler::ActivateTileRange constexpr

Range of tile activation, in tiles either side of a player.

Everything inside this square around a player is spawned from the event map, and everything whose origin tile leaves it by a further 4 tiles is destroyed again. Nothing culls an actor's update, only its drawing, so every actor in here - enemies, platforms, and the gems, ammo and crates that are just as much actors - runs a full movement and tile-collision step every frame. The range is therefore a direct lever on how much the level costs to simulate, quadratically: 26 is a 52x52 tile box, 18 is 36x36, or 48% of the area.

The consoles below take the smaller value because their screens are small enough that it is still entirely off-screen. What has to stay off-screen is the margin between the box and the edge of the view, which at 32 pixels to the tile is 8 tiles (256 px) on the widest of them (the 640-wide Dreamcast, GameCube and PlayStation 2, whose visible half-width is 10 tiles) and 13 tiles on the Nintendo 64. Even the tightest of those is about half a second of travel at Player::MaxDashingSpeed, and lowering PreferencesCache::RenderingResolutionPercent only ever shows less of the world, so it cannot eat into the margin. The Wii is deliberately not in the list - it is the fastest machine here and renders the same 640 columns - but it would be safe if it ever needs the room.