12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514 |
-
- #include "base/CCDirector.h"
- #include <string>
- #include "2d/CCDrawingPrimitives.h"
- #include "2d/CCSpriteFrameCache.h"
- #include "platform/CCFileUtils.h"
- #include "2d/CCActionManager.h"
- #include "2d/CCFontFNT.h"
- #include "2d/CCFontAtlasCache.h"
- #include "2d/CCAnimationCache.h"
- #include "2d/CCTransition.h"
- #include "2d/CCFontFreeType.h"
- #include "2d/CCLabelAtlas.h"
- #include "renderer/CCGLProgramCache.h"
- #include "renderer/CCGLProgramStateCache.h"
- #include "renderer/CCTextureCache.h"
- #include "renderer/ccGLStateCache.h"
- #include "renderer/CCRenderer.h"
- #include "renderer/CCRenderState.h"
- #include "renderer/CCFrameBuffer.h"
- #include "2d/CCCamera.h"
- #include "base/CCUserDefault.h"
- #include "base/ccFPSImages.h"
- #include "base/CCScheduler.h"
- #include "base/ccMacros.h"
- #include "base/CCEventDispatcher.h"
- #include "base/CCEventCustom.h"
- #include "base/CCConsole.h"
- #include "base/CCAutoreleasePool.h"
- #include "base/CCConfiguration.h"
- #include "base/CCAsyncTaskPool.h"
- #include "platform/CCApplication.h"
- #if CC_ENABLE_SCRIPT_BINDING
- #include "base/CCScriptSupport.h"
- #endif
- #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
- #include "platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxEngineDataManager.h"
- #endif
- #ifndef CC_DIRECTOR_STATS_POSITION
- #define CC_DIRECTOR_STATS_POSITION Director::getInstance()->getVisibleOrigin()
- #endif
- using namespace std;
- NS_CC_BEGIN
- static Director *s_SharedDirector = nullptr;
- #define kDefaultFPS 60
- extern const char* cocos2dVersion(void);
- const char *Director::EVENT_BEFORE_SET_NEXT_SCENE = "director_before_set_next_scene";
- const char *Director::EVENT_AFTER_SET_NEXT_SCENE = "director_after_set_next_scene";
- const char *Director::EVENT_PROJECTION_CHANGED = "director_projection_changed";
- const char *Director::EVENT_AFTER_DRAW = "director_after_draw";
- const char *Director::EVENT_AFTER_VISIT = "director_after_visit";
- const char *Director::EVENT_BEFORE_UPDATE = "director_before_update";
- const char *Director::EVENT_AFTER_UPDATE = "director_after_update";
- const char *Director::EVENT_RESET = "director_reset";
- Director* Director::getInstance()
- {
- if (!s_SharedDirector)
- {
- s_SharedDirector = new (std::nothrow) Director;
- CCASSERT(s_SharedDirector, "FATAL: Not enough memory");
- s_SharedDirector->init();
- }
- return s_SharedDirector;
- }
- Director::Director()
- : _isStatusLabelUpdated(true)
- , _invalid(true)
- {
- }
- bool Director::init(void)
- {
- setDefaultValues();
-
- _runningScene = nullptr;
- _nextScene = nullptr;
- _notificationNode = nullptr;
- _scenesStack.reserve(15);
-
- _accumDt = 0.0f;
- _frameRate = 0.0f;
- _FPSLabel = _drawnBatchesLabel = _drawnVerticesLabel = nullptr;
- _totalFrames = 0;
- _lastUpdate = std::chrono::steady_clock::now();
-
- _secondsPerFrame = 1.0f;
- _frames = 0;
-
- _paused = false;
-
- _purgeDirectorInNextLoop = false;
-
-
- _restartDirectorInNextLoop = false;
-
-
- _invalid = false;
- _winSizeInPoints = Size::ZERO;
- _openGLView = nullptr;
- _defaultFBO = nullptr;
-
- _contentScaleFactor = 1.0f;
- _console = new (std::nothrow) Console;
-
- _scheduler = new (std::nothrow) Scheduler();
-
- _actionManager = new (std::nothrow) ActionManager();
- _scheduler->scheduleUpdate(_actionManager, Scheduler::PRIORITY_SYSTEM, false);
- _eventDispatcher = new (std::nothrow) EventDispatcher();
-
- _beforeSetNextScene = new (std::nothrow) EventCustom(EVENT_BEFORE_SET_NEXT_SCENE);
- _beforeSetNextScene->setUserData(this);
- _afterSetNextScene = new (std::nothrow) EventCustom(EVENT_AFTER_SET_NEXT_SCENE);
- _afterSetNextScene->setUserData(this);
- _eventAfterDraw = new (std::nothrow) EventCustom(EVENT_AFTER_DRAW);
- _eventAfterDraw->setUserData(this);
- _eventAfterVisit = new (std::nothrow) EventCustom(EVENT_AFTER_VISIT);
- _eventAfterVisit->setUserData(this);
- _eventBeforeUpdate = new (std::nothrow) EventCustom(EVENT_BEFORE_UPDATE);
- _eventBeforeUpdate->setUserData(this);
- _eventAfterUpdate = new (std::nothrow) EventCustom(EVENT_AFTER_UPDATE);
- _eventAfterUpdate->setUserData(this);
- _eventProjectionChanged = new (std::nothrow) EventCustom(EVENT_PROJECTION_CHANGED);
- _eventProjectionChanged->setUserData(this);
- _eventResetDirector = new (std::nothrow) EventCustom(EVENT_RESET);
-
- initTextureCache();
- initMatrixStack();
- _renderer = new (std::nothrow) Renderer;
- RenderState::initialize();
- #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
- EngineDataManager::init();
- #endif
- return true;
- }
- Director::~Director(void)
- {
- CCLOGINFO("deallocing Director: %p", this);
- CC_SAFE_RELEASE(_FPSLabel);
- CC_SAFE_RELEASE(_drawnVerticesLabel);
- CC_SAFE_RELEASE(_drawnBatchesLabel);
- CC_SAFE_RELEASE(_runningScene);
- CC_SAFE_RELEASE(_notificationNode);
- CC_SAFE_RELEASE(_scheduler);
- CC_SAFE_RELEASE(_actionManager);
- CC_SAFE_DELETE(_defaultFBO);
-
- CC_SAFE_RELEASE(_beforeSetNextScene);
- CC_SAFE_RELEASE(_afterSetNextScene);
- CC_SAFE_RELEASE(_eventBeforeUpdate);
- CC_SAFE_RELEASE(_eventAfterUpdate);
- CC_SAFE_RELEASE(_eventAfterDraw);
- CC_SAFE_RELEASE(_eventAfterVisit);
- CC_SAFE_RELEASE(_eventProjectionChanged);
- CC_SAFE_RELEASE(_eventResetDirector);
- delete _renderer;
- delete _console;
- CC_SAFE_RELEASE(_eventDispatcher);
-
- Configuration::destroyInstance();
- s_SharedDirector = nullptr;
- }
- void Director::setDefaultValues(void)
- {
- Configuration *conf = Configuration::getInstance();
-
- double fps = conf->getValue("cocos2d.x.fps", Value(kDefaultFPS)).asDouble();
- _oldAnimationInterval = _animationInterval = 1.0 / fps;
-
- _displayStats = conf->getValue("cocos2d.x.display_fps", Value(false)).asBool();
-
- std::string projection = conf->getValue("cocos2d.x.gl.projection", Value("3d")).asString();
- if (projection == "3d")
- _projection = Projection::_3D;
- else if (projection == "2d")
- _projection = Projection::_2D;
- else if (projection == "custom")
- _projection = Projection::CUSTOM;
- else
- CCASSERT(false, "Invalid projection value");
-
- std::string pixel_format = conf->getValue("cocos2d.x.texture.pixel_format_for_png", Value("rgba8888")).asString();
- if (pixel_format == "rgba8888")
- Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888);
- else if(pixel_format == "rgba4444")
- Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444);
- else if(pixel_format == "rgba5551")
- Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGB5A1);
-
- bool pvr_alpha_premultiplied = conf->getValue("cocos2d.x.texture.pvrv2_has_alpha_premultiplied", Value(false)).asBool();
- Image::setPVRImagesHavePremultipliedAlpha(pvr_alpha_premultiplied);
- }
- void Director::setGLDefaultValues()
- {
-
- CCASSERT(_openGLView, "opengl view should not be null");
- setAlphaBlending(true);
- setDepthTest(false);
- setProjection(_projection);
- }
- void Director::drawScene()
- {
-
- calculateDeltaTime();
-
- if (_openGLView)
- {
- _openGLView->pollEvents();
- }
-
- if (! _paused)
- {
- _eventDispatcher->dispatchEvent(_eventBeforeUpdate);
- _scheduler->update(_deltaTime);
- _eventDispatcher->dispatchEvent(_eventAfterUpdate);
- }
- _renderer->clear();
- experimental::FrameBuffer::clearAllFBOs();
-
- if (_nextScene)
- {
- setNextScene();
- }
- pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
-
- if (_runningScene)
- {
- #if (CC_USE_PHYSICS || (CC_USE_3D_PHYSICS && CC_ENABLE_BULLET_INTEGRATION) || CC_USE_NAVMESH)
- _runningScene->stepPhysicsAndNavigation(_deltaTime);
- #endif
-
- _renderer->clearDrawStats();
-
-
- _openGLView->renderScene(_runningScene, _renderer);
-
- _eventDispatcher->dispatchEvent(_eventAfterVisit);
- }
-
- if (_notificationNode)
- {
- _notificationNode->visit(_renderer, Mat4::IDENTITY, 0);
- }
- updateFrameRate();
-
- if (_displayStats)
- {
- showStats();
- }
-
- _renderer->render();
- _eventDispatcher->dispatchEvent(_eventAfterDraw);
- popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
- _totalFrames++;
-
- if (_openGLView)
- {
- _openGLView->swapBuffers();
- }
- if (_displayStats)
- {
- calculateMPF();
- }
- }
- void Director::calculateDeltaTime()
- {
- auto now = std::chrono::steady_clock::now();
-
- if (_nextDeltaTimeZero)
- {
- _deltaTime = 0;
- _nextDeltaTimeZero = false;
- }
- else
- {
- _deltaTime = std::chrono::duration_cast<std::chrono::microseconds>(now - _lastUpdate).count() / 1000000.0f;
- _deltaTime = MAX(0, _deltaTime);
- }
- #if COCOS2D_DEBUG
-
- if (_deltaTime > 0.2f)
- {
- _deltaTime = 1 / 60.0f;
- }
- #endif
- _lastUpdate = now;
- }
- float Director::getDeltaTime() const
- {
- return _deltaTime;
- }
- void Director::setOpenGLView(GLView *openGLView)
- {
- CCASSERT(openGLView, "opengl view should not be null");
- if (_openGLView != openGLView)
- {
-
- Configuration *conf = Configuration::getInstance();
- conf->gatherGPUInfo();
- CCLOG("%s\n",conf->getInfo().c_str());
- if(_openGLView)
- _openGLView->release();
- _openGLView = openGLView;
- _openGLView->retain();
-
- _winSizeInPoints = _openGLView->getDesignResolutionSize();
- _isStatusLabelUpdated = true;
- if (_openGLView)
- {
- setGLDefaultValues();
- }
- _renderer->initGLView();
- CHECK_GL_ERROR_DEBUG();
- if (_eventDispatcher)
- {
- _eventDispatcher->setEnabled(true);
- }
-
- _defaultFBO = experimental::FrameBuffer::getOrCreateDefaultFBO(_openGLView);
- _defaultFBO->retain();
- }
- }
- TextureCache* Director::getTextureCache() const
- {
- return _textureCache;
- }
- void Director::initTextureCache()
- {
- _textureCache = new (std::nothrow) TextureCache();
- }
- void Director::destroyTextureCache()
- {
- if (_textureCache)
- {
- _textureCache->waitForQuit();
- CC_SAFE_RELEASE_NULL(_textureCache);
- }
- }
- void Director::setViewport()
- {
- if (_openGLView)
- {
- _openGLView->setViewPortInPoints(0, 0, _winSizeInPoints.width, _winSizeInPoints.height);
- }
- }
- void Director::setNextDeltaTimeZero(bool nextDeltaTimeZero)
- {
- _nextDeltaTimeZero = nextDeltaTimeZero;
- }
- void Director::initMatrixStack()
- {
- while (!_modelViewMatrixStack.empty())
- {
- _modelViewMatrixStack.pop();
- }
- _projectionMatrixStackList.clear();
- while (!_textureMatrixStack.empty())
- {
- _textureMatrixStack.pop();
- }
- _modelViewMatrixStack.push(Mat4::IDENTITY);
- std::stack<Mat4> projectionMatrixStack;
- projectionMatrixStack.push(Mat4::IDENTITY);
- _projectionMatrixStackList.push_back(projectionMatrixStack);
- _textureMatrixStack.push(Mat4::IDENTITY);
- }
- void Director::resetMatrixStack()
- {
- initMatrixStack();
- }
- void Director::initProjectionMatrixStack(size_t stackCount)
- {
- _projectionMatrixStackList.clear();
- std::stack<Mat4> projectionMatrixStack;
- projectionMatrixStack.push(Mat4::IDENTITY);
- for (size_t i = 0; i < stackCount; ++i)
- _projectionMatrixStackList.push_back(projectionMatrixStack);
- }
- size_t Director::getProjectionMatrixStackSize()
- {
- return _projectionMatrixStackList.size();
- }
- void Director::popMatrix(MATRIX_STACK_TYPE type)
- {
- if(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW == type)
- {
- _modelViewMatrixStack.pop();
- }
- else if(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION == type)
- {
- _projectionMatrixStackList[0].pop();
- }
- else if(MATRIX_STACK_TYPE::MATRIX_STACK_TEXTURE == type)
- {
- _textureMatrixStack.pop();
- }
- else
- {
- CCASSERT(false, "unknown matrix stack type");
- }
- }
- void Director::popProjectionMatrix(size_t index)
- {
- _projectionMatrixStackList[index].pop();
- }
- void Director::loadIdentityMatrix(MATRIX_STACK_TYPE type)
- {
- if(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW == type)
- {
- _modelViewMatrixStack.top() = Mat4::IDENTITY;
- }
- else if(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION == type)
- {
- _projectionMatrixStackList[0].top() = Mat4::IDENTITY;
- }
- else if(MATRIX_STACK_TYPE::MATRIX_STACK_TEXTURE == type)
- {
- _textureMatrixStack.top() = Mat4::IDENTITY;
- }
- else
- {
- CCASSERT(false, "unknown matrix stack type");
- }
- }
- void Director::loadProjectionIdentityMatrix(size_t index)
- {
- _projectionMatrixStackList[index].top() = Mat4::IDENTITY;
- }
- void Director::loadMatrix(MATRIX_STACK_TYPE type, const Mat4& mat)
- {
- if(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW == type)
- {
- _modelViewMatrixStack.top() = mat;
- }
- else if(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION == type)
- {
- _projectionMatrixStackList[0].top() = mat;
- }
- else if(MATRIX_STACK_TYPE::MATRIX_STACK_TEXTURE == type)
- {
- _textureMatrixStack.top() = mat;
- }
- else
- {
- CCASSERT(false, "unknown matrix stack type");
- }
- }
- void Director::loadProjectionMatrix(const Mat4& mat, size_t index)
- {
- _projectionMatrixStackList[index].top() = mat;
- }
- void Director::multiplyMatrix(MATRIX_STACK_TYPE type, const Mat4& mat)
- {
- if(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW == type)
- {
- _modelViewMatrixStack.top() *= mat;
- }
- else if(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION == type)
- {
- _projectionMatrixStackList[0].top() *= mat;
- }
- else if(MATRIX_STACK_TYPE::MATRIX_STACK_TEXTURE == type)
- {
- _textureMatrixStack.top() *= mat;
- }
- else
- {
- CCASSERT(false, "unknown matrix stack type");
- }
- }
- void Director::multiplyProjectionMatrix(const Mat4& mat, size_t index)
- {
- _projectionMatrixStackList[index].top() *= mat;
- }
- void Director::pushMatrix(MATRIX_STACK_TYPE type)
- {
- if(type == MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW)
- {
- _modelViewMatrixStack.push(_modelViewMatrixStack.top());
- }
- else if(type == MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION)
- {
- _projectionMatrixStackList[0].push(_projectionMatrixStackList[0].top());
- }
- else if(type == MATRIX_STACK_TYPE::MATRIX_STACK_TEXTURE)
- {
- _textureMatrixStack.push(_textureMatrixStack.top());
- }
- else
- {
- CCASSERT(false, "unknown matrix stack type");
- }
- }
- void Director::pushProjectionMatrix(size_t index)
- {
- _projectionMatrixStackList[index].push(_projectionMatrixStackList[index].top());
- }
- const Mat4& Director::getMatrix(MATRIX_STACK_TYPE type) const
- {
- if(type == MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW)
- {
- return _modelViewMatrixStack.top();
- }
- else if(type == MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION)
- {
- return _projectionMatrixStackList[0].top();
- }
- else if(type == MATRIX_STACK_TYPE::MATRIX_STACK_TEXTURE)
- {
- return _textureMatrixStack.top();
- }
- CCASSERT(false, "unknown matrix stack type, will return modelview matrix instead");
- return _modelViewMatrixStack.top();
- }
- const Mat4& Director::getProjectionMatrix(size_t index) const
- {
- return _projectionMatrixStackList[index].top();
- }
- void Director::setProjection(Projection projection)
- {
- Size size = _winSizeInPoints;
- if (size.width == 0 || size.height == 0)
- {
- CCLOGERROR("cocos2d: warning, Director::setProjection() failed because size is 0");
- return;
- }
- setViewport();
- switch (projection)
- {
- case Projection::_2D:
- {
- Mat4 orthoMatrix;
- Mat4::createOrthographicOffCenter(0, size.width, 0, size.height, -1024, 1024, &orthoMatrix);
- loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION, orthoMatrix);
- loadIdentityMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
- break;
- }
-
- case Projection::_3D:
- {
- float zeye = this->getZEye();
- Mat4 matrixPerspective, matrixLookup;
-
- Mat4::createPerspective(60, (GLfloat)size.width/size.height, 10, zeye+size.height/2, &matrixPerspective);
- Vec3 eye(size.width/2, size.height/2, zeye), center(size.width/2, size.height/2, 0.0f), up(0.0f, 1.0f, 0.0f);
- Mat4::createLookAt(eye, center, up, &matrixLookup);
- Mat4 proj3d = matrixPerspective * matrixLookup;
- loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION, proj3d);
- loadIdentityMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
- break;
- }
- case Projection::CUSTOM:
-
-
- break;
- default:
- CCLOG("cocos2d: Director: unrecognized projection");
- break;
- }
- _projection = projection;
- GL::setProjectionMatrixDirty();
- _eventDispatcher->dispatchEvent(_eventProjectionChanged);
- }
- void Director::purgeCachedData(void)
- {
- FontFNT::purgeCachedData();
- FontAtlasCache::purgeCachedData();
- if (s_SharedDirector->getOpenGLView())
- {
- SpriteFrameCache::getInstance()->removeUnusedSpriteFrames();
- _textureCache->removeUnusedTextures();
-
-
- log("%s\n", _textureCache->getCachedTextureInfo().c_str());
- }
- FileUtils::getInstance()->purgeCachedEntries();
- }
- float Director::getZEye(void) const
- {
- return (_winSizeInPoints.height / 1.1566f);
- }
- void Director::setAlphaBlending(bool on)
- {
- if (on)
- {
- GL::blendFunc(CC_BLEND_SRC, CC_BLEND_DST);
- }
- else
- {
- GL::blendFunc(GL_ONE, GL_ZERO);
- }
- CHECK_GL_ERROR_DEBUG();
- }
- void Director::setDepthTest(bool on)
- {
- _renderer->setDepthTest(on);
- }
- void Director::setClearColor(const Color4F& clearColor)
- {
- _renderer->setClearColor(clearColor);
- auto defaultFBO = experimental::FrameBuffer::getOrCreateDefaultFBO(_openGLView);
-
- if(defaultFBO) defaultFBO->setClearColor(clearColor);
- }
- static void GLToClipTransform(Mat4 *transformOut)
- {
- if(nullptr == transformOut) return;
-
- Director* director = Director::getInstance();
- CCASSERT(nullptr != director, "Director is null when setting matrix stack");
- auto projection = director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
- auto modelview = director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
- *transformOut = projection * modelview;
- }
- Vec2 Director::convertToGL(const Vec2& uiPoint)
- {
- Mat4 transform;
- GLToClipTransform(&transform);
- Mat4 transformInv = transform.getInversed();
-
- float zClip = transform.m[14]/transform.m[15];
- Size glSize = _openGLView->getDesignResolutionSize();
- Vec4 clipCoord(2.0f*uiPoint.x/glSize.width - 1.0f, 1.0f - 2.0f*uiPoint.y/glSize.height, zClip, 1);
- Vec4 glCoord;
-
- transformInv.transformVector(clipCoord, &glCoord);
- float factor = 1.0f / glCoord.w;
- return Vec2(glCoord.x * factor, glCoord.y * factor);
- }
- Vec2 Director::convertToUI(const Vec2& glPoint)
- {
- Mat4 transform;
- GLToClipTransform(&transform);
- Vec4 clipCoord;
-
- Vec4 glCoord(glPoint.x, glPoint.y, 0.0, 1);
- transform.transformVector(glCoord, &clipCoord);
-
-
- clipCoord.x = clipCoord.x / clipCoord.w;
- clipCoord.y = clipCoord.y / clipCoord.w;
- clipCoord.z = clipCoord.z / clipCoord.w;
- Size glSize = _openGLView->getDesignResolutionSize();
- float factor = 1.0f / glCoord.w;
- return Vec2(glSize.width * (clipCoord.x * 0.5f + 0.5f) * factor, glSize.height * (-clipCoord.y * 0.5f + 0.5f) * factor);
- }
- const Size& Director::getWinSize(void) const
- {
- return _winSizeInPoints;
- }
- Size Director::getWinSizeInPixels() const
- {
- return Size(_winSizeInPoints.width * _contentScaleFactor, _winSizeInPoints.height * _contentScaleFactor);
- }
- Size Director::getVisibleSize() const
- {
- if (_openGLView)
- {
- return _openGLView->getVisibleSize();
- }
- else
- {
- return Size::ZERO;
- }
- }
- Vec2 Director::getVisibleOrigin() const
- {
- if (_openGLView)
- {
- return _openGLView->getVisibleOrigin();
- }
- else
- {
- return Vec2::ZERO;
- }
- }
- void Director::runWithScene(Scene *scene)
- {
- CCASSERT(scene != nullptr, "This command can only be used to start the Director. There is already a scene present.");
- CCASSERT(_runningScene == nullptr, "_runningScene should be null");
- pushScene(scene);
- startAnimation();
- }
- void Director::replaceScene(Scene *scene)
- {
-
- CCASSERT(scene != nullptr, "the scene should not be null");
-
- if (_runningScene == nullptr) {
- runWithScene(scene);
- return;
- }
-
- if (scene == _nextScene)
- return;
-
- if (_nextScene)
- {
- if (_nextScene->isRunning())
- {
- _nextScene->onExit();
- }
- _nextScene->cleanup();
- _nextScene = nullptr;
- }
- ssize_t index = _scenesStack.size() - 1;
- _sendCleanupToScene = true;
- #if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
- auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();
- if (sEngine)
- {
- sEngine->retainScriptObject(this, scene);
- sEngine->releaseScriptObject(this, _scenesStack.at(index));
- }
- #endif
- _scenesStack.replace(index, scene);
- _nextScene = scene;
- }
- void Director::pushScene(Scene *scene)
- {
- CCASSERT(scene, "the scene should not null");
- _sendCleanupToScene = false;
- #if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
- auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();
- if (sEngine)
- {
- sEngine->retainScriptObject(this, scene);
- }
- #endif
- _scenesStack.pushBack(scene);
- _nextScene = scene;
- }
- void Director::popScene(void)
- {
- CCASSERT(_runningScene != nullptr, "running scene should not null");
-
- #if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
- auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();
- if (sEngine)
- {
- sEngine->releaseScriptObject(this, _scenesStack.back());
- }
- #endif
- _scenesStack.popBack();
- ssize_t c = _scenesStack.size();
- if (c == 0)
- {
- end();
- }
- else
- {
- _sendCleanupToScene = true;
- _nextScene = _scenesStack.at(c - 1);
- }
- }
- void Director::popToRootScene(void)
- {
- popToSceneStackLevel(1);
- }
- void Director::popToSceneStackLevel(int level)
- {
- CCASSERT(_runningScene != nullptr, "A running Scene is needed");
- ssize_t c = _scenesStack.size();
-
- if (level == 0)
- {
- end();
- return;
- }
-
- if (level >= c)
- return;
- auto firstOnStackScene = _scenesStack.back();
- if (firstOnStackScene == _runningScene)
- {
- #if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
- auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();
- if (sEngine)
- {
- sEngine->releaseScriptObject(this, _scenesStack.back());
- }
- #endif
- _scenesStack.popBack();
- --c;
- }
-
- while (c > level)
- {
- auto current = _scenesStack.back();
- if (current->isRunning())
- {
- current->onExit();
- }
- current->cleanup();
- #if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
- auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();
- if (sEngine)
- {
- sEngine->releaseScriptObject(this, _scenesStack.back());
- }
- #endif
- _scenesStack.popBack();
- --c;
- }
- _nextScene = _scenesStack.back();
-
- _sendCleanupToScene = true;
- }
- void Director::end()
- {
- _purgeDirectorInNextLoop = true;
- }
- void Director::restart()
- {
- _restartDirectorInNextLoop = true;
- }
- void Director::reset()
- {
- #if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
- auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();
- #endif
-
- if (_runningScene)
- {
- #if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
- if (sEngine)
- {
- sEngine->releaseScriptObject(this, _runningScene);
- }
- #endif
- _runningScene->onExit();
- _runningScene->cleanup();
- _runningScene->release();
- }
-
- _runningScene = nullptr;
- _nextScene = nullptr;
- _eventDispatcher->dispatchEvent(_eventResetDirector);
-
-
- getScheduler()->unscheduleAll();
-
-
- if (_eventDispatcher)
- {
- _eventDispatcher->removeAllEventListeners();
- }
-
- if(_notificationNode)
- {
- _notificationNode->onExit();
- _notificationNode->cleanup();
- _notificationNode->release();
- }
-
- _notificationNode = nullptr;
-
-
-
- #if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
- if (sEngine)
- {
- for (const auto &scene : _scenesStack)
- {
- if (scene)
- sEngine->releaseScriptObject(this, scene);
- }
- }
- #endif
- _scenesStack.clear();
-
- stopAnimation();
-
- CC_SAFE_RELEASE_NULL(_notificationNode);
- CC_SAFE_RELEASE_NULL(_FPSLabel);
- CC_SAFE_RELEASE_NULL(_drawnBatchesLabel);
- CC_SAFE_RELEASE_NULL(_drawnVerticesLabel);
-
-
- FontFNT::purgeCachedData();
- FontAtlasCache::purgeCachedData();
-
- FontFreeType::shutdownFreeType();
-
-
-
- #if defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)))
- #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
- #elif _MSC_VER >= 1400
- #pragma warning (push)
- #pragma warning (disable: 4996)
- #endif
- #ifndef __clang_analyzer__
- DrawPrimitives::free();
- #endif
- #if defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)))
- #pragma GCC diagnostic warning "-Wdeprecated-declarations"
- #elif _MSC_VER >= 1400
- #pragma warning (pop)
- #endif
- AnimationCache::destroyInstance();
- SpriteFrameCache::destroyInstance();
- GLProgramCache::destroyInstance();
- GLProgramStateCache::destroyInstance();
- FileUtils::destroyInstance();
- AsyncTaskPool::destroyInstance();
-
-
- UserDefault::destroyInstance();
-
- GL::invalidateStateCache();
- RenderState::finalize();
-
- destroyTextureCache();
- }
- void Director::purgeDirector()
- {
- reset();
- CHECK_GL_ERROR_DEBUG();
-
-
- if (_openGLView)
- {
- _openGLView->end();
- _openGLView = nullptr;
- }
- #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
- EngineDataManager::destroy();
- #endif
-
- release();
- }
- void Director::restartDirector()
- {
- reset();
-
-
- RenderState::initialize();
-
- initTextureCache();
-
-
- getScheduler()->scheduleUpdate(getActionManager(), Scheduler::PRIORITY_SYSTEM, false);
-
-
- PoolManager::getInstance()->getCurrentPool()->clear();
-
- startAnimation();
-
-
- #if CC_ENABLE_SCRIPT_BINDING
- ScriptEvent scriptEvent(kRestartGame, nullptr);
- ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent);
- #endif
- }
- void Director::setNextScene()
- {
- _eventDispatcher->dispatchEvent(_beforeSetNextScene);
- bool runningIsTransition = dynamic_cast<TransitionScene*>(_runningScene) != nullptr;
- bool newIsTransition = dynamic_cast<TransitionScene*>(_nextScene) != nullptr;
-
- if (! newIsTransition)
- {
- if (_runningScene)
- {
- _runningScene->onExitTransitionDidStart();
- _runningScene->onExit();
- }
-
-
-
- if (_sendCleanupToScene && _runningScene)
- {
- _runningScene->cleanup();
- }
- }
- if (_runningScene)
- {
- _runningScene->release();
- }
- _runningScene = _nextScene;
- _nextScene->retain();
- _nextScene = nullptr;
- if ((! runningIsTransition) && _runningScene)
- {
- _runningScene->onEnter();
- _runningScene->onEnterTransitionDidFinish();
- }
-
- _eventDispatcher->dispatchEvent(_afterSetNextScene);
- }
- void Director::pause()
- {
- if (_paused)
- {
- return;
- }
- _oldAnimationInterval = _animationInterval;
-
- setAnimationInterval(1 / 4.0, SetIntervalReason::BY_DIRECTOR_PAUSE);
- _paused = true;
- }
- void Director::resume()
- {
- if (! _paused)
- {
- return;
- }
- setAnimationInterval(_oldAnimationInterval, SetIntervalReason::BY_ENGINE);
- _paused = false;
- _deltaTime = 0;
-
- setNextDeltaTimeZero(true);
- }
- void Director::updateFrameRate()
- {
-
- _frameRate = 1.0f / _deltaTime;
- }
- void Director::showStats()
- {
- if (_isStatusLabelUpdated)
- {
- createStatsLabel();
- _isStatusLabelUpdated = false;
- }
- static unsigned long prevCalls = 0;
- static unsigned long prevVerts = 0;
- ++_frames;
- _accumDt += _deltaTime;
-
- if (_displayStats && _FPSLabel && _drawnBatchesLabel && _drawnVerticesLabel)
- {
- char buffer[30] = {0};
-
-
-
- if (_accumDt > CC_DIRECTOR_STATS_INTERVAL)
- {
- sprintf(buffer, "%.1f / %.3f", _frames / _accumDt, _secondsPerFrame);
- _FPSLabel->setString(buffer);
- _accumDt = 0;
- _frames = 0;
- }
- auto currentCalls = (unsigned long)_renderer->getDrawnBatches();
- auto currentVerts = (unsigned long)_renderer->getDrawnVertices();
- if( currentCalls != prevCalls ) {
- sprintf(buffer, "GL calls:%6lu", currentCalls);
- _drawnBatchesLabel->setString(buffer);
- prevCalls = currentCalls;
- }
- if( currentVerts != prevVerts) {
- sprintf(buffer, "GL verts:%6lu", currentVerts);
- _drawnVerticesLabel->setString(buffer);
- prevVerts = currentVerts;
- }
- const Mat4& identity = Mat4::IDENTITY;
- _drawnVerticesLabel->visit(_renderer, identity, 0);
- _drawnBatchesLabel->visit(_renderer, identity, 0);
- _FPSLabel->visit(_renderer, identity, 0);
- }
- }
- void Director::calculateMPF()
- {
- static float prevSecondsPerFrame = 0;
- static const float MPF_FILTER = 0.10f;
- auto now = std::chrono::steady_clock::now();
-
- _secondsPerFrame = std::chrono::duration_cast<std::chrono::microseconds>(now - _lastUpdate).count() / 1000000.0f;
- _secondsPerFrame = _secondsPerFrame * MPF_FILTER + (1-MPF_FILTER) * prevSecondsPerFrame;
- prevSecondsPerFrame = _secondsPerFrame;
- }
- void Director::getFPSImageData(unsigned char** datapointer, ssize_t* length)
- {
-
- *datapointer = cc_fps_images_png;
- *length = cc_fps_images_len();
- }
- void Director::createStatsLabel()
- {
- Texture2D *texture = nullptr;
- std::string fpsString = "00.0";
- std::string drawBatchString = "000";
- std::string drawVerticesString = "00000";
- if (_FPSLabel)
- {
- fpsString = _FPSLabel->getString();
- drawBatchString = _drawnBatchesLabel->getString();
- drawVerticesString = _drawnVerticesLabel->getString();
-
- CC_SAFE_RELEASE_NULL(_FPSLabel);
- CC_SAFE_RELEASE_NULL(_drawnBatchesLabel);
- CC_SAFE_RELEASE_NULL(_drawnVerticesLabel);
- _textureCache->removeTextureForKey("/cc_fps_images");
- FileUtils::getInstance()->purgeCachedEntries();
- }
- Texture2D::PixelFormat currentFormat = Texture2D::getDefaultAlphaPixelFormat();
- Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444);
- unsigned char *data = nullptr;
- ssize_t dataLength = 0;
- getFPSImageData(&data, &dataLength);
- Image* image = new (std::nothrow) Image();
- bool isOK = image->initWithImageData(data, dataLength);
- if (! isOK) {
- CCLOGERROR("%s", "Fails: init fps_images");
- return;
- }
- texture = _textureCache->addImage(image, "/cc_fps_images");
- CC_SAFE_RELEASE(image);
-
- float scaleFactor = 1 / CC_CONTENT_SCALE_FACTOR();
- _FPSLabel = LabelAtlas::create();
- _FPSLabel->retain();
- _FPSLabel->setIgnoreContentScaleFactor(true);
- _FPSLabel->initWithString(fpsString, texture, 12, 32 , '.');
- _FPSLabel->setScale(scaleFactor);
- _drawnBatchesLabel = LabelAtlas::create();
- _drawnBatchesLabel->retain();
- _drawnBatchesLabel->setIgnoreContentScaleFactor(true);
- _drawnBatchesLabel->initWithString(drawBatchString, texture, 12, 32, '.');
- _drawnBatchesLabel->setScale(scaleFactor);
- _drawnVerticesLabel = LabelAtlas::create();
- _drawnVerticesLabel->retain();
- _drawnVerticesLabel->setIgnoreContentScaleFactor(true);
- _drawnVerticesLabel->initWithString(drawVerticesString, texture, 12, 32, '.');
- _drawnVerticesLabel->setScale(scaleFactor);
- Texture2D::setDefaultAlphaPixelFormat(currentFormat);
- const int height_spacing = 22 / CC_CONTENT_SCALE_FACTOR();
- _drawnVerticesLabel->setPosition(Vec2(0, height_spacing*2) + CC_DIRECTOR_STATS_POSITION);
- _drawnBatchesLabel->setPosition(Vec2(0, height_spacing*1) + CC_DIRECTOR_STATS_POSITION);
- _FPSLabel->setPosition(Vec2(0, height_spacing*0)+CC_DIRECTOR_STATS_POSITION);
- }
- void Director::setContentScaleFactor(float scaleFactor)
- {
- if (scaleFactor != _contentScaleFactor)
- {
- _contentScaleFactor = scaleFactor;
- _isStatusLabelUpdated = true;
- }
- }
- void Director::setNotificationNode(Node *node)
- {
- if (_notificationNode != nullptr){
- _notificationNode->onExitTransitionDidStart();
- _notificationNode->onExit();
- _notificationNode->cleanup();
- }
- CC_SAFE_RELEASE(_notificationNode);
- _notificationNode = node;
- if (node == nullptr)
- return;
- _notificationNode->onEnter();
- _notificationNode->onEnterTransitionDidFinish();
- CC_SAFE_RETAIN(_notificationNode);
- }
- void Director::setScheduler(Scheduler* scheduler)
- {
- if (_scheduler != scheduler)
- {
- CC_SAFE_RETAIN(scheduler);
- CC_SAFE_RELEASE(_scheduler);
- _scheduler = scheduler;
- }
- }
- void Director::setActionManager(ActionManager* actionManager)
- {
- if (_actionManager != actionManager)
- {
- CC_SAFE_RETAIN(actionManager);
- CC_SAFE_RELEASE(_actionManager);
- _actionManager = actionManager;
- }
- }
- void Director::setEventDispatcher(EventDispatcher* dispatcher)
- {
- if (_eventDispatcher != dispatcher)
- {
- CC_SAFE_RETAIN(dispatcher);
- CC_SAFE_RELEASE(_eventDispatcher);
- _eventDispatcher = dispatcher;
- }
- }
- void Director::startAnimation()
- {
- startAnimation(SetIntervalReason::BY_ENGINE);
- }
- void Director::startAnimation(SetIntervalReason reason)
- {
- _lastUpdate = std::chrono::steady_clock::now();
- _invalid = false;
- _cocos2d_thread_id = std::this_thread::get_id();
- Application::getInstance()->setAnimationInterval(_animationInterval, reason);
-
- setNextDeltaTimeZero(true);
- }
- void Director::mainLoop()
- {
- if (_purgeDirectorInNextLoop)
- {
- _purgeDirectorInNextLoop = false;
- purgeDirector();
- }
- else if (_restartDirectorInNextLoop)
- {
- _restartDirectorInNextLoop = false;
- restartDirector();
- }
- else if (! _invalid)
- {
- drawScene();
-
-
- PoolManager::getInstance()->getCurrentPool()->clear();
- }
- }
- void Director::stopAnimation()
- {
- _invalid = true;
- }
- void Director::setAnimationInterval(float interval)
- {
- setAnimationInterval(interval, SetIntervalReason::BY_GAME);
- }
- void Director::setAnimationInterval(float interval, SetIntervalReason reason)
- {
- _animationInterval = interval;
- if (! _invalid)
- {
- stopAnimation();
- startAnimation(reason);
- }
- }
- NS_CC_END
|