本文主要讲解Cocos2d-x的整体启动过程:Cocos2d-x 在各个平台的实现代码是一样的,只要针对不同平台做相应的配置就可以了。
一、启动前奏
现在来看一下在iOS平台下的相关结构:
打开源代码自带工程,你会看到一个main文件,这里main里面有一个main函数,这是程序的入口函数。在这里它会加载AppController,进入这个类,这里有iOS平台初始化代码,但是最先执行的如下:
1
2
|
// cocos2d application instance
static
AppDelegate s_sharedApplication;
|
在这里Cocos2d-x创建了一个appDelegare的对象,当然在创建的过程中会进行相应的初始化,通过代码可以看到:
1
2
3
4
5
|
/**
@brief The cocos2d Application.
The reason to implement with private inheritance is to hide some interface details of CCDirector.
*/
class
AppDelegate :
private
cocos2d::CCApplication
|
这里就会调用CCApplicaiton的构造函数:
1
2
3
4
5
|
CCApplication::CCApplication()
{
CC_ASSERT(! sm_pSharedApplication);
sm_pSharedApplication =
this
;
//全局共享实例对象
}
|
将this赋值给了sm_pSharedApplication, 这个this是什么? 实际上this是AppDeletegate, 因为这里的调用过程中并没有涉及到父类的对象,如果要涉及应该是CCApplication::CCApplication(); C++中,在创建派生类对象的时候不会创建父类对象,只会显示或者隐式的调用父类的构造函数。
但是这里为什么会有一个没有用到的全局变量呢? 答案在后面:
1
|
cocos2d::CCApplication::sharedApplication()->run();
|
一开始定义一个static 变量就是要定义一个CCApplication的实例,然后调用run函数。
进入run函数:
1
2
3
4
5
6
7
8
|
int
CCApplication::run()
{
if
(applicationDidFinishLaunching())
{
[[CCDirectorCaller sharedDirectorCaller] startMainLoop];
}
return
0;
}
|
ok,可以看到,当applicationDidFinishLaunching执行成功后就会执行startMainLoop函数(这其实就启动了线程),分别看一下源代码:
applicationDidFinishLaunching 是CCApplication的抽象函数,在AppDelegate中实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
bool
AppDelegate::applicationDidFinishLaunching()
{
// initialize director
CCDirector *pDirector = CCDirector::sharedDirector();
pDirector->setOpenGLView(CCEGLView::sharedOpenGLView());
// turn on display FPS
pDirector->setDisplayStats(
true
);
// set FPS. the default value is 1.0/60 if you don’t call this
pDirector->setAnimationInterval(1.0 / 60);
// create a scene. it’s an autorelease object
CCScene *pScene = HelloWorld::scene();
// run
pDirector->runWithScene(pScene);
return
true
;
}
|
其实对于游戏运行来说,说白了就是一个死循环,就像win的消息那样。
来看一下startMainLoop函数:
1
2
3
4
5
6
7
8
9
|
-(
void
) startMainLoop
{
// CCDirector::setAnimationInterval() is called, we should invalidate it first
[displayLink invalidate];
displayLink = nil;
displayLink = [NSClassFromString(@
"CADisplayLink"
) displayLinkWithTarget:self selector:@selector(doCaller:)];
[displayLink setFrameInterval: self.interval];
[displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}
|
什么?没有循环? 你错了,注意的是这里加载了一个类:CADisplayLink,就是这里循环起来的,这其实是一个定时器,默认情况是每秒运行60次。CADisplayLink是一个定时器类,他能以特定的模式注册到runloop,这样每当屏幕显示内容刷新结束,runloop就会向CADisplayLink指定的target发送一次执行的selector消息,对应的毁掉函数就会调用起来。
可以看到这里有一个回调函数:
1
2
3
4
|
-(
void
) doCaller: (id) sender
{
cocos2d::CCDirector::sharedDirector()->mainLoop();
}
|
二、开始执行
在这里,我们就进入了mainLoop函数了。这里就是我们的头了:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
void
CCDisplayLinkDirector::mainLoop(
void
)
{
if
(m_bPurgeDirecotorInNextLoop)
//这个变量在end函数里会被设置成为true
{
m_bPurgeDirecotorInNextLoop =
false
;
purgeDirector();
}
else
if
(! m_bInvalid)
{
drawScene();
// release the objects
CCPoolManager::sharedPoolManager()->pop();
//每次回调都会清楚pool池(还记得之前的内存管理么)
}
}
|
好吧,这里主要的函数drawScene(),来看看主要的实现点:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
// Draw the Scene
void
CCDirector::drawScene(
void
)
{
// calculate “global” dt
calculateDeltaTime();
//距离上次main loop的时间
//tick before glClear: issue #533
if
(! m_bPaused)
//暂停
{
m_pScheduler->update(m_fDeltaTime);
//下面会解释这里的内容
}
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//函数的作用是用当前缓冲区清除值,也就是glClearColor或者glClearDepth、 glClearIndex、glClearStencil、glClearAccum等函数所指定的值来清除指定的缓冲区,也可以使用glDrawBuffer一次清除多个颜色缓存。比如:glClearColor(0.0,0.0,0.0,0.0);glClear(GL_COLOR_BUFFER_BIT);第一条语句表示清除颜色设为黑色,第二条语句表示实际完成了把整个窗口清除为黑色的任务,glClear()的唯一参数表示需要被清除的缓冲区
/* 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();
//初始化场景, 如:onEnter 或者 onExit
}
kmGLPushMatrix();
//矩阵压栈
// draw the scene
if
(m_pRunningScene)
{
m_pRunningScene->visit();
//遍历正在运行的Scene,先遍历的是CCNode的visit,因为CCScene并没有实现这个方法。
}
// draw the notifications node
if
(m_pNotificationNode)
{
m_pNotificationNode->visit();
//遍历m_pNotificationNode,可以通过该m_pNotificationNode绘制特殊的节点
}
if
(m_bDisplayStats)
{
showStats();
//左下角的fps(每秒传输的帧数)
}
kmGLPopMatrix();
//从矩阵栈中弹出
m_uTotalFrames++;
// swap buffers
if
(m_pobOpenGLView)
{
m_pobOpenGLView->swapBuffers();
}
if
(m_bDisplayStats)
{
calculateMPF();
}
}
|
我们先一步一步的看,在CCDirector中,mm文件里面有一个句:
1
|
static
CCDisplayLinkDirector *s_SharedDirector = NULL;
|
在这里CCSisplayLinkDirector是继承自CCDirector的,所以我们在运行的时候会调用:
1
2
3
4
5
6
7
8
9
|
CCDirector* CCDirector::sharedDirector(
void
)
{
if
(!s_SharedDirector)
{
s_SharedDirector =
new
CCDisplayLinkDirector();
s_SharedDirector->init();
}
return
s_SharedDirector;
}
|
而后:
1
2
3
4
5
6
7
8
9
10
11
|
bool
CCDirector::init(
void
)
{
CCLOG(“cocos2d: %s”, cocos2dVersion());
…………………
// scheduler 初始化 CCScheduler定时调度器 第二篇中会看到哟
m_pScheduler =
new
CCScheduler();
………………….
// create autorelease pool 这里CCPoolManager管理多个CCAutoreleasePool,将CCAutoreleasePool放到CCPoolManager中的m_pReleasePoolStack
CCPoolManager::sharedPoolManager()->push();
return
true
;
}
|
三、渲染开始
还记得刚刚我们看到的visit么? 他是在CCNode中实现的,我们来看一下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
void
CCNode::visit()
{
// quick return if not visible. children won’t be drawn.
if
(!m_bVisible)
//如果不可见,就会直接返回,不递归迭代
{
return
;
}
kmGLPushMatrix();
//压 入 矩阵
if
(m_pGrid && m_pGrid->isActive())
//处理CCGridBase
{
m_pGrid->beforeDraw();
}
this
->transform();
//这里的工作我们稍后还要继续看
CCNode* pNode = NULL;
unsigned
int
i = 0;
if
(m_pChildren && m_pChildren->count() > 0)
{
sortAllChildren();
// draw children zOrder < 0
ccArray *arrayData = m_pChildren->data;
for
( ; i < arrayData->num; i++ )
//遍历zOrder<0的子类
{
pNode = (CCNode*) arrayData->arr[i];
if
( pNode && pNode->m_nZOrder < 0 )
{
pNode->visit();
}
else
{
break
;
}
}
// self draw
this
->draw();
for
( ; i < arrayData->num; i++ )
{
pNode = (CCNode*) arrayData->arr[i];
if
(pNode)
{
pNode->visit();
}
}
}
else
{
this
->draw();
}
// reset for next frame
m_uOrderOfArrival = 0;
if
(m_pGrid && m_pGrid->isActive())
{
m_pGrid->afterDraw(
this
);
}
kmGLPopMatrix();
//出矩阵
}
|
刚刚看到了transform,这是做什么的呢?它是进行坐标系的变换,没有坐标系的变换,则无法在正确的位置绘制出纹理。变换矩阵等价于坐标系变换.变换矩阵是如何根据当前节点的位置、旋转角度和缩放比例等属性计算出来的了。形象地讲,transform 方法的任务就是根据当前节点的属性计算出如何把绘图坐标系变换为新坐标系的矩阵。
那就继续看transform吧:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
void
CCNode::transform()
{
kmMat4 transfrom4x4;
// Convert 3×3 into 4×4 matrix
CCAffineTransform tmpAffine =
this
->nodeToParentTransform();
//获取节点相对于父节点的变换矩阵
CGAffineToGL(&tmpAffine, transfrom4x4.mat);
//转换
// Update Z vertex manually
transfrom4x4.mat[14] = m_fVertexZ;
//设置z
kmGLMultMatrix( &transfrom4x4 );
//右乘一个矩阵 参数里面那个
// XXX: Expensive calls. Camera should be integrated into the cached affine matrix
if
( m_pCamera != NULL && !(m_pGrid != NULL && m_pGrid->isActive()) )
{
bool
translate = (m_obAnchorPointInPoints.x != 0.0f || m_obAnchorPointInPoints.y != 0.0f);
if
( translate )
kmGLTranslatef(RENDER_IN_SUBPIXEL(m_obAnchorPointInPoints.x), RENDER_IN_SUBPIXEL(m_obAnchorPointInPoints.y), 0 );
m_pCamera->locate();
if
( translate )
kmGLTranslatef(RENDER_IN_SUBPIXEL(-m_obAnchorPointInPoints.x), RENDER_IN_SUBPIXEL(-m_obAnchorPointInPoints.y), 0 );
}
}
|
一般来说游戏中会大量使用旋转,缩放,平移等仿射变换( 所谓仿射变换是指在线性变换的基础上加上平移,平移不是线性变换)。2D计算机图形学中的仿射变换通常是通过和3×3齐次矩阵相乘来实现的。Cocos2d中的仿射变换使用了Quartz 2D中的CGAffineTransform类来表示:
1
2
3
4
|
struct
CCAffineTransform {
float
a, b, c, d;
float
tx, ty;
};
typedef
struct
CGAffineTransform CGAffineTransform;
|
在Cocos2d-x中,绘制是使用了openies的,所以CGAffineTransform只是用来表示2d仿射变换的,最终还是要转化成OpenglES的4*4变换矩阵的,因为OpenGL是3d的。这个转换工作是由 CGAffineToGL来完成的。
变换后的矩阵关系如下:
1
|
| m11 m21 m31 m41 | | a c 0 tx | | m12 m22 m32 m42 | | b d 0 ty | | m13 m23 m33 m43 | <=> | 0 0 1 0 | | m14 m24 m34 m44 | | 0 0 0 1 |
|
最后来看一个概念:
“节点坐标系”指的是以一个节点作为参考而产生的坐标系,换句话说,它的任何一个子节点的坐标值都是由这个坐标系确定的,通过以上方法,我们可以方便地处理触摸点,也可以方便地计算两个不同坐标系下点之间的方向关系。
这里是整个启动过程的一部分,后面我们还会根据Cocos2d-x的内存机制和回调机制来进行分析,也会有一些深层次的渲染知识。
来源网址:http://iqll.sinaapp.com/cocos2dx-启动过程详解一:渲染/