CCDirector(导演 )


#ifndef __CCDIRECTOR_H__

#define __CCDIRECTOR_H__


#include "platform/CCPlatformMacros.h"

#include "cocoa/CCObject.h"

#include "ccTypes.h"

#include "cocoa/CCGeometry.h"

#include "cocoa/CCArray.h"

#include "CCGL.h"

#include "kazmath/mat4.h"

#include "label_nodes/CCLabelAtlas.h"

#include "ccTypeInfo.h"



NS_CC_BEGIN



/** @typedef ccDirectorProjection

 Possible OpenGL projections used by director

 */

//枚举一些 可能用到的 opengl投影

typedef enum {  

    /// sets a 2D projection (orthogonal projection)

    kCCDirectorProjection2D,//2d投影

    

    /// sets a 3D projection with a fovy=60, znear=0.5f and zfar=1500.

    kCCDirectorProjection3D,// 3d投影 默认

    

    /// it calls "updateProjection" on the projection delegate.

    kCCDirectorProjectionCustom,

    

    /// Default projection is 3D projection

    kCCDirectorProjectionDefault = kCCDirectorProjection3D,

} ccDirectorProjection;


//前置声明告诉编译器这些类存在 

class CCLabelAtlas;

class CCScene;

class CCEGLView;

class CCDirectorDelegate;

class CCNode;

class CCScheduler;

class CCActionManager;

class CCTouchDispatcher;

class CCKeypadDispatcher;

class CCAccelerometer;


/**

@brief Class that creates and handle the main Window and manages how

and when to execute(执行) the Scenes.

 

 The CCDirector is also responsible(负责的) for:

  - initializing the OpenGL context//初始化 OpenGL

  - setting the OpenGL pixel format (default on is RGB565)//设置OpenGL着色器类型

  - setting the OpenGL buffer depth (default one is 0-bit)//设置 OpenGL 缓存大小

  - setting the projection (default one is 3D)//设置 投影 

  - setting the orientation (default one is Portrait)//设置 方向 (默认是 Portrait)    //竖屏 

 

 The CCDirector also sets the default OpenGL context:

  - GL_TEXTURE_2D is enabled

  - GL_VERTEX_ARRAY is enabled

  - GL_COLOR_ARRAY is enabled

  - GL_TEXTURE_COORD_ARRAY is enabled

*/

class CC_DLL CCDirector : public CCObject, public TypeInfo

{

public:

    CCDirector(void);

//注意下面的 说法  单例不一定非要构造私有 核心是有一个得到同一个实例指针的接口  标准的用法是CCDirector::sharedDirector() 当然也可以new但会出问题且破坏单例

 Since the CCDirector is a singleton, the standard way to use it is by calling:

  _ CCDirector::sharedDirector()->methodName();

//



    virtual ~CCDirector(void);

    virtual bool init(void);

    virtual long getClassTypeInfo() {

static const long id = cocos2d::getHashCodeByString(typeid(cocos2d::CCDirector).name());

return id;

    }//得到导演id ???


    /** Get current running Scene. Director can only run one Scene at the time */

    inline CCScene* getRunningScene(void) { return m_pRunningScene; }//inline内联函数在函数体不是很大时执行效率更高


    /** Get the FPS value */

    inline double getAnimationInterval(void) { return m_dAnimationInterval; }

    /** Set the FPS value. */

    virtual void setAnimationInterval(double dValue) = 0;


    /** Whether or not to display the FPS on the bottom-left corner */

    inline bool isDisplayStats(void) { return m_bDisplayStats; }

    /** Display the FPS on the bottom-left corner */

    inline void setDisplayStats(bool bDisplayStats) { m_bDisplayStats = bDisplayStats; }

    

    /** seconds per frame */

    inline float getSecondsPerFrame() { return m_fSecondsPerFrame; }


    /** Get the CCEGLView, where everything is rendered */

    inline CCEGLView* getOpenGLView(void) { return m_pobOpenGLView; }

    void setOpenGLView(CCEGLView *pobOpenGLView);


//下一次帧间隔是否为0

    inline bool isNextDeltaTimeZero(void) { return m_bNextDeltaTimeZero; }

//为true 则每帧调用

    void setNextDeltaTimeZero(bool bNextDeltaTimeZero);


    /** Whether or not the Director is paused */

    inline bool isPaused(void) { return m_bPaused; }


    /** How many frames were called since the director started */

    inline unsigned int getTotalFrames(void) { return m_uTotalFrames; }

    

    /** Sets an OpenGL projection

     @since v0.8.2

     */

//得到导演的投影枚举类型值

    inline ccDirectorProjection getProjection(void) { return m_eProjection; }

    void setProjection(ccDirectorProjection kProjection);

    

    /** Sets the glViewport*/

//以winsize设置view范围

    void setViewport();


    /** How many frames were called since the director started */

    

    /** 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.

     */

//是否清除上个场景

    inline bool isSendCleanupToScene(void) { return m_bSendCleanupToScene; }


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

     This object MUST implement(执行 实现) the "visit" selector.

     Useful to hook(使上钩) a notification object     */

//用来显示全局消息的node,这个消息不受场景切换影响

//在主场景被visit之后将被访问的对象,这个对象必须可以执行visit selector。经常用来挂载notification对象,如CCNotifications   

//例子在cocos2dx->使用CCDirector的notificationNode来创建独立的信息提示层

    CCNode* getNotificationNode();

  // 设置在主场景被visit之后将被访问的对象

    void setNotificationNode(CCNode *node);

    

    

/** CCDirector delegate. It shall implemente the CCDirectorDelegate protocol

     @since v0.99.5

     */

    CCDirectorDelegate* getDelegate() const; 

//导演代理,提供更新接口可供用户重新实现

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

/** * OpenGL projection(投影) protocol(协议) */

class CC_DLL CCDirectorDelegate{

public:

  //Will be called by CCDirector when the projection is updated, and "custom" projection is used

    virtualvoid updateProjection(void) =0;  //????????????????????????????

};

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    void setDelegate(CCDirectorDelegate* pDelegate);


    // window size


    /** returns the size of the OpenGL view in points.

    */

    CCSize getWinSize(void);


    /** returns the size of the OpenGL view in pixels(像素).

    */

//返回OpenGL view的大小,单位为像素

    CCSize getWinSizeInPixels(void);

    

    /** returns visible size of the OpenGL view in points.

     *  the value is equal to getWinSize if don't invoke

     *  CCEGLView::setDesignResolutionSize()

     */

//返回OpenGL view可见区域的大小,单位为点。

    CCSize getVisibleSize();

//

getWinSize与getWinSizeInPixels的差别在于是否使用DesignResolutionSize,getWinSizeInPixsels是窗口实际大小

而getWinSize是DesignResolutionSize,getVisibleSize是在有DesignResolutionSize的情况下,有对不齐的情况时不一样的值

/    

    /** returns visible origin of the OpenGL view in points.

     */

    CCPoint getVisibleOrigin();


    /** converts(转换) a UIKit coordinate(坐标) to an OpenGL coordinate

     Useful to convert (multi) touch coordinates to the current layout(布局 陈列) (portrait(肖像 描写) or landscape(风景))

     */

    CCPoint convertToGL(const CCPoint& obPoint);


    /** converts an OpenGL coordinate to a UIKit coordinate

     Useful to convert node points to window points for calls such as glScissor

     */

    CCPoint convertToUI(const CCPoint& obPoint);

//坐标转换,从GL坐标到UI坐标的相互转换,GL坐标左下角为原点,UI坐标则是坐上角

    /// XXX: missing description 

    float getZEye(void);


    // Scene Management


    /** 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 startAnimation

     */

    void runWithScene(CCScene *pScene);


    /** 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.

     */

//暂停当前scene,将其推入暂停scene栈,启动新的scene

    void pushScene(CCScene *pScene);


    /** Pops out a scene from the queue.

     * 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.

     */

//弹出当前运行的scene,如果栈中还有scene,那么继续栈顶的scene,如果没有,程序退出

    void popScene(void);


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

     * This scene will replace the running one.

     * Internally it will call `popToSceneStackLevel(1)`

     */

//弹出所有的scene,除了最后一个不弹

    void popToRootScene(void);


    /** Pops out all scenes from the queue 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.

     */

//弹到某个地方,如果level为0,那么相当于程序结束,如果level为1,那么相当于popToRootScene,如果level大于栈深度,那啥也不干

 void popToSceneStackLevel(int level);


    /** Replaces the running scene with a new one. The running scene is terminated.

     * ONLY call it if there is a running scene.

     */

    void replaceScene(CCScene *pScene);


    /** Ends the execution, releases the running scene.

     It doesn't remove the OpenGL view from its parent. You have to do it manually.

     */

    void end(void);//结束


    /** 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

     */

    void pause(void);//暂停


    /** Resumes the paused scene

     The scheduled timers will be activated again.

     The "delta time" will be 0 (as if the game wasn't paused)

     */

    void resume(void);//继续


    /** Stops the animation. Nothing will be drawn. The main loop won't be triggered anymore.

     If you don't want to pause your animation call [pause] instead.

     */

    virtual void stopAnimation(void) = 0;


    /** The main loop is triggered again.

     Call this function only if [stopAnimation] was called earlier

     @warning Don't call this function to start the main loop. To run the main loop call runWithScene

     */

    virtual void startAnimation(void) = 0;

//停止和开始画场景,默认实现和pause、resume相同


//每帧调用 

    void drawScene(void);

void CCDirector::drawScene(void)

{

    // calculate "global" dt

    calculateDeltaTime();


    //tick before glClear: issue #533

    if (! m_bPaused)

    {

        m_pScheduler->update(m_fDeltaTime);

    }


    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);


    /* to avoid flickr, nextScene MUST be here: after tick and before draw.

     XXX: Which bug is this one. It seems that it can't be reproduced with v0.9 */

    if (m_pNextScene)

    {

        setNextScene();

    }


    kmGLPushMatrix();


    // draw the scene

    if (m_pRunningScene)

    {

        m_pRunningScene->visit();

    }


    // draw the notifications node

    if (m_pNotificationNode)

    {

        m_pNotificationNode->visit();

    }

    

    if (m_bDisplayStats)

    {

        showStats();

    }


    kmGLPopMatrix();


    m_uTotalFrames++;


    // swap buffers

    if (m_pobOpenGLView)

    {

        m_pobOpenGLView->swapBuffers();

    }

    

    if (m_bDisplayStats)

    {

        calculateMPF();

    }

}



    // Memory Helper


    /** Removes cached all cocos2d cached data.

     It will purge the CCTextureCache, CCSpriteFrameCache, CCLabelBMFont cache

     @since v0.99.3

     */

    void purgeCachedData(void);

//清空缓存,主要是CCTextureCache, CCSpriteFrameCache, CCLabelBMFont所指缓存


/** sets the default values based on the CCConfiguration info */

    void setDefaultValues(void);


    // OpenGL Helper

      

/ **设置后OpenGL默认值* /

    /** sets the OpenGL default values */

    void setGLDefaultValues(void);


    /** enables/disables OpenGL alpha blending */

/ **使用/禁用OpenGL的Alpha组合* /

    void setAlphaBlending(bool bOn);



    /** enables/disables OpenGL depth test */

/ **使用/禁用OpenGL景深测试* /

    void setDepthTest(bool bOn);

//设置一些OpenGL参数

    virtual void mainLoop(void) = 0;

//主循环,负责画scene

    /** 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

    */

    void setContentScaleFactor(float scaleFactor);

    float getContentScaleFactor(void);

//设置缩放因子

public:

    /** CCScheduler associated(关联) with this director

     @since v2.0

     */

    CC_PROPERTY(CCScheduler*, m_pScheduler, Scheduler);  //关联导演的 调度器 因为导演单例 所以这个调度器也唯一 且这个调度器只使用update类型回调 即每帧调用

//init()中一段代码

    // scheduler

    m_pScheduler = new CCScheduler();

    // action manager

    m_pActionManager = new CCActionManager();

    m_pScheduler->scheduleUpdateForTarget(m_pActionManager, kCCPrioritySystem, false);

//


    /** CCActionManager associated with this director

     @since v2.0

     */

    CC_PROPERTY(CCActionManager*, m_pActionManager, ActionManager);


    /** CCTouchDispatcher associated with this director

     @since v2.0

     */

    CC_PROPERTY(CCTouchDispatcher*, m_pTouchDispatcher, TouchDispatcher);


    /** CCKeypadDispatcher associated with this director

     @since v2.0

     */

    CC_PROPERTY(CCKeypadDispatcher*, m_pKeypadDispatcher, KeypadDispatcher);


    /** CCAccelerometer associated with this director

     @since v2.0

     */

    CC_PROPERTY(CCAccelerometer*, m_pAccelerometer, Accelerometer);


    /* delta time since last tick to main loop */

CC_PROPERTY_READONLY(float, m_fDeltaTime, DeltaTime);

//各种属性

public:

    /** returns a shared instance of the director */

    static CCDirector* sharedDirector(void);

//单例

protected:

//删除导演

    void purgeDirector();

//是否在下个循环删除导演

    bool m_bPurgeDirecotorInNextLoop; // this flag(标记) will be set to true in end()

    

    void setNextScene(void);

    //fps

    void showStats();

    void createStatsLabel();


    void calculateMPF();//计算m_fSecondsPerFrame

    void getFPSImageData(unsigned char** datapointer, unsigned int* length);

    

    /** calculates delta time since last time it was called */   

 / **计算时间差,自从它最后一次被调用时起* /  

    void calculateDeltaTime();

protected:

    /* The CCEGLView, where everything is rendered */

    CCEGLView    *m_pobOpenGLView;


    double m_dAnimationInterval;//FPS value

    double m_dOldAnimationInterval;


    /* landscape mode ? */

    bool m_bLandscape;

    

    bool m_bDisplayStats;

    float m_fAccumDt;

    float m_fFrameRate;

    

    CCLabelAtlas *m_pFPSLabel;

    CCLabelAtlas *m_pSPFLabel;

    CCLabelAtlas *m_pDrawsLabel;

    

    /** Whether or not the Director is paused */

    bool m_bPaused;


    /* How many frames were called since the director started */

    unsigned int m_uTotalFrames;

    unsigned int m_uFrames;

    float m_fSecondsPerFrame;

     

    /* The running scene */

    CCScene *m_pRunningScene;

    

    /* will be the next 'runningScene' in the next frame

     nextScene is a weak reference. */

/ *下一帧将是下一个'runningScene'

     nextScene是弱引用。 * /

 CCScene *m_pNextScene;

    

    /* If YES, then "old" scene will receive the cleanup message */

    bool    m_bSendCleanupToScene;


   /* scheduled scenes */

    CCArray* m_pobScenesStack;

    

    /* last time the main loop was updated */

    struct cc_timeval *m_pLastUpdate;


    /* whether or not the next delta time will be zero */

    bool m_bNextDeltaTimeZero;

    

    /* projection used */

    ccDirectorProjection m_eProjection;


    /* window size in points */

    CCSize    m_obWinSizeInPoints;

    

    /* content scale factor */

    float    m_fContentScaleFactor;


    /* store the fps string */

    char *m_pszFPS;


    /* This object will be visited after the scene. Useful to hook a notification node */

    CCNode *m_pNotificationNode;


    /* Projection protocol delegate */

    CCDirectorDelegate *m_pProjectionDelegate;

    

    // CCEGLViewProtocol will recreate stats labels to fit visible rect

    friend class CCEGLViewProtocol;

};


/** 

 @brief DisplayLinkDirector is a Director that synchronizes(同步的)timers with the refresh(更新)rate of the display.

 

 Features and Limitations:

  - Scheduled timers & drawing are synchronizes(同步的) with the refresh(更新) rate of the display

  - Only supports animation intervals(动画间隔) of 1/60 1/30 & 1/15

 

 @since v0.8.2

 */

class CCDisplayLinkDirector : public CCDirector

{

public:

    CCDisplayLinkDirector(void) 

        : m_bInvalid(false)

    {}


    virtual void mainLoop(void);

    virtual void setAnimationInterval(double dValue);

    virtual void startAnimation(void);

    virtual void stopAnimation();


protected:

    bool m_bInvalid;

};


// end of base_node group

/// @}


NS_CC_END


#endif // __CCDIRECTOR_H__


——————————————————————————————————————————————————————————————————————————————————————————

.cpp

void CCDirector::setNextScene(void)

{

/

dynamic_cast < type-id > ( expression )
该运算符把expression转换成type-id类型的对象。Type-id必须是类的指针、类的引用或者void*
dynamic_cast运算符可以在执行期决定真正的类型。如果downcast是安全的(也就说,如果基类指针或者引用确实指向一个派生类对象)这个运算符会传回适当转型过的指针。如果downcast不安全,这个运算符会传回空指针(也就是说,基类指针或者引用没有指向一个派生类对象)。
相对于直接强转更安全
//
  bool  runningIsTransition =  dynamic_cast < CCTransitionScene *>( m_pRunningScene ) !=  NULL ;   //CCTransitionScene*.....等看完这个再往下看

    bool newIsTransition = dynamic_cast<CCTransitionScene*>(m_pNextScene) != NULL;


    // If it is not a transition, call onExit/cleanup

     if (! newIsTransition)

     {

         if (m_pRunningScene)

         {

             m_pRunningScene->onExitTransitionDidStart();

             m_pRunningScene->onExit();

         }

 

         // issue #709. the root node (scene) should receive the cleanup message too

         // otherwise it might be leaked.

         if (m_bSendCleanupToScene && m_pRunningScene)

         {

             m_pRunningScene->cleanup();

         }

     }


    if (m_pRunningScene)

    {

        m_pRunningScene->release();

    }

    m_pRunningScene = m_pNextScene;

    m_pNextScene->retain();

    m_pNextScene = NULL;


    if ((! runningIsTransition) && m_pRunningScene)

    {

        m_pRunningScene->onEnter();

        m_pRunningScene->onEnterTransitionDidFinish();

    }

}





void CCDisplayLinkDirector::mainLoop(void)

{

    if (m_bPurgeDirecotorInNextLoop)

    {

        m_bPurgeDirecotorInNextLoop = false;

        purgeDirector();

    }

    else if (! m_bInvalid)

     {

         drawScene();

     

         // release the objects

         CCPoolManager::sharedPoolManager()->pop();        

     }

}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值