Axmol 3.0.0-89d6d9a
Loading...
Searching...
No Matches
Director Class Reference

Class that creates and handles the main Window and manages how and when to execute the Scenes. More...

#include <Director.h>

Public Types

enum class  TaskTiming { NextUpdate , FrameBoundary }
 Defines the execution timing for asynchronous tasks dispatched to the main execution thread. More...

Public Member Functions

 ~Director ()
 @lua NA
Scene * getRunningScene ()
 Gets the current running Scene.
Scene * getNextScene ()
 Gets the top(next) scene which will going to running state.
float getAnimationInterval ()
 Gets the FPS value.
void setAnimationInterval (float interval)
 Sets the FPS value.
bool isStatsDisplay ()
 Whether the FPS on the bottom-left corner of the screen is displayed or not.
void setStatsDisplay (bool displayStats)
 Display the FPS on the bottom-left corner of the screen.
float getSecondsPerFrame ()
 Gets the seconds per frame.
void setStatsAnchor (AnchorPreset anchor=(AnchorPreset) 0)
 Sets the stats corner displayed on screen if display stats is enabled.
RenderViewCore * getRenderView ()
 Sets the FPS value.
void setRenderView (RenderViewCore *renderView)
 Sets the RenderView.
bool isNextDeltaTimeZero ()
 Whether or not _nextDeltaTimeZero is set to 0.
void setNextDeltaTimeZero (bool nextDeltaTimeZero)
 Sets the delta time between current frame and next frame is 0.
float getMaxDeltaTime () const
 Gets the maximum delta time allowed per frame.
void setMaxDeltaTime (float maxDeltaTime)
 Sets the maximum delta time allowed per frame.
bool isPaused ()
 Whether or not the Director is paused.
unsigned int getTotalFrames ()
 How many frames were called since the director started.
void setViewport ()
 Sets the viewport.
bool isSendCleanupToScene ()
 Whether or not the replaced scene will receive the cleanup message.
Node * getNotificationNode () const
 This object will be visited after the main scene is visited.
void setNotificationNode (Node *node)
 Sets the notification node.
Vec2 canvasToPixels (const Vec2 &size) const
 Converts a size from canvas coordinates to canvas pixels.
const Vec2 & getCanvasSize () const
 Returns the size of the render view in points.
Vec2 getCanvasSizeInPixels () const
 Returns the size of the render view in pixels.
Vec2 screenToCanvas (const Vec2 &screenPoint) const
 Converts a screen point (top-left origin) to canvas point (bottom-left origin).
Vec2 getVisibleSize () const
 Returns visible size of the render view in points.
Vec2 getVisibleOrigin () const
 Returns visible origin coordinate of the render view in points.
Rect getSafeAreaRect () const
 Returns safe area rectangle of the render view in points.
float getZEye () const
 Gets the distance between camera and near clipping frame.
void runWithScene (Scene *scene)
 Enters the Director's main loop with the given Scene.
void pushScene (Scene *scene)
 Suspends the execution of the running scene, pushing it on the stack of suspended scenes.
void popScene ()
 Pops out a scene from the stack.
void popToRootScene ()
 Pops out all scenes from the stack until the root scene in the queue.
void popToSceneStackLevel (int level)
 Pops out all scenes from the stack until it reaches level.
void replaceScene (Scene *scene)
 Replaces the running scene with a new one.
Scene * popPreviousSceneOut ()
 Removes the previous scene from the stack if it exists, and returns it If there are less than 2 scenes in the stack, or if there is a scene switch about to occur, then this call would be invalid, and a nullptr will be returned.
void end ()
 Ends the execution, releases the running scene.
void pause ()
 Pauses the running scene.
void resume ()
 Resumes the paused scene.
void deactivate ()
 Deactivates the Director, suspending logic updates and rendering.
void activate ()
 Activates the Director, enabling the main frame processing loop.
void purgeCachedData ()
 Removes all axmol cached data.
void setDefaultValues ()
 Sets the default values based on the Environment info.
void setRenderDefaults ()
 Sets the Render default values.
void setClearColor (const Color &clearColor)
 Sets clear values for the color buffers, value range of each element is [0.0, 1.0].
void renderFrame ()
 Drives the execution of a single engine frame.
void renderFrame (float dt)
 Drives the execution of a single engine frame with a caller-provided delta time.
void setContentScaleFactor (float scaleFactor)
 The size in pixels of the surface.
float getContentScaleFactor () const
 Gets content scale factor.
JobSystem * getJobSystem () const
 Gets the JobSystem associated with this director.
JobHandle runAsync (std::function< void()> task, std::function< void()> done=nullptr)
 Run work on the JobSystem and optionally post a completion callback to the Axmol thread.
Scheduler * getScheduler () const
 Gets the Scheduler associated with this director.
void setScheduler (Scheduler *scheduler)
 Sets the Scheduler associated with this director.
ActionManager * getActionManager () const
 Gets the ActionManager associated with this director.
void setActionManager (ActionManager *actionManager)
 Sets the ActionManager associated with this director.
EventDispatcher * getEventDispatcher () const
 Gets the EventDispatcher associated with this director.
void setEventDispatcher (EventDispatcher *dispatcher)
 Sets the EventDispatcher associated with this director.
Renderer * getRenderer () const
 Returns the Renderer associated with this director.
float getFrameRate () const
 Gets Frame Rate.
const std::thread::id & getCocos2dThreadId () const
 returns the axmol thread id.
void setChildrenIndexerEnabled (bool enable)
 Enable node tree children indexer map, the concept is like database INDEX Notes: If enable is true: will cost more memory to speed up getChildByTag & getChildByName.
bool isChildrenIndexerEnabled () const
 returns whether or not node tree children indexer map enabled
void postTask (std::function< void()> task, TaskTiming timing=TaskTiming::NextUpdate)
 Safely dispatches a callable task from any background thread (e.g., Java UI thread, network thread, or audio thread) to be executed on the main Axmol thread.
void clearPendingTasks (TaskTiming timing=TaskTiming::NextUpdate)
 Forcefully purges all pending tasks from the specified queue.
bool isActive () const
 Checks whether the Director is currently active and processing frames.

Static Public Member Functions

static Director * getInstance ()
 Returns a shared instance of the director.

Static Public Attributes

static std::string_view EVENT_BEFORE_SET_NEXT_SCENE
 Director will trigger an event before set next scene.
static std::string_view EVENT_AFTER_SET_NEXT_SCENE
 Director will trigger an event after set next scene.
static std::string_view EVENT_BEFORE_UPDATE
 Director will trigger an event before Schedule::update() is invoked.
static std::string_view EVENT_AFTER_UPDATE
 Director will trigger an event after Schedule::update() is invoked.
static std::string_view EVENT_AFTER_VISIT
 Director will trigger an event after Scene::render() is invoked.
static std::string_view EVENT_AFTER_DRAW
 Director will trigger an event after a scene is drawn, the data is sent to GPU.
static std::string_view EVENT_BEFORE_DRAW
 Director will trigger an event before a scene is drawn, right after clear.
static std::string_view EVENT_RESET
 Director will trigger an event while resetting Director.
static std::string_view EVENT_DISPOSING
 Director dispatches this event before deletion.
static std::string_view EVENT_BEFORE_GFX_DROP
 Director will trigger an event before dropping the graphics subsystem.
static std::string_view EVENT_AFTER_GFX_DROP
 Director will trigger an event after dropping the graphics subsystem.

Detailed Description

Class that creates and handles the main Window and manages how and when to execute the Scenes.

The Director is also responsible for:

  • initializing the graphics context
  • setting the buffer depth (default one is 0-bit)
  • setting the projection (default one is 3D)

Since the Director is a singleton, the standard way to use it is by calling: _ Director::getInstance()->methodName();

Member Enumeration Documentation

◆ TaskTiming

enum class TaskTiming
strong

Defines the execution timing for asynchronous tasks dispatched to the main execution thread.

Enumerator
NextUpdate 

Defer the task to the next main logic update tick (inside Scheduler::update).

Note
Recommended for 95% of standard gameplay logic, UI refreshes, and network response handlers.
FrameBoundary 

Defer the task to the absolute boundary of a frame (outside the main loop's update/visit/render stages).

Note
Reserved for heavy, structural operations such as scene destruction/replacement, massive resource purges, or critical RHI context resets on mobile platforms.

Member Function Documentation

◆ getRunningScene()

Scene * getRunningScene ( )
inline

Gets the current running Scene.

Director can only run one Scene at a time.

◆ setAnimationInterval()

void setAnimationInterval ( float interval)

Sets the FPS value.

FPS = 1/interval.

◆ getRenderView()

RenderViewCore * getRenderView ( )
inline

Sets the FPS value.

Get the RenderView. @lua NA

◆ setRenderView()

void setRenderView ( RenderViewCore * renderView)

Sets the RenderView.

@lua NA

◆ setNextDeltaTimeZero()

void setNextDeltaTimeZero ( bool nextDeltaTimeZero)

Sets the delta time between current frame and next frame is 0.

This value will be used in Schedule, and will affect all functions that are using frame delta time, such as Actions. This value will take effect only one time.

◆ setMaxDeltaTime()

void setMaxDeltaTime ( float maxDeltaTime)

Sets the maximum delta time allowed per frame.

Default is 1/3 second, minimum is 1/60 second.

◆ isSendCleanupToScene()

bool isSendCleanupToScene ( )
inline

Whether or not the replaced scene will receive the cleanup message.

If the new scene is pushed, then the old scene won't receive the "cleanup" message. If the new scene replaces the old one, the it will receive the "cleanup" message.

Since
v0.99.0

◆ getNotificationNode()

Node * getNotificationNode ( ) const
inline

This object will be visited after the main scene is visited.

This object MUST implement the "visit" function. Useful to hook a notification object, like Notifications (http://github.com/manucorporat/CCNotifications)

Since
v0.99.5

◆ setNotificationNode()

void setNotificationNode ( Node * node)

Sets the notification node.

See also
Director::getNotificationNode()

◆ canvasToPixels()

Vec2 canvasToPixels ( const Vec2 & size) const

Converts a size from canvas coordinates to canvas pixels.

This applies only the Director content scale factor. Use this when a canvas-sized logical area needs a texture with matching pixel density, while preserving the same logical content size when used by Sprite.

◆ getVisibleSize()

Vec2 getVisibleSize ( ) const

Returns visible size of the render view in points.

The value is equal to Director::getCanvasSize() if don't invoke RenderView::setDesignResolutionSize().

◆ getZEye()

float getZEye ( ) const

Gets the distance between camera and near clipping frame.

It is correct for default camera that near clipping frame is same as the screen.

◆ runWithScene()

void runWithScene ( Scene * scene)

Enters the Director's main loop with the given Scene.

Call it to run only your FIRST scene. Don't call it if there is already a running scene.

It will call pushScene: and then it will call activate

◆ pushScene()

void pushScene ( Scene * scene)

Suspends the execution of the running scene, pushing it on the stack of suspended scenes.

The new scene will be executed. Try to avoid big stacks of pushed scenes to reduce memory allocation. ONLY call it if there is a running scene.

◆ popScene()

void popScene ( )

Pops out a scene from the stack.

This scene will replace the running one. The running scene will be deleted. If there are no more scenes in the stack the execution is terminated. ONLY call it if there is a running scene.

◆ popToRootScene()

void popToRootScene ( )

Pops out all scenes from the stack until the root scene in the queue.

This scene will replace the running one. Internally it will call popToSceneStackLevel(1).

◆ popToSceneStackLevel()

void popToSceneStackLevel ( int level)

Pops out all scenes from the stack until it reaches level.

If level is 0, it will end the director. If level is 1, it will pop all scenes until it reaches to root scene. If level is <= than the current stack level, it won't do anything.

◆ replaceScene()

void replaceScene ( Scene * scene)

Replaces the running scene with a new one.

The running scene is terminated. ONLY call it if there is a running scene.

◆ popPreviousSceneOut()

Scene * popPreviousSceneOut ( )

Removes the previous scene from the stack if it exists, and returns it If there are less than 2 scenes in the stack, or if there is a scene switch about to occur, then this call would be invalid, and a nullptr will be returned.

Returns previous scene or nullptr if invalid

◆ end()

void end ( )

Ends the execution, releases the running scene.

@lua endToLua

◆ pause()

void pause ( )

Pauses the running scene.

The running scene will be drawed but all scheduled timers will be paused. While paused, the draw rate will be 4 FPS to reduce CPU consumption.

◆ resume()

void resume ( )

Resumes the paused scene.

The scheduled timers will be activated again. The "delta time" will be 0 (as if the game wasn't paused).

◆ deactivate()

void deactivate ( )

Deactivates the Director, suspending logic updates and rendering.

When deactivated, renderFrame() will skip all internal logic updates and rendering processes (saving CPU/GPU resources), while still allowing the OS event pump to run. This is typically invoked when the application enters the background or loses window focus.

Note
Unlike pause(), which only stops the logic updates but continues to render the current frame, deactivate() completely freezes the engine's world.
This safely replaces the legacy stopAnimation() method.

◆ activate()

void activate ( )

Activates the Director, enabling the main frame processing loop.

When activated, the Director will process game logic, update the scheduler, and render the scene during each renderFrame() call. It also resets the delta time to prevent physics or animation spikes upon resuming.

Note
This safely replaces the legacy startAnimation() method.

◆ purgeCachedData()

void purgeCachedData ( )

Removes all axmol cached data.

It will purge the TextureCache, SpriteFrameCache, LabelBMFont cache

Since
v0.99.3

◆ setRenderDefaults()

void setRenderDefaults ( )

Sets the Render default values.

It will enable alpha blending, disable depth test.

◆ renderFrame() [1/2]

void renderFrame ( )

Drives the execution of a single engine frame.

This is the core function of the engine's main loop. In a single call, it:

  1. Polls underlying OS events to keep the application responsive.
  2. Handles pending Director lifecycle states (e.g., restart or cleanup).
  3. If the Director is active (isActive() == true):
    • Advances the scheduler and game logic (if not paused).
    • Submits render commands via the RHI and swaps buffers.
Note
This method should be called continuously by the platform-specific application loop.
This replaces the legacy stepFrame() and processFrame() methods.

◆ renderFrame() [2/2]

void renderFrame ( float dt)

Drives the execution of a single engine frame with a caller-provided delta time.

This overload allows the platform layer to pass in a custom delta time (e.g., from a display link), bypassing calculateDeltaTime(). The delta passed may include vsync time. See issue #17806.

Note
This replaces the legacy stepFrame(float dt) method.

◆ setContentScaleFactor()

void setContentScaleFactor ( float scaleFactor)

The size in pixels of the surface.

It could be different than the screen size. High-res devices might have a higher surface size than the screen size. Only available when compiled using SDK >= 4.0.

Since
v0.99.4

◆ getContentScaleFactor()

float getContentScaleFactor ( ) const
inline

Gets content scale factor.

See also
Director::setContentScaleFactor()

◆ getJobSystem()

JobSystem * getJobSystem ( ) const
inline

Gets the JobSystem associated with this director.

Since
axmol-2.1.4

◆ runAsync()

JobHandle runAsync ( std::function< void()> task,
std::function< void()> done = nullptr )

Run work on the JobSystem and optionally post a completion callback to the Axmol thread.

The task function runs on the JobSystem. After task returns, done is posted through Director::postTask() and therefore runs later on the Axmol thread.

Parameters
taskFunction executed by the JobSystem.
doneOptional completion callback posted to the Axmol thread after task returns.
Returns
A handle for the background job. The handle reaches a terminal state after task returns; it does not wait for the posted done callback to run.
Note
This is the preferred high-level API for the common background-work-then-main-thread-callback pattern. Use JobSystem::enqueue() directly for low-level jobs that do not need Director or Scheduler semantics.
Since
axmol-3.0.0

◆ getScheduler()

Scheduler * getScheduler ( ) const
inline

Gets the Scheduler associated with this director.

Since
v2.0

◆ setScheduler()

void setScheduler ( Scheduler * scheduler)

Sets the Scheduler associated with this director.

Since
v2.0

◆ getActionManager()

ActionManager * getActionManager ( ) const
inline

Gets the ActionManager associated with this director.

Since
v2.0

◆ setActionManager()

void setActionManager ( ActionManager * actionManager)

Sets the ActionManager associated with this director.

Since
v2.0

◆ getEventDispatcher()

EventDispatcher * getEventDispatcher ( ) const
inline

Gets the EventDispatcher associated with this director.

Since
v3.0

◆ setEventDispatcher()

void setEventDispatcher ( EventDispatcher * dispatcher)

Sets the EventDispatcher associated with this director.

Since
v3.0

◆ getRenderer()

Renderer * getRenderer ( ) const
inline

Returns the Renderer associated with this director.

Since
v3.0

◆ getCocos2dThreadId()

const std::thread::id & getCocos2dThreadId ( ) const
inline

returns the axmol thread id.

Useful to know if certain code is already running on the axmol thread

◆ postTask()

void postTask ( std::function< void()> task,
TaskTiming timing = TaskTiming::NextUpdate )

Safely dispatches a callable task from any background thread (e.g., Java UI thread, network thread, or audio thread) to be executed on the main Axmol thread.

  • This API provides a high-performance, Zero-Allocation (Zero GC) pipeline across platforms by utilizing modern C++ move semantics internally, paired with an optimized FIFO signaling pipeline on Android to completely eliminate runtime heap allocations.
  • Parameters
    taskThe callable closure, lambda, or std::function to be executed.
    timingThe specific execution timing when this task should be consumed. Defaults to TaskTiming::NextUpdate.
  • // Example 1: Standard asynchronous network callback (runs in the next logic tick)
    this->updatePlayerGold(goldCount);
    });
    * // Example 2: Critical structural engine operation (runs at the safe frame boundary)
    void postTask(std::function< void()> task, TaskTiming timing=TaskTiming::NextUpdate)
    Safely dispatches a callable task from any background thread (e.g., Java UI thread,...
    static Director * getInstance()
    Returns a shared instance of the director.
    @ FrameBoundary
    Defer the task to the absolute boundary of a frame (outside the main loop's update/visit/render stage...
    Definition Director.h:120
    void replaceScene(Scene *scene)
    Replaces the running scene with a new one.
    Since
    axmol-3.0.0

◆ clearPendingTasks()

void clearPendingTasks ( TaskTiming timing = TaskTiming::NextUpdate)

Forcefully purges all pending tasks from the specified queue.

Warning
This is an extreme, engine-level utility (e.g., during full game reboot or director end). Calling this on FrameBoundary may leak graphics contexts or skip critical structural cleanups. Do NOT use this for standard gameplay object lifecycle management.

The documentation for this class was generated from the following file:
  • Director.h