From 2027d2f752421bd22c436ef559a0929150af81f5 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Wed, 18 Oct 2017 17:13:54 +0800 Subject: [PATCH 01/35] fix fireball/issues/6475 --- .../android/java/src/org/cocos2dx/lib/Cocos2dxVideoView.java | 1 - 1 file changed, 1 deletion(-) diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoView.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoView.java index 67e15a697d..09c34cc1c0 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoView.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoView.java @@ -422,7 +422,6 @@ public class Cocos2dxVideoView extends SurfaceView implements MediaPlayerControl mCurrentState = STATE_PLAYBACK_COMPLETED; mTargetState = STATE_PLAYBACK_COMPLETED; - release(true); if (mOnVideoEventListener != null) { mOnVideoEventListener.onVideoEvent(mViewTag,EVENT_COMPLETED); } From 60948a66c42afabb9ef06ed50fa432d48753c4f5 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 1 Nov 2017 00:20:48 +0800 Subject: [PATCH 02/35] Fix unscheduleAllCallbacks not working for schedules by key --- .../js-bindings/manual/cocos2d_specifics.cpp | 118 ++++++++---------- 1 file changed, 51 insertions(+), 67 deletions(-) diff --git a/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp b/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp index e9d44119c7..9dfa50ea55 100644 --- a/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp +++ b/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp @@ -1424,43 +1424,6 @@ bool js_cocos2dx_CCNode_scheduleUpdate(JSContext *cx, uint32_t argc, JS::Value * return false; } -bool js_cocos2dx_CCScheduler_unscheduleAllSelectorsForTarget(JSContext *cx, uint32_t argc, JS::Value *vp) -{ - JS::CallArgs args = JS::CallArgsFromVp(argc, vp); - JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); - js_proxy_t *proxy = jsb_get_js_proxy(cx, obj); - cocos2d::Scheduler* cobj = (cocos2d::Scheduler *)(proxy ? proxy->ptr : nullptr); - TEST_NATIVE_OBJECT(cx, cobj) - - if (argc == 1) { - do { - JS::RootedObject tmpObj(cx, args.get(0).toObjectOrNull()); - - auto arr = JSScheduleWrapper::getTargetForJSObject(cx, tmpObj); - // If there aren't any targets, just return true. - // Otherwise, the for loop will break immediately. - // It will lead to logic errors. - // For details to reproduce it, please refer to SchedulerTest/SchedulerUpdate. - if(! arr) return true; - - JSScheduleWrapper* wrapper = nullptr; - for(ssize_t i = 0; i < arr->size(); ++i) { - wrapper = (JSScheduleWrapper*)arr->at(i); - if(wrapper) { - cobj->unscheduleAllForTarget(wrapper); - } - } - JSScheduleWrapper::removeAllTargetsForJSObject(cx, tmpObj); - - } while (0); - - args.rval().setUndefined(); - return true; - } - JS_ReportErrorUTF8(cx, "wrong number of arguments: %d, was expecting %d", argc, 1); - return false; -} - bool js_CCScheduler_scheduleUpdateForTarget(JSContext *cx, uint32_t argc, JS::Value *vp) { if (argc >= 1) { @@ -1687,6 +1650,43 @@ bool js_CCScheduler_unscheduleCallbackForTarget(JSContext *cx, uint32_t argc, JS return false; } +bool js_cocos2dx_CCScheduler_unscheduleAllSelectorsForTarget(JSContext *cx, uint32_t argc, JS::Value *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); + js_proxy_t *proxy = jsb_get_js_proxy(cx, obj); + cocos2d::Scheduler* cobj = (cocos2d::Scheduler *)(proxy ? proxy->ptr : nullptr); + TEST_NATIVE_OBJECT(cx, cobj) + + if (argc == 1) { + do { + JS::RootedObject targetObj(cx, args.get(0).toObjectOrNull()); + cobj->unscheduleAllForTarget(targetObj); + + auto arr = JSScheduleWrapper::getTargetForJSObject(cx, targetObj); + // If there aren't any targets, just return true. + // Otherwise, the for loop will break immediately. + // It will lead to logic errors. + // For details to reproduce it, please refer to SchedulerTest/SchedulerUpdate. + if(! arr) return true; + + JSScheduleWrapper* wrapper = nullptr; + for(ssize_t i = 0; i < arr->size(); ++i) { + wrapper = (JSScheduleWrapper*)arr->at(i); + if(wrapper) { + cobj->unscheduleAllForTarget(wrapper); + } + } + JSScheduleWrapper::removeAllTargetsForJSObject(cx, targetObj); + } while (0); + + args.rval().setUndefined(); + return true; + } + JS_ReportErrorUTF8(cx, "wrong number of arguments: %d, was expecting %d", argc, 1); + return false; +} + bool js_cocos2dx_CCScheduler_unscheduleAll(JSContext *cx, uint32_t argc, JS::Value *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); @@ -1737,8 +1737,10 @@ bool js_cocos2dx_CCScheduler_pauseTarget(JSContext *cx, uint32_t argc, JS::Value if (argc == 1) { do { - JS::RootedObject tmpObj(cx, args.get(0).toObjectOrNull()); - auto arr = JSScheduleWrapper::getTargetForJSObject(cx, tmpObj); + JS::RootedObject targetObj(cx, args.get(0).toObjectOrNull()); + sched->pauseTarget(targetObj); + + auto arr = JSScheduleWrapper::getTargetForJSObject(cx, targetObj); if(! arr) return true; for(ssize_t i = 0; i < arr->size(); ++i) { if(arr->at(i)) { @@ -1763,8 +1765,10 @@ bool js_cocos2dx_CCScheduler_resumeTarget(JSContext *cx, uint32_t argc, JS::Valu if (argc == 1) { do { - JS::RootedObject tmpObj(cx, args.get(0).toObjectOrNull()); - auto arr = JSScheduleWrapper::getTargetForJSObject(cx, tmpObj); + JS::RootedObject targetObj(cx, args.get(0).toObjectOrNull()); + sched->resumeTarget(targetObj); + + auto arr = JSScheduleWrapper::getTargetForJSObject(cx, targetObj); if(! arr) return true; for(ssize_t i = 0; i < arr->size(); ++i) { if(arr->at(i)) { @@ -1790,16 +1794,8 @@ bool js_cocos2dx_CCScheduler_isTargetPaused(JSContext *cx, uint32_t argc, JS::Va if (argc == 1) { bool ret = false; do { - JS::RootedObject tmpObj(cx, args.get(0).toObjectOrNull()); - auto arr = JSScheduleWrapper::getTargetForJSObject(cx, tmpObj); - if(! arr) return true; - for(ssize_t i = 0; i < arr->size(); ++i) { - if(arr->at(i)) { - ret = cobj->isTargetPaused(arr->at(i)) ? true : false; - // break directly since all targets have the same `pause` status. - break; - } - } + JS::RootedObject targetObj(cx, args.get(0).toObjectOrNull()); + ret = cobj->isTargetPaused(targetObj); } while (0); args.rval().set(JS::BooleanValue(ret)); return true; @@ -1819,24 +1815,12 @@ bool js_cocos2dx_CCScheduler_isScheduled(JSContext *cx, uint32_t argc, JS::Value if (argc == 2) { bool isScheduled = false; - JS::RootedObject funcObj(cx, args.get(0).toObjectOrNull()); + std::string key; + bool ok = jsval_to_std_string(cx, args.get(0), &key); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); JS::RootedObject tmpObj(cx, args.get(1).toObjectOrNull()); - auto arr = JSScheduleWrapper::getTargetForJSObject(cx, tmpObj); - if(! arr) { - args.rval().set(JS::BooleanValue(isScheduled)); - return true; - }; - JSScheduleWrapper* wrapper = nullptr; - JS::RootedObject wrapperFunc(cx); - for (ssize_t i = 0; i < arr->size(); ++i) { - wrapper = (JSScheduleWrapper*)arr->at(i); - wrapper->getJSCallback(cx, &wrapperFunc); - if(wrapper && funcObj.get() == wrapperFunc.get()) { - isScheduled = cobj->isScheduled(schedule_selector(JSScheduleWrapper::scheduleFunc), wrapper); - break; - } - } + isScheduled = cobj->isScheduled(key, tmpObj); args.rval().set(JS::BooleanValue(isScheduled)); return true; } From 737fbfc26464c0095e9875790f01917c103a6e31 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 10 Jan 2018 11:45:06 +0800 Subject: [PATCH 03/35] Fixed potential crash on iOS. (#1062) * Fixed potential crash on iOS. * Remove log --- .../js-bindings/manual/ScriptingCore.cpp | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp b/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp index bb6702894b..a1d40ae57f 100644 --- a/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp +++ b/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp @@ -59,15 +59,28 @@ void ScriptingCore::retainScriptObject(Ref* owner, Ref* target) return; } + se::Value targetVal; + se::Object* targetObj = nullptr; auto iterTarget = se::NativePtrToObjectMap::find(target); if (iterTarget == se::NativePtrToObjectMap::end()) { - return; + se::Class* cls = JSBClassType::findClass(target); + if (cls == nullptr) + return; + + targetObj = se::Object::createObjectWithClass(cls); + targetVal.setObject(targetObj, true); + targetObj->setPrivateData(target); + target->retain(); // Retain the native object to unify the logic in finalize method of js object. + } + else + { + targetObj = iterTarget->second; } se::ScriptEngine::getInstance()->clearException(); se::AutoHandleScope hs; - iterOwner->second->attachObject(iterTarget->second); + iterOwner->second->attachObject(targetObj); } void ScriptingCore::rootScriptObject(Ref* target) From fca426955581acb02a429419dbdaf4c4793909fd Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 2 Jan 2018 13:56:26 +0800 Subject: [PATCH 04/35] fixed #1041: Potential crash in invokeJSTouchOneByOneCallback. (#1043) And fixed potential invalid se::Object after invoking cc.director.getScheduler/getActionManager/getEventDispatcher, cc.SpriteFrame/Sprite.getTexture. Added hook functions in EventDispatcher, TextureCache to prevent using dangerous se::Object. Stop propagation for TouchOneByOne event should only affect current Touch point. Fixed updateListener may not be invoked. --- native/cocos/base/CCEventDispatcher.cpp | 55 ++++++-- native/cocos/base/CCEventDispatcher.h | 16 ++- native/cocos/renderer/CCTextureCache.cpp | 34 ++++- native/cocos/renderer/CCTextureCache.h | 14 +- .../manual/jsb_cocos2dx_manual.cpp | 130 ++++++++++++++---- .../js-bindings/script/jsb_cocos2d.js | 54 ++++++++ 6 files changed, 248 insertions(+), 55 deletions(-) diff --git a/native/cocos/base/CCEventDispatcher.cpp b/native/cocos/base/CCEventDispatcher.cpp index d458928f20..fdc9522b6a 100644 --- a/native/cocos/base/CCEventDispatcher.cpp +++ b/native/cocos/base/CCEventDispatcher.cpp @@ -191,12 +191,15 @@ void EventDispatcher::EventListenerVector::clear() EventDispatcher::EventDispatcher() : _inDispatch(0) -, _isEnabled(false) , _nodePriorityIndex(0) +, _isEnabled(false) { _toAddedListeners.reserve(50); _toRemovedListeners.reserve(50); + memset(_beforeDispatchEventHooks, 0, sizeof(_beforeDispatchEventHooks)); + memset(_afterDispatchEventHooks, 0, sizeof(_afterDispatchEventHooks)); + // fixed #4129: Mark the following listener IDs for internal use. // Therefore, internal listeners would not be cleaned when removeAllEventListeners is invoked. _internalCustomListenerIDs.insert(EVENT_COME_TO_FOREGROUND); @@ -803,6 +806,13 @@ void EventDispatcher::dispatchEvent(Event* event) if (!_isEnabled) return; + DispatchEventHook beforeDispatchHook = _beforeDispatchEventHooks[(int)event->getType()]; + DispatchEventHook afterDispatchHook = _afterDispatchEventHooks[(int)event->getType()]; + if (beforeDispatchHook != nullptr) + { + beforeDispatchHook(event); + } + updateDirtyFlagForSceneGraph(); DispatchGuard guard(_inDispatch); @@ -810,6 +820,11 @@ void EventDispatcher::dispatchEvent(Event* event) if (event->getType() == Event::Type::TOUCH) { dispatchTouchEvent(static_cast(event)); + updateListeners(event); + if (afterDispatchHook != nullptr) + { + afterDispatchHook(event); + } return; } @@ -832,6 +847,11 @@ void EventDispatcher::dispatchEvent(Event* event) updateListeners(event); } + + if (afterDispatchHook != nullptr) + { + afterDispatchHook(event); + } } void EventDispatcher::dispatchCustomEvent(const std::string &eventName, void *optionalUserData) @@ -873,6 +893,16 @@ bool EventDispatcher::hasEventListener(const EventListener::ListenerID& listener return true; } +void EventDispatcher::setBeforeDispatchEventHook(Event::Type type, const DispatchEventHook& hook) +{ + _beforeDispatchEventHooks[(int)type] = hook; +} + +void EventDispatcher::setAfterDispatchEventHook(Event::Type type, const DispatchEventHook& hook) +{ + _afterDispatchEventHooks[(int)type] = hook; +} + void EventDispatcher::dispatchTouchEvent(EventTouch* event) { sortEventListeners(EventListenerTouchOneByOne::LISTENER_ID); @@ -967,13 +997,6 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event) } } - // If the event was stopped, return directly. - if (event->isStopped()) - { - updateListeners(event); - return true; - } - CCASSERT((*touchesIter)->getID() == (*mutableTouchesIter)->getID(), "touchesIter ID should be equal to mutableTouchesIter's ID."); @@ -987,15 +1010,20 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event) return true; } + if (event->isStopped()) + { + // TouchOneByOne event is special, touchEvent->stopPropagation() should only affect current touch. + // Therefore, reset it to non-stopped state for next touch event handling and return true to stop + // current touch event propagation. + event->_isStopped = false; + return true; + } + return false; }; // dispatchEventToListeners(oneByOneListeners, onTouchEvent); - if (event->isStopped()) - { - return; - } if (!isSwallowed) ++mutableTouchesIter; @@ -1050,7 +1078,6 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event) // If the event was stopped, return directly. if (event->isStopped()) { - updateListeners(event); return true; } @@ -1063,8 +1090,6 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event) return; } } - - updateListeners(event); } void EventDispatcher::updateListeners(Event* event) diff --git a/native/cocos/base/CCEventDispatcher.h b/native/cocos/base/CCEventDispatcher.h index 0925c54abd..a40d54f9cd 100644 --- a/native/cocos/base/CCEventDispatcher.h +++ b/native/cocos/base/CCEventDispatcher.h @@ -185,6 +185,10 @@ public: */ bool hasEventListener(const EventListener::ListenerID& listenerID) const; + using DispatchEventHook = void (*)(Event*); + void setBeforeDispatchEventHook(Event::Type type, const DispatchEventHook& hook); + void setAfterDispatchEventHook(Event::Type type, const DispatchEventHook& hook); + ///////////////////////////////////////////// /** Constructor of EventDispatcher. @@ -328,15 +332,17 @@ protected: /** The nodes were associated with scene graph based priority listeners */ std::set _dirtyNodes; + std::set _internalCustomListenerIDs; + + static const int MAX_EVENT_TYPE = (int)Event::Type::CUSTOM + 1; + DispatchEventHook _beforeDispatchEventHooks[MAX_EVENT_TYPE]; + DispatchEventHook _afterDispatchEventHooks[MAX_EVENT_TYPE]; + /** Whether the dispatcher is dispatching event */ int _inDispatch; - + int _nodePriorityIndex; /** Whether to enable dispatching event */ bool _isEnabled; - - int _nodePriorityIndex; - - std::set _internalCustomListenerIDs; }; diff --git a/native/cocos/renderer/CCTextureCache.cpp b/native/cocos/renderer/CCTextureCache.cpp index bf915006d1..a9e1a745f2 100644 --- a/native/cocos/renderer/CCTextureCache.cpp +++ b/native/cocos/renderer/CCTextureCache.cpp @@ -56,8 +56,10 @@ TextureCache* TextureCache::getInstance() TextureCache::TextureCache() : _loadingThread(nullptr) -, _needQuit(false) +, _textureCreateHook(nullptr) +, _textureDestroyHook(nullptr) , _asyncRefCount(0) +, _needQuit(false) { } @@ -298,6 +300,9 @@ void TextureCache::addImageAsyncCallBack(float dt) texture->retain(); texture->autorelease(); + + if (_textureCreateHook != nullptr) + _textureCreateHook(this, texture); } else { texture = nullptr; CCLOG("cocos2d: failed to call TextureCache::addImageAsync(%s)", asyncStruct->filename.c_str()); @@ -360,6 +365,9 @@ Texture2D * TextureCache::addImage(const std::string &path) // texture already retained, no need to re-retain it _textures.insert( std::make_pair(fullpath, texture) ); + if (_textureCreateHook != nullptr) + _textureCreateHook(this, texture); + //parse 9-patch info this->parseNinePatchImage(image, texture, path); } @@ -410,6 +418,9 @@ Texture2D* TextureCache::addImage(Image *image, const std::string &key) texture->retain(); texture->autorelease(); + + if (_textureCreateHook != nullptr) + _textureCreateHook(this, texture); } else { @@ -483,6 +494,9 @@ cocos2d::Vector TextureCache::getAllTextures() const void TextureCache::removeAllTextures() { for( auto it=_textures.begin(); it!=_textures.end(); ++it ) { + if (_textureDestroyHook != nullptr) + _textureDestroyHook(this, it->second); + (it->second)->release(); } _textures.clear(); @@ -494,6 +508,8 @@ void TextureCache::removeUnusedTextures() Texture2D *tex = it->second; if( tex->getReferenceCount() == 1 ) { CCLOG("cocos2d: TextureCache: removing unused texture: %s", it->first.c_str()); + if (_textureDestroyHook != nullptr) + _textureDestroyHook(this, tex); tex->release(); it = _textures.erase(it); @@ -514,6 +530,9 @@ void TextureCache::removeTexture(Texture2D* texture) for( auto it=_textures.cbegin(); it!=_textures.cend(); /* nothing */ ) { if( it->second == texture ) { + if (_textureDestroyHook != nullptr) + _textureDestroyHook(this, texture); + it->second->release(); it = _textures.erase(it); break; @@ -534,6 +553,9 @@ void TextureCache::removeTextureForKey(const std::string &textureKeyName) } if( it != _textures.end() ) { + if (_textureDestroyHook != nullptr) + _textureDestroyHook(this, it->second); + (it->second)->release(); _textures.erase(it); } @@ -657,6 +679,16 @@ void TextureCache::renameTextureWithKey(const std::string& srcName, const std::s } } +void TextureCache::setTextureCreateHook(TextureLifeCycleHook hook) +{ + _textureCreateHook = hook; +} + +void TextureCache::setTextureDestroyHook(TextureLifeCycleHook hook) +{ + _textureDestroyHook = hook; +} + #if CC_ENABLE_CACHE_TEXTURE_DATA std::list VolatileTextureMgr::_textures; diff --git a/native/cocos/renderer/CCTextureCache.h b/native/cocos/renderer/CCTextureCache.h index 52fdebd64b..73885d3050 100644 --- a/native/cocos/renderer/CCTextureCache.h +++ b/native/cocos/renderer/CCTextureCache.h @@ -212,6 +212,9 @@ public: */ void renameTextureWithKey(const std::string& srcName, const std::string& dstName); + using TextureLifeCycleHook = void (*)(TextureCache*, Texture2D*); + void setTextureCreateHook(TextureLifeCycleHook hook); + void setTextureDestroyHook(TextureLifeCycleHook hook); private: void addImageAsyncCallBack(float dt); @@ -221,8 +224,6 @@ public: protected: struct AsyncStruct; - std::thread* _loadingThread; - std::deque _asyncStructQueue; std::deque _requestQueue; std::deque _responseQueue; @@ -231,12 +232,15 @@ protected: std::mutex _responseMutex; std::condition_variable _sleepCondition; + std::unordered_map _textures; - bool _needQuit; + std::thread* _loadingThread; + + TextureLifeCycleHook _textureCreateHook; + TextureLifeCycleHook _textureDestroyHook; int _asyncRefCount; - - std::unordered_map _textures; + bool _needQuit; }; #if CC_ENABLE_CACHE_TEXTURE_DATA diff --git a/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp b/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp index ce8095b74b..5c0cfaffd8 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp @@ -11,6 +11,7 @@ #include "cocos/scripting/js-bindings/jswrapper/SeApi.h" #include "cocos/scripting/js-bindings/manual/jsb_conversions.hpp" #include "cocos/scripting/js-bindings/manual/jsb_global.h" +#include "cocos/scripting/js-bindings/manual/ScriptingCore.h" #include "cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp" #include "cocos/scripting/js-bindings/auto/jsb_cocos2dx_ui_auto.hpp" @@ -341,7 +342,7 @@ static bool invokeJSMouseCallback(EventListenerMouse* listener, const char* func SE_PRECONDITION2(ok, false, "invokeJSMouseCallback convert arg1 failed!"); if (!fromCache) - { + { // EventMouse is holded by CCGLView-desktop forever. So just root it once to make it never be garbage collected. arg1Val.toObject()->root(); } argArr.push_back(std::move(arg1Val)); @@ -433,28 +434,20 @@ static bool invokeJSTouchOneByOneCallback(EventListenerTouchOneByOne* listener, se::ValueArray argArr; argArr.reserve(2); se::Value arg1Val; - se::Object* arg1Obj = nullptr; do { ok = native_ptr_to_seval(touch, &arg1Val); SE_PRECONDITION_ERROR_BREAK(ok, "invokeJSTouchOneByOneCallback convert arg1 failed!"); - - arg1Obj = arg1Val.toObject(); - - if (type == TOUCH_ONE_BY_ONE_ON_TOUCH_BEGAN) - { - arg1Obj->root(); - } - argArr.push_back(std::move(arg1Val)); + bool fromCache = true; se::Value arg2Val; - bool eventFromCache = true; - ok = native_ptr_to_seval(event, &arg2Val, &eventFromCache); + ok = native_ptr_to_seval(event, &arg2Val, &fromCache); SE_PRECONDITION_ERROR_BREAK(ok, "invokeJSTouchOneByOneCallback convert arg2 failed!"); - if (!eventFromCache) + if (!fromCache) { + // EventTouch is holded by CCGLView forever. So just root it once to make it never be garbage collected. arg2Val.toObject()->root(); } @@ -468,18 +461,6 @@ static bool invokeJSTouchOneByOneCallback(EventListenerTouchOneByOne* listener, } while(false); - if (type == TOUCH_ONE_BY_ONE_ON_TOUCH_BEGAN) - { - if (!(retVal->isBoolean() && retVal->toBoolean())) - { - arg1Obj->unroot(); - } - } - else if (type == TOUCH_ONE_BY_ONE_ON_TOUCH_ENDED || type == TOUCH_ONE_BY_ONE_ON_TOUCH_CANCELLED) - { - arg1Obj->unroot(); - } - return ok; } @@ -553,14 +534,16 @@ static bool invokeJSTouchAllAtOnceCallback(EventListenerTouchAllAtOnce* listener SE_PRECONDITION2(ok, false, "invokeJSTouchAllAtOnceCallback convert arg1 failed!"); argArr.push_back(std::move(arg1Val)); + bool fromCache = true; se::Value arg2Val; - bool eventFromCache = true; - ok = native_ptr_to_seval(event, &arg2Val, &eventFromCache); + ok = native_ptr_to_seval(event, &arg2Val, &fromCache); SE_PRECONDITION2(ok, false, "invokeJSTouchAllAtOnceCallback convert arg2 failed!"); - if (!eventFromCache) + if (!fromCache) { + // EventTouch is holded by CCGLView forever. So just root it once to make it never be garbage collected. arg2Val.toObject()->root(); } + argArr.push_back(std::move(arg2Val)); ok = funcVal.toObject()->call(argArr, listenerObj, retVal); @@ -787,7 +770,7 @@ static bool js_EventListenerCustom_create(se::State& s) se::Value funcVal = args[1]; assert(funcVal.isObject() && funcVal.toObject()->isFunction()); - auto ret = new EventListenerCustom(); + auto ret = new (std::nothrow) EventListenerCustom(); ret->init(eventName, [ret, funcVal](EventCustom* event){ @@ -836,6 +819,89 @@ static bool js_EventListenerCustom_create(se::State& s) } SE_BIND_FUNC(js_EventListenerCustom_create) +static void onBeforeDispatchTouchEvent(Event* event) +{ + if (event->getType() == Event::Type::TOUCH) + { + EventTouch* touchEvent = static_cast(event); + if (touchEvent->getEventCode() == EventTouch::EventCode::BEGAN) + { + bool fromCache = true; + const auto& touches = touchEvent->getTouches(); + for (auto&& touch : touches) + { + se::Value touchVal; + native_ptr_to_seval(touch, __jsb_cocos2d_Touch_class, &touchVal, &fromCache); + assert(!fromCache); + touchVal.toObject()->root(); + } + } + } +} + +static void onAfterDispatchTouchEvent(Event* event) +{ + if (event->getType() == Event::Type::TOUCH) + { + EventTouch* touchEvent = static_cast(event); + EventTouch::EventCode code = touchEvent->getEventCode(); + if (code == EventTouch::EventCode::ENDED || code == EventTouch::EventCode::CANCELLED) + { + const auto& touches = touchEvent->getTouches(); + for (auto&& touch : touches) + { + auto iter = se::NativePtrToObjectMap::find(touch); + assert(iter != se::NativePtrToObjectMap::end()); + iter->second->unroot(); + } + } + } +} + +static void onTextureCreate(TextureCache* cache, Texture2D* texture) +{ + auto iterOwner = se::NativePtrToObjectMap::find(cache); + if (iterOwner == se::NativePtrToObjectMap::end()) + { + assert(false); + return; + } + + se::Value textureVal; + bool fromCache = false; + native_ptr_to_seval(texture, __jsb_cocos2d_Texture2D_class, &textureVal, &fromCache); + if (!fromCache && textureVal.isObject()) + { + iterOwner->second->attachObject(textureVal.toObject()); + } + else + { + assert(false); + } +} + +static void onTextureDestroy(TextureCache* cache, Texture2D* texture) +{ + auto iterOwner = se::NativePtrToObjectMap::find(cache); + if (iterOwner == se::NativePtrToObjectMap::end()) + { + assert(false); + return; + } + + se::Value textureVal; + bool fromCache = false; + native_ptr_to_seval(texture, __jsb_cocos2d_Texture2D_class, &textureVal, &fromCache); + if (fromCache && textureVal.isObject()) + { + iterOwner->second->detachObject(textureVal.toObject()); + } + else + { + assert(false); + } +} + static bool register_eventlistener(se::Object* obj) { se::Value v; @@ -867,6 +933,12 @@ static bool register_eventlistener(se::Object* obj) assert(v.isObject()); v.toObject()->defineFunction("create", _SE(js_EventListenerCustom_create)); + Director::getInstance()->getEventDispatcher()->setBeforeDispatchEventHook(Event::Type::TOUCH, onBeforeDispatchTouchEvent); + Director::getInstance()->getEventDispatcher()->setAfterDispatchEventHook(Event::Type::TOUCH, onAfterDispatchTouchEvent); + + Director::getInstance()->getTextureCache()->setTextureCreateHook(onTextureCreate); + Director::getInstance()->getTextureCache()->setTextureDestroyHook(onTextureDestroy); + se::ScriptEngine::getInstance()->clearException(); return true; diff --git a/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js b/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js index 572ae53c66..833973a05f 100644 --- a/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js +++ b/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js @@ -1089,3 +1089,57 @@ cc.GLProgram.prototype.setUniformLocationWithMatrix4fv = function(){ tempArray.push(4); this.setUniformLocationWithMatrixfvUnion.apply(this, tempArray); }; + +// Hack for the lifecycle of JS objects +cc.Director.prototype._jsb_getScheduler = cc.Director.prototype.getScheduler; +cc.Director.prototype.getScheduler = function() { + var scheduler = this._jsb_getScheduler(); + if (this._jsb_scheduler != scheduler) + { + this._jsb_scheduler = scheduler; + } + return scheduler; +} + +cc.Director.prototype._jsb_getActionManager = cc.Director.prototype.getActionManager; +cc.Director.prototype.getActionManager = function() { + var actionManager = this._jsb_getActionManager(); + if (this._jsb_actionManager != actionManager) + { + this._jsb_actionManager = actionManager; + } + return actionManager; +} + +cc.Director.prototype._jsb_getEventDispatcher = cc.Director.prototype.getEventDispatcher; +cc.Director.prototype.getEventDispatcher = function() { + var eventDispatcher = this._jsb_getEventDispatcher(); + if (this._jsb_eventDispatcher != eventDispatcher) + { + this._jsb_eventDispatcher = eventDispatcher; + } + return eventDispatcher; +} + +cc.SpriteFrame.prototype._jsb_getTexture = cc.SpriteFrame.prototype.getTexture; +cc.SpriteFrame.prototype.getTexture = function() { + var texture = this._jsb_getTexture(); + if (this._jsb_texture != texture) + { + this._jsb_texture = texture; + } + return texture; +} + +cc.Sprite.prototype._jsb_getTexture = cc.Sprite.prototype.getTexture; +cc.Sprite.prototype.getTexture = function() { + var texture = this._jsb_getTexture(); + if (this._jsb_texture != texture) + { + this._jsb_texture = texture; + } + return texture; +} + +// + From 04598ed3266015117ed119c2e7ca1d92afde17ec Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 8 Jan 2018 15:31:20 +0800 Subject: [PATCH 05/35] Adds missing se::autoHandleScope. (#1057) --- .../scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp b/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp index 5c0cfaffd8..167c91c4f3 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp @@ -821,6 +821,7 @@ SE_BIND_FUNC(js_EventListenerCustom_create) static void onBeforeDispatchTouchEvent(Event* event) { + se::AutoHandleScope hs; if (event->getType() == Event::Type::TOUCH) { EventTouch* touchEvent = static_cast(event); @@ -841,6 +842,7 @@ static void onBeforeDispatchTouchEvent(Event* event) static void onAfterDispatchTouchEvent(Event* event) { + se::AutoHandleScope hs; if (event->getType() == Event::Type::TOUCH) { EventTouch* touchEvent = static_cast(event); @@ -860,6 +862,7 @@ static void onAfterDispatchTouchEvent(Event* event) static void onTextureCreate(TextureCache* cache, Texture2D* texture) { + se::AutoHandleScope hs; auto iterOwner = se::NativePtrToObjectMap::find(cache); if (iterOwner == se::NativePtrToObjectMap::end()) { @@ -882,6 +885,7 @@ static void onTextureCreate(TextureCache* cache, Texture2D* texture) static void onTextureDestroy(TextureCache* cache, Texture2D* texture) { + se::AutoHandleScope hs; auto iterOwner = se::NativePtrToObjectMap::find(cache); if (iterOwner == se::NativePtrToObjectMap::end()) { From ecef1d178a53373bab471684c9e6d79bc424e402 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 10 Jan 2018 16:17:02 +0800 Subject: [PATCH 06/35] [iOS] Updates cocosanalytics lib to 1.0.5 (#1065) --- native/external/config.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/native/external/config.json b/native/external/config.json index 374c2c2a60..8179ce9089 100644 --- a/native/external/config.json +++ b/native/external/config.json @@ -1,5 +1,5 @@ { - "version": "v3-deps-53", + "version": "v3-deps-54", "zip_file_size": "114318593", "repo_name": "cocos2d-x-lite-external", "repo_parent": "https://github.com/cocos-creator/" From 6693c26403a53714f306fb89b40b630fa43ca461 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 10 Jan 2018 18:42:13 +0800 Subject: [PATCH 07/35] [iOS] Fixes createTypedArray return null on <= iOS 9 (#1066) --- native/cocos/scripting/js-bindings/jswrapper/jsc/Object.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/native/cocos/scripting/js-bindings/jswrapper/jsc/Object.cpp b/native/cocos/scripting/js-bindings/jswrapper/jsc/Object.cpp index 8a9cddcb55..96819b24a9 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/jsc/Object.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/jsc/Object.cpp @@ -292,7 +292,9 @@ namespace se { Value func; bool ok = ScriptEngine::getInstance()->getGlobalObject()->getProperty(typedArrayCtor, &func); - if (ok && func.isObject() && func.toObject()->isFunction()) + // On <= iOS 9, typed array constructor is an object rather than a function. + // Therefore, don't check whether typed array constructor is a function here. + if (ok && func.isObject()/* && func.toObject()->isFunction() */) { JSValueRef exception = nullptr; JSObjectRef ret = JSObjectCallAsConstructor(__cx, func.toObject()->_obj, 1, &arr->_obj, &exception); From df164be9a46afcbc018dc3c839f0301706a69c57 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 11 Jan 2018 15:44:13 +0800 Subject: [PATCH 08/35] Fixes crash of missing se::AutoHandleScrope before se::createObjectWithClass in ScriptingCore::retainScriptObject. (#1067) --- native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp b/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp index a1d40ae57f..c25968699e 100644 --- a/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp +++ b/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp @@ -59,6 +59,9 @@ void ScriptingCore::retainScriptObject(Ref* owner, Ref* target) return; } + se::ScriptEngine::getInstance()->clearException(); + se::AutoHandleScope hs; + se::Value targetVal; se::Object* targetObj = nullptr; auto iterTarget = se::NativePtrToObjectMap::find(target); @@ -78,8 +81,6 @@ void ScriptingCore::retainScriptObject(Ref* owner, Ref* target) targetObj = iterTarget->second; } - se::ScriptEngine::getInstance()->clearException(); - se::AutoHandleScope hs; iterOwner->second->attachObject(targetObj); } From 1b0965803cfa0dccb0fa5d8e1c03d6b73bf4ccee Mon Sep 17 00:00:00 2001 From: Knox Date: Tue, 16 Jan 2018 18:30:13 +0800 Subject: [PATCH 09/35] fix CocosAnalytics issue for fireball/issues/6730 (#1058) --- .../android/java/libs/libcocosanalytics.jar | Bin 31561 -> 31590 bytes .../cocos2dx/lib/Cocos2dxGLSurfaceView.java | 8 ++++++-- .../js-bindings/script/jsb_cocosanalytics.js | 12 ++++++++++++ .../proj.ios_mac/ios/AppController.mm | 8 ++++++-- .../proj.ios_mac/ios/AppController.mm | 8 ++++++-- .../proj.ios_mac/ios/AppController.mm | 8 ++++++-- 6 files changed, 36 insertions(+), 8 deletions(-) diff --git a/native/cocos/platform/android/java/libs/libcocosanalytics.jar b/native/cocos/platform/android/java/libs/libcocosanalytics.jar index 29e665f8f595d6cb73024d2c7021dadc942dce42..5ed690948f45899d0003bb11b255a07c69f3d0a1 100644 GIT binary patch delta 6404 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 XkIzfk@}DgJC{Qqn;HCGUr}F;*!xGB_ diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java index 4385eaf085..c33b89288c 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java @@ -179,7 +179,9 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView { @Override public void run() { Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleOnResume(); - CAAgent.onResume(Cocos2dxGLSurfaceView.this.getContext()); + if (CAAgent.isInited()) { + CAAgent.onResume(Cocos2dxGLSurfaceView.this.getContext()); + } } }); } @@ -190,7 +192,9 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView { @Override public void run() { Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleOnPause(); - CAAgent.onPause(Cocos2dxGLSurfaceView.this.getContext()); + if (CAAgent.isInited()) { + CAAgent.onPause(Cocos2dxGLSurfaceView.this.getContext()); + } } }); this.setRenderMode(RENDERMODE_WHEN_DIRTY); diff --git a/native/cocos/scripting/js-bindings/script/jsb_cocosanalytics.js b/native/cocos/scripting/js-bindings/script/jsb_cocosanalytics.js index 7e15691d6b..9673d66db9 100644 --- a/native/cocos/scripting/js-bindings/script/jsb_cocosanalytics.js +++ b/native/cocos/scripting/js-bindings/script/jsb_cocosanalytics.js @@ -36,6 +36,10 @@ if (platform === sys.ANDROID) { } }; + cocosAnalytics.isInited = function() { + return jsb.reflection.callStaticMethod(cls_CAAgent, "isInited", "()Z"); + }; + cocosAnalytics.enableDebug = function(enabled) { jsb.reflection.callStaticMethod(cls_CAAgent, "enableDebug", "(Z)V", @@ -326,6 +330,10 @@ if (platform === sys.ANDROID) { } }; + cocosAnalytics.isInited = function() { + return jsb.reflection.callStaticMethod(cls_CAAgent, "isInited"); + }; + cocosAnalytics.enableDebug = function(enabled) { jsb.reflection.callStaticMethod(cls_CAAgent, "enableDebug:", @@ -594,6 +602,10 @@ if (platform === sys.ANDROID) { console.log("Cocos Analytics module isn't available on this platform!"); }; + cocosAnalytics.isInited = function() { + return false; + }; + cocosAnalytics.enableDebug = function(enabled) { }; diff --git a/native/templates/js-template-binary/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm b/native/templates/js-template-binary/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm index 4d63a42d0e..de05bea003 100755 --- a/native/templates/js-template-binary/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm +++ b/native/templates/js-template-binary/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm @@ -117,7 +117,9 @@ static AppDelegate* s_sharedApplication = nullptr; If your application supports background execution, called instead of applicationWillTerminate: when the user quits. */ cocos2d::Application::getInstance()->applicationDidEnterBackground(); - [CAAgent onPause]; + if (CAAgent.isInited) { + [CAAgent onPause]; + } } - (void)applicationWillEnterForeground:(UIApplication *)application { @@ -129,7 +131,9 @@ static AppDelegate* s_sharedApplication = nullptr; if (glview == currentView) { cocos2d::Application::getInstance()->applicationWillEnterForeground(); } - [CAAgent onResume]; + if (CAAgent.isInited) { + [CAAgent onResume]; + } } - (void)applicationWillTerminate:(UIApplication *)application { diff --git a/native/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm b/native/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm index 4d63a42d0e..de05bea003 100755 --- a/native/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm +++ b/native/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm @@ -117,7 +117,9 @@ static AppDelegate* s_sharedApplication = nullptr; If your application supports background execution, called instead of applicationWillTerminate: when the user quits. */ cocos2d::Application::getInstance()->applicationDidEnterBackground(); - [CAAgent onPause]; + if (CAAgent.isInited) { + [CAAgent onPause]; + } } - (void)applicationWillEnterForeground:(UIApplication *)application { @@ -129,7 +131,9 @@ static AppDelegate* s_sharedApplication = nullptr; if (glview == currentView) { cocos2d::Application::getInstance()->applicationWillEnterForeground(); } - [CAAgent onResume]; + if (CAAgent.isInited) { + [CAAgent onResume]; + } } - (void)applicationWillTerminate:(UIApplication *)application { diff --git a/native/templates/js-template-link/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm b/native/templates/js-template-link/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm index 4d63a42d0e..de05bea003 100755 --- a/native/templates/js-template-link/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm +++ b/native/templates/js-template-link/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm @@ -117,7 +117,9 @@ static AppDelegate* s_sharedApplication = nullptr; If your application supports background execution, called instead of applicationWillTerminate: when the user quits. */ cocos2d::Application::getInstance()->applicationDidEnterBackground(); - [CAAgent onPause]; + if (CAAgent.isInited) { + [CAAgent onPause]; + } } - (void)applicationWillEnterForeground:(UIApplication *)application { @@ -129,7 +131,9 @@ static AppDelegate* s_sharedApplication = nullptr; if (glview == currentView) { cocos2d::Application::getInstance()->applicationWillEnterForeground(); } - [CAAgent onResume]; + if (CAAgent.isInited) { + [CAAgent onResume]; + } } - (void)applicationWillTerminate:(UIApplication *)application { From b55c44e0865bc9f6679194c4bd635bb04c7571ad Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 18 Jan 2018 13:41:44 +0800 Subject: [PATCH 10/35] Memory leak fix for dragonbones & spine. (#1073) * Memory leak fixes for Dragonbones module when restarting game. * Fixes memory leak for Spine Runtime. * Compilation fix in BaseObject. * Remove unused log. * Copy dragonbones vector before enumating the vector. * update comments. * LOG fix. --- .../cocos2dx/CCArmatureDisplay.cpp | 7 +- .../dragonbones/cocos2dx/CCFactory.cpp | 18 +++++- .../dragonbones/cocos2dx/CCFactory.h | 8 +-- .../dragonbones/core/BaseObject.cpp | 29 +++++++-- .../dragonbones/core/BaseObject.h | 10 ++- .../editor-support/spine/SkeletonRenderer.cpp | 17 +++-- .../api/jsb_cocos2dx_dragonbones_auto_api.js | 15 ++++- .../auto/jsb_cocos2dx_dragonbones_auto.cpp | 44 ++++++++----- .../auto/jsb_cocos2dx_dragonbones_auto.hpp | 3 +- .../manual/jsb_dragonbones_manual.cpp | 64 ++++++++++++++++++- native/tools/tojs/cocos2dx_dragonbones.ini | 2 +- 11 files changed, 172 insertions(+), 45 deletions(-) diff --git a/native/cocos/editor-support/dragonbones/cocos2dx/CCArmatureDisplay.cpp b/native/cocos/editor-support/dragonbones/cocos2dx/CCArmatureDisplay.cpp index adfa819531..66aa461853 100644 --- a/native/cocos/editor-support/dragonbones/cocos2dx/CCArmatureDisplay.cpp +++ b/native/cocos/editor-support/dragonbones/cocos2dx/CCArmatureDisplay.cpp @@ -28,7 +28,12 @@ CCArmatureDisplay::CCArmatureDisplay() : this->setEventDispatcher(_dispatcher); _dispatcher->setEnabled(true); } -CCArmatureDisplay::~CCArmatureDisplay() {} + +CCArmatureDisplay::~CCArmatureDisplay() +{ + dispose(); + CC_SAFE_RELEASE(_dispatcher); +} // cleared by armature void CCArmatureDisplay::_onClear() diff --git a/native/cocos/editor-support/dragonbones/cocos2dx/CCFactory.cpp b/native/cocos/editor-support/dragonbones/cocos2dx/CCFactory.cpp index be0980faba..29c65d4660 100644 --- a/native/cocos/editor-support/dragonbones/cocos2dx/CCFactory.cpp +++ b/native/cocos/editor-support/dragonbones/cocos2dx/CCFactory.cpp @@ -5,7 +5,23 @@ DRAGONBONES_NAMESPACE_BEGIN -CCFactory CCFactory::factory; +namespace { + CCFactory* __instance = nullptr; +} + +CCFactory* CCFactory::getInstance() +{ + if (__instance == nullptr) + __instance = new (std::nothrow) CCFactory(); + + return __instance; +} + +void CCFactory::destroyInstance() +{ + delete __instance; + __instance = nullptr; +} CCFactory::CCFactory() { diff --git a/native/cocos/editor-support/dragonbones/cocos2dx/CCFactory.h b/native/cocos/editor-support/dragonbones/cocos2dx/CCFactory.h index 89c1090196..4f1eef77bd 100644 --- a/native/cocos/editor-support/dragonbones/cocos2dx/CCFactory.h +++ b/native/cocos/editor-support/dragonbones/cocos2dx/CCFactory.h @@ -10,13 +10,11 @@ DRAGONBONES_NAMESPACE_BEGIN class CCFactory : public BaseFactory { public: - static CCFactory factory; - -public: + static CCFactory* getInstance(); + static void destroyInstance(); +private: CCFactory(); ~CCFactory(); - -private: DRAGONBONES_DISALLOW_COPY_AND_ASSIGN(CCFactory); protected: diff --git a/native/cocos/editor-support/dragonbones/core/BaseObject.cpp b/native/cocos/editor-support/dragonbones/core/BaseObject.cpp index 7c0dd6be47..0ead7068af 100644 --- a/native/cocos/editor-support/dragonbones/core/BaseObject.cpp +++ b/native/cocos/editor-support/dragonbones/core/BaseObject.cpp @@ -1,6 +1,9 @@ #include "BaseObject.h" + DRAGONBONES_NAMESPACE_BEGIN +std::vector BaseObject::__allDragonBonesObjects; + std::size_t BaseObject::_hashCode = 0; std::size_t BaseObject::_defaultMaxCount = 5000; std::unordered_map BaseObject::_maxCountMap; @@ -116,6 +119,7 @@ void BaseObject::clearPool(std::size_t classTypeIndex) { for (auto object : pool) { +// printf("delete object: %s, %p\n", typeid(*object).name(), object); delete object; } @@ -125,19 +129,34 @@ void BaseObject::clearPool(std::size_t classTypeIndex) } } -BaseObject::BaseObject() : - hashCode(BaseObject::_hashCode++) -{} + + +BaseObject::BaseObject() +: hashCode(BaseObject::_hashCode++) +, _isInPool(false) +{ + __allDragonBonesObjects.push_back(this); +} + BaseObject::~BaseObject() { - int i = 0; - ++i; + auto iter = std::find(__allDragonBonesObjects.begin(), __allDragonBonesObjects.end(), this); + if (iter != __allDragonBonesObjects.end()) + { + __allDragonBonesObjects.erase(iter); + } } void BaseObject::returnToPool() { _onClear(); _returnObject(this); + _isInPool = true; +} + +std::vector& BaseObject::getAllObjects() +{ + return __allDragonBonesObjects; } DRAGONBONES_NAMESPACE_END diff --git a/native/cocos/editor-support/dragonbones/core/BaseObject.h b/native/cocos/editor-support/dragonbones/core/BaseObject.h index b80b237c78..900a165aa7 100644 --- a/native/cocos/editor-support/dragonbones/core/BaseObject.h +++ b/native/cocos/editor-support/dragonbones/core/BaseObject.h @@ -1,4 +1,4 @@ -#ifndef DRAGONBONES_BASE_OBJECT_H +#ifndef DRAGONBONES_BASE_OBJECT_H #define DRAGONBONES_BASE_OBJECT_H #include "DragonBones.h" @@ -47,7 +47,7 @@ public: { const auto object = dynamic_cast(pool.back()); pool.pop_back(); - + object->_isInPool = false; return object; } } @@ -55,6 +55,8 @@ public: return new (std::nothrow) T(); } + static std::vector& getAllObjects(); + public: const std::size_t hashCode; @@ -72,6 +74,10 @@ public: virtual std::size_t getClassTypeIndex() const = 0; void returnToPool(); + inline bool isInPool() const { return _isInPool; } +private: + static std::vector __allDragonBonesObjects; + bool _isInPool; }; DRAGONBONES_NAMESPACE_END diff --git a/native/cocos/editor-support/spine/SkeletonRenderer.cpp b/native/cocos/editor-support/spine/SkeletonRenderer.cpp index ea92a595ec..e66de41713 100644 --- a/native/cocos/editor-support/spine/SkeletonRenderer.cpp +++ b/native/cocos/editor-support/spine/SkeletonRenderer.cpp @@ -59,8 +59,11 @@ SkeletonRenderer* SkeletonRenderer::createWithFile (const std::string& skeletonD return node; } -void SkeletonRenderer::initialize () { - _worldVertices = new float[1000]; // Max number of vertices per mesh. +void SkeletonRenderer::initialize () { + + // SkeletonRenderer::initalize may be invoked twice, need to check whether _worldVertics is already allocated to avoid memory leak. + if (_worldVertices == nullptr) + _worldVertices = new float[1000]; // Max number of vertices per mesh. _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED; setOpacityModifyRGB(true); @@ -74,25 +77,25 @@ void SkeletonRenderer::setSkeletonData (spSkeletonData *skeletonData, bool ownsS } SkeletonRenderer::SkeletonRenderer () - : _atlas(nullptr), _attachmentLoader(nullptr), _debugSlots(false), _debugBones(false), _timeScale(1) { + : _atlas(nullptr), _attachmentLoader(nullptr), _debugSlots(false), _debugBones(false), _worldVertices(nullptr), _timeScale(1) { } SkeletonRenderer::SkeletonRenderer (spSkeletonData *skeletonData, bool ownsSkeletonData) - : _atlas(nullptr), _attachmentLoader(nullptr), _debugSlots(false), _debugBones(false), _timeScale(1) { + : _atlas(nullptr), _attachmentLoader(nullptr), _debugSlots(false), _debugBones(false), _worldVertices(nullptr), _timeScale(1) { initWithData(skeletonData, ownsSkeletonData); } SkeletonRenderer::SkeletonRenderer (const std::string& skeletonDataFile, spAtlas* atlas, float scale) - : _atlas(nullptr), _attachmentLoader(nullptr), _debugSlots(false), _debugBones(false), _timeScale(1) { + : _atlas(nullptr), _attachmentLoader(nullptr), _debugSlots(false), _debugBones(false), _worldVertices(nullptr), _timeScale(1) { initWithJsonFile(skeletonDataFile, atlas, scale); } SkeletonRenderer::SkeletonRenderer (const std::string& skeletonDataFile, const std::string& atlasFile, float scale) - : _atlas(nullptr), _attachmentLoader(nullptr), _debugSlots(false), _debugBones(false), _timeScale(1) { + : _atlas(nullptr), _attachmentLoader(nullptr), _debugSlots(false), _debugBones(false), _worldVertices(nullptr), _timeScale(1) { initWithJsonFile(skeletonDataFile, atlasFile, scale); } -SkeletonRenderer::~SkeletonRenderer () { +SkeletonRenderer::~SkeletonRenderer () { if (_ownsSkeletonData) spSkeletonData_dispose(_skeleton->data); spSkeleton_dispose(_skeleton); if (_atlas) spAtlas_dispose(_atlas); diff --git a/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_dragonbones_auto_api.js b/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_dragonbones_auto_api.js index 78c7a49655..fe7f9b3bcf 100644 --- a/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_dragonbones_auto_api.js +++ b/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_dragonbones_auto_api.js @@ -1566,12 +1566,21 @@ float }, /** - * @method CCFactory - * @constructor + * @method destroyInstance */ -CCFactory : function ( +destroyInstance : function ( ) { }, +/** + * @method getInstance + * @return {dragonBones::CCFactory} + */ +getInstance : function ( +) +{ + return dragonBones::CCFactory; +}, + }; diff --git a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_dragonbones_auto.cpp b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_dragonbones_auto.cpp index f8a9685bd3..c4fbc43ca9 100644 --- a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_dragonbones_auto.cpp +++ b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_dragonbones_auto.cpp @@ -4855,17 +4855,34 @@ static bool js_cocos2dx_dragonbones_CCFactory_parseTextureAtlasData(se::State& s } SE_BIND_FUNC(js_cocos2dx_dragonbones_CCFactory_parseTextureAtlasData) -SE_DECLARE_FINALIZE_FUNC(js_dragonBones_CCFactory_finalize) - -static bool js_cocos2dx_dragonbones_CCFactory_constructor(se::State& s) +static bool js_cocos2dx_dragonbones_CCFactory_destroyInstance(se::State& s) { - dragonBones::CCFactory* cobj = new (std::nothrow) dragonBones::CCFactory(); - s.thisObject()->setPrivateData(cobj); - se::NonRefNativePtrCreatedByCtorMap::emplace(cobj); - return true; + const auto& args = s.args(); + size_t argc = args.size(); + if (argc == 0) { + dragonBones::CCFactory::destroyInstance(); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; } -SE_BIND_CTOR(js_cocos2dx_dragonbones_CCFactory_constructor, __jsb_dragonBones_CCFactory_class, js_dragonBones_CCFactory_finalize) +SE_BIND_FUNC(js_cocos2dx_dragonbones_CCFactory_destroyInstance) +static bool js_cocos2dx_dragonbones_CCFactory_getInstance(se::State& s) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + dragonBones::CCFactory* result = dragonBones::CCFactory::getInstance(); + ok &= native_ptr_to_rooted_seval((dragonBones::CCFactory*)result, &s.rval()); + SE_PRECONDITION2(ok, false, "js_cocos2dx_dragonbones_CCFactory_getInstance : Error processing arguments"); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_cocos2dx_dragonbones_CCFactory_getInstance) extern se::Object* __jsb_dragonBones_BaseFactory_proto; @@ -4873,25 +4890,20 @@ extern se::Object* __jsb_dragonBones_BaseFactory_proto; static bool js_dragonBones_CCFactory_finalize(se::State& s) { CCLOGINFO("jsbindings: finalizing JS object %p (dragonBones::CCFactory)", s.nativeThisObject()); - auto iter = se::NonRefNativePtrCreatedByCtorMap::find(s.nativeThisObject()); - if (iter != se::NonRefNativePtrCreatedByCtorMap::end()) - { - se::NonRefNativePtrCreatedByCtorMap::erase(iter); - dragonBones::CCFactory* cobj = (dragonBones::CCFactory*)s.nativeThisObject(); - delete cobj; - } return true; } SE_BIND_FINALIZE_FUNC(js_dragonBones_CCFactory_finalize) bool js_register_cocos2dx_dragonbones_CCFactory(se::Object* obj) { - auto cls = se::Class::create("CCFactory", obj, __jsb_dragonBones_BaseFactory_proto, _SE(js_cocos2dx_dragonbones_CCFactory_constructor)); + auto cls = se::Class::create("CCFactory", obj, __jsb_dragonBones_BaseFactory_proto, nullptr); cls->defineFunction("getTextureDisplay", _SE(js_cocos2dx_dragonbones_CCFactory_getTextureDisplay)); cls->defineFunction("getSoundEventManater", _SE(js_cocos2dx_dragonbones_CCFactory_getSoundEventManater)); cls->defineFunction("buildArmatureDisplay", _SE(js_cocos2dx_dragonbones_CCFactory_buildArmatureDisplay)); cls->defineFunction("parseTextureAtlasData", _SE(js_cocos2dx_dragonbones_CCFactory_parseTextureAtlasData)); + cls->defineStaticFunction("destroyInstance", _SE(js_cocos2dx_dragonbones_CCFactory_destroyInstance)); + cls->defineStaticFunction("getInstance", _SE(js_cocos2dx_dragonbones_CCFactory_getInstance)); cls->defineFinalizeFunction(_SE(js_dragonBones_CCFactory_finalize)); cls->install(); JSBClassType::registerClass(cls); diff --git a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_dragonbones_auto.hpp b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_dragonbones_auto.hpp index 846dabad0f..9b134d6628 100644 --- a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_dragonbones_auto.hpp +++ b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_dragonbones_auto.hpp @@ -285,5 +285,6 @@ SE_DECLARE_FUNC(js_cocos2dx_dragonbones_CCFactory_getTextureDisplay); SE_DECLARE_FUNC(js_cocos2dx_dragonbones_CCFactory_getSoundEventManater); SE_DECLARE_FUNC(js_cocos2dx_dragonbones_CCFactory_buildArmatureDisplay); SE_DECLARE_FUNC(js_cocos2dx_dragonbones_CCFactory_parseTextureAtlasData); -SE_DECLARE_FUNC(js_cocos2dx_dragonbones_CCFactory_CCFactory); +SE_DECLARE_FUNC(js_cocos2dx_dragonbones_CCFactory_destroyInstance); +SE_DECLARE_FUNC(js_cocos2dx_dragonbones_CCFactory_getInstance); diff --git a/native/cocos/scripting/js-bindings/manual/jsb_dragonbones_manual.cpp b/native/cocos/scripting/js-bindings/manual/jsb_dragonbones_manual.cpp index 45741905ca..60be57b760 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_dragonbones_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_dragonbones_manual.cpp @@ -10,7 +10,6 @@ using namespace cocos2d; - static bool js_cocos2dx_dragonbones_Armature_getAnimation(se::State& s) { if (s.args().size() == 0) @@ -269,8 +268,8 @@ static bool js_cocos2dx_dragonbones_CCFactory_getFactory(se::State& s) { if (s.args().size() == 0) { - const dragonBones::CCFactory& ret = dragonBones::CCFactory::factory; - bool ok = native_ptr_to_rooted_seval((dragonBones::CCFactory*)&ret, __jsb_dragonBones_CCFactory_class, &s.rval()); + auto ret = dragonBones::CCFactory::getInstance(); + bool ok = native_ptr_to_rooted_seval(ret, __jsb_dragonBones_CCFactory_class, &s.rval()); SE_PRECONDITION2(ok, false, "Convert dragonBones::CCFactory to se::Value failed!"); return true; } @@ -452,6 +451,65 @@ bool register_all_dragonbones_manual(se::Object* obj) } }); + se::ScriptEngine::getInstance()->addAfterCleanupHook([](){ + + // Destroy CCFactory singlton. + dragonBones::CCFactory::destroyInstance(); + + // World clock is a static variable and needs to be cleared and reset. + dragonBones::WorldClock::clock.clear(); + dragonBones::WorldClock::clock.time = 0.0f; + dragonBones::WorldClock::clock.timeScale = 1.0f; + + // Copy the dragonbones object vector since vector element will be deleted in BaseObject destructor. + std::vector allDragonBonesObjects = dragonBones::BaseObject::getAllObjects(); + SE_LOGD("Starting to cleanup dragonbones object, count: %d\n", (int)allDragonBonesObjects.size()); + // Clear dragonBones::Armature objects those are not in the pool because + // dragonBones::Armature controls life cycle for lots of other objects, + // so it needs to be disposed first. + for (auto dbObj : allDragonBonesObjects) + { + if (dynamic_cast(dbObj) != nullptr && !dbObj->isInPool()) + { +// SE_LOGD("1. Force delete not in pool DragonBones Armature object: %s, %p\n", typeid(*dbObj).name(), dbObj); + delete dbObj; + } + } + + // After disposing dragonBones::Armature objects, there will be lots of other kinds of objects returned to pool. + // Therefore, we clean object pool here. + dragonBones::BaseObject::clearPool(0); + + // Copy the dragonbones object vector again. + allDragonBonesObjects = dragonBones::BaseObject::getAllObjects(); + SE_LOGD("After first cleanup, dragonbones object remained count: %d\n", (int)allDragonBonesObjects.size()); + // Check again whether there are some objects still in pool since the releationship of dragonbones objects is really complex. + for (auto dbObj : allDragonBonesObjects) + { + if (!dbObj->isInPool()) + { +// SE_LOGD("2. Force delete not in pool DragonBones object: %s, %p\n", typeid(*dbObj).name(), dbObj); + delete dbObj; + } + } + + // Clear pool again. + dragonBones::BaseObject::clearPool(0); + + // Don't need to use copy operator since we only print leak object below. + auto& refAllDragonBonesObjects = dragonBones::BaseObject::getAllObjects(); + SE_LOGD("After second cleanup, dragonbones object remained count: %d\n", (int)refAllDragonBonesObjects.size()); + + // Print leak objects + for (auto dbObj : refAllDragonBonesObjects) + { + SE_LOGD("Leak dragonbones object: %s, %p\n", typeid(*dbObj).name(), dbObj); + } + + // If there're leak objects, clear vector should be done for restarting game. + refAllDragonBonesObjects.clear(); + }); + se::ScriptEngine::getInstance()->clearException(); return true; diff --git a/native/tools/tojs/cocos2dx_dragonbones.ini b/native/tools/tojs/cocos2dx_dragonbones.ini index b32c38e458..0e6455bc21 100644 --- a/native/tools/tojs/cocos2dx_dragonbones.ini +++ b/native/tools/tojs/cocos2dx_dragonbones.ini @@ -69,4 +69,4 @@ rename_functions = CCArmatureDisplay::[getArmature=armature addEvent=addEventLis rename_classes = -classes_owned_by_cpp = DragonBonesData Armature CCSlot WorldClock Animation Slot BaseFactory BaseObject TextureData CCTextureData TextureAtlasData CCTextureAtlasData AnimationState EventObject Bone Transform Matrix TransformObject ArmatureData BoneData SlotData SkinData AnimationData +classes_owned_by_cpp = DragonBonesData Armature CCSlot WorldClock Animation Slot BaseFactory BaseObject TextureData CCTextureData TextureAtlasData CCTextureAtlasData AnimationState EventObject Bone Transform Matrix TransformObject ArmatureData BoneData SlotData SkinData AnimationData CCFactory From 653367df9f6a9b661b24337e92174d0c3b09cd41 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 18 Jan 2018 13:58:41 +0800 Subject: [PATCH 11/35] Update cocos2dx_dragonbones.ini --- native/tools/tojs/cocos2dx_dragonbones.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/native/tools/tojs/cocos2dx_dragonbones.ini b/native/tools/tojs/cocos2dx_dragonbones.ini index 0e6455bc21..c2ad0a0c43 100644 --- a/native/tools/tojs/cocos2dx_dragonbones.ini +++ b/native/tools/tojs/cocos2dx_dragonbones.ini @@ -40,7 +40,7 @@ skip = CCFactory::[loadDragonBonesData loadTextureAtlasData], AnimationData::[cacheFrames addBoneTimeline addSlotTimeline addFFDTimeline getBontTimeline getSlotTimeline getFFDTimeline getBoneTimeline], SkinData::[addSlot getSlot], DBCCSprite::[getPolygonInfoModify draw], - BaseObject::[setObjectRecycleOrDestroyCallback], + BaseObject::[setObjectRecycleOrDestroyCallback isInPool getAllObjects], BoneTimelineData::[*], SlotData::[generateColor], TextureData::[generateRectangle] From eb84ae8003107f925a19a2d309f6f17c9d1bddde Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 18 Jan 2018 14:10:16 +0800 Subject: [PATCH 12/35] Bug fix of releasing JS object logic in CPP controls JS object's cycle mode (spine, dragonbones, box2d). (#1075) --- .../js-bindings/docs/JSB2.0-learning-en.md | 44 ++++++++++------ .../js-bindings/docs/JSB2.0-learning-zh.md | 43 ++++++++++------ .../js-bindings/manual/jsb_box2d_manual.cpp | 47 ++++++++++------- .../manual/jsb_dragonbones_manual.cpp | 50 ++++++++++++------- .../js-bindings/manual/jsb_spine_manual.cpp | 38 +++++++++----- 5 files changed, 144 insertions(+), 78 deletions(-) diff --git a/native/cocos/scripting/js-bindings/docs/JSB2.0-learning-en.md b/native/cocos/scripting/js-bindings/docs/JSB2.0-learning-en.md index 1d9db8658a..091780c832 100644 --- a/native/cocos/scripting/js-bindings/docs/JSB2.0-learning-en.md +++ b/native/cocos/scripting/js-bindings/docs/JSB2.0-learning-en.md @@ -178,33 +178,45 @@ Under normal circumstances, if CPP object is not a subclass of `cocos2d :: Ref`, ```c++ spTrackEntry_setDisposeCallback([](spTrackEntry* entry){ - // The callback of spTrackEntry destruction - auto cleanup = [entry](){ + se::Object* seObj = nullptr; - if (!se::ScriptEngine::getInstance()->isValid()) + auto iter = se::NativePtrToObjectMap::find(entry); + if (iter != se::NativePtrToObjectMap::end()) + { + // Save se::Object pointer for being used in cleanup method. + seObj = iter->second; + // Unmap native and js object since native object was destroyed. + // Otherwise, it may trigger 'assertion' in se::Object::setPrivateData later + // since native obj is already released and the new native object may be assigned with + // the same address. + se::NativePtrToObjectMap::erase(iter); + } + else + { + return; + } + + auto cleanup = [seObj](){ + + auto se = se::ScriptEngine::getInstance(); + if (!se->isValid() || se->isInCleanup()) return; se::AutoHandleScope hs; - se::ScriptEngine::getInstance()->clearException(); + se->clearException(); - auto iter = se::NativePtrToObjectMap::find(entry); - if (iter != se::NativePtrToObjectMap::end()) - { - CCLOG("spTrackEntry %p was recycled!", entry); - se::Object* seObj = iter->second; - seObj->clearPrivateData(); // Remove the mapping - seObj->unroot(); // unroot,make JS objects controlled by garbage collector - seObj->decRef(); // Decrease the reference of se::Object - } + // The native <-> JS mapping was cleared in the callback above. + // seObj->clearPrivateData isn't needed since the JS object will be garbage collected after unroot and decRef. + seObj->unroot(); + seObj->decRef(); }; - // Make sure not to touch JS engine API while garbage collecting. if (!se::ScriptEngine::getInstance()->isGarbageCollecting()) { cleanup(); } else - { // Put the cleanning task at the end of current game frame if it's in garbage collection. + { CleanupTask::pushTaskToAutoReleasePool(cleanup); } }); @@ -221,7 +233,7 @@ In addition, `se::Object` currently supports the manual creation of the followin * Plain Object: Created by `se::Object::createPlainObject`, similar to `var a = {};` in JS * Array Object: Created by `se::Object::createArrayObject`, similar to `var a = [];` in JS -* Uint8 Typed Array Object: Created by `se::Object::createUint8TypedArray`, like `var a = new Uint8Array(buffer);` in JS +* Uint8 Typed Array Object: Created by `se::Object::createTypedArray`, like `var a = new Uint8Array(buffer);` in JS * Array Buffer Object: Created by `se::Object::createArrayBufferObject` similar to `var a = new ArrayBuffer(len);` in JS __The Release of The Objects Created Manually__ diff --git a/native/cocos/scripting/js-bindings/docs/JSB2.0-learning-zh.md b/native/cocos/scripting/js-bindings/docs/JSB2.0-learning-zh.md index 196c64649a..816ab94d2d 100644 --- a/native/cocos/scripting/js-bindings/docs/JSB2.0-learning-zh.md +++ b/native/cocos/scripting/js-bindings/docs/JSB2.0-learning-zh.md @@ -178,23 +178,38 @@ se::Object 中提供了 root/unroot 方法供开发者调用,root 会把 JS ```c++ spTrackEntry_setDisposeCallback([](spTrackEntry* entry){ // spTrackEntry 的销毁回调 - auto cleanup = [entry](){ + se::Object* seObj = nullptr; - if (!se::ScriptEngine::getInstance()->isValid()) + auto iter = se::NativePtrToObjectMap::find(entry); + if (iter != se::NativePtrToObjectMap::end()) + { + // 保存 se::Object 指针,用于在下面的 cleanup 函数中释放其内存 + seObj = iter->second; + // Native 对象 entry 的内存已经被释放,因此需要立马解除 Native 对象与 JS 对象的关联。 + // 如果解除引用关系放在下面的 cleanup 函数中处理,有可能触发 se::Object::setPrivateData 中 + // 的断言,因为新生成的 Native 对象的地址可能与当前对象相同,而 cleanup 可能被延迟到帧结束前执行。 + se::NativePtrToObjectMap::erase(iter); + } + else + { + return; + } + + auto cleanup = [seObj](){ + + auto se = se::ScriptEngine::getInstance(); + if (!se->isValid() || se->isInCleanup()) return; se::AutoHandleScope hs; - se::ScriptEngine::getInstance()->clearException(); - - auto iter = se::NativePtrToObjectMap::find(entry); - if (iter != se::NativePtrToObjectMap::end()) - { - CCLOG("spTrackEntry %p was recycled!", entry); - se::Object* seObj = iter->second; - seObj->clearPrivateData(); // 解除 mapping 关系 - seObj->unroot(); // unroot,使 JS 对象受 GC 管理 - seObj->decRef(); // 释放 se::Object - } + se->clearException(); + + // 没必要调用 seObj->clearPrivateData ,因为 Native 对象与 JS 对象的引用关系已经在上面被解除。 + // 如果调用,反而会导致把新生成的 Native 对象的引用关系错误解除掉。 + // 设置 seObj 的 privateData 为 nullptr 也无意义,因为在执行 unroot 和 decRef 后, + // 当前 JS 对象即将被回收。 + seObj->unroot(); // unroot,使 JS 对象受 GC 管理 + seObj->decRef(); // 释放 se::Object }; // 确保不再垃圾回收中去操作 JS 引擎的 API @@ -218,7 +233,7 @@ __对象类型__ * Plain Object : 通过 se::Object::createPlainObject 创建,类似 JS 中的 `var a = {};` * Array Object : 通过 se::Object::createArrayObject 创建,类似 JS 中的 `var a = [];` -* Uint8 Typed Array Object : 通过 se::Object::createUint8TypedArray 创建,类似 JS 中的 `var a = new Uint8Array(buffer);` +* Uint8 Typed Array Object : 通过 se::Object::createTypedArray 创建,类似 JS 中的 `var a = new Uint8Array(buffer);` * Array Buffer Object : 通过 se::Object::createArrayBufferObject,类似 JS 中的 `var a = new ArrayBuffer(len);` __手动创建对象的释放__ diff --git a/native/cocos/scripting/js-bindings/manual/jsb_box2d_manual.cpp b/native/cocos/scripting/js-bindings/manual/jsb_box2d_manual.cpp index 6d69e1fff4..ffc5ea121a 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_box2d_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_box2d_manual.cpp @@ -1081,29 +1081,40 @@ bool register_all_box2d_manual(se::Object* obj) b2SetObjectDestroyNotifier([](void* obj, b2ObjectType type, const char* typeName){ - std::string typeNameStr = typeName; - auto cleanup = [obj, typeNameStr](){ + se::Object* seObj = nullptr; - if (!se::ScriptEngine::getInstance()->isValid()) + auto iter = se::NativePtrToObjectMap::find(obj); + if (iter != se::NativePtrToObjectMap::end()) + { + // Save se::Object pointer for being used in cleanup method. + seObj = iter->second; + // Unmap native and js object since native object was destroyed. + // Otherwise, it may trigger 'assertion' in se::Object::setPrivateData later + // since native obj is already released and the new native object may be assigned with + // the same address. + se::NativePtrToObjectMap::erase(iter); + } + else + { +// CCLOG("Didn't find %s, %p in map", typeName, obj); +// assert(false); + return; + } + + std::string typeNameStr = typeName; + auto cleanup = [seObj, typeNameStr](){ + + auto se = se::ScriptEngine::getInstance(); + if (!se->isValid() || se->isInCleanup()) return; se::AutoHandleScope hs; - se::ScriptEngine::getInstance()->clearException(); + se->clearException(); - auto iter = se::NativePtrToObjectMap::find(obj); - if (iter != se::NativePtrToObjectMap::end()) - { -// CCLOG("%s, %p was recycled!", typeNameStr.c_str(), obj); - se::Object* seObj = iter->second; - seObj->clearPrivateData(); - seObj->unroot(); - seObj->decRef(); - } - else - { -// CCLOG("Didn't find %s, %p in map", typeNameStr.c_str(), obj); -// assert(false); - } + // The native <-> JS mapping was cleared in the callback above. + // seObj->clearPrivateData isn't needed since the JS object will be garbage collected after unroot and decRef. + seObj->unroot(); + seObj->decRef(); }; if (!se::ScriptEngine::getInstance()->isGarbageCollecting()) diff --git a/native/cocos/scripting/js-bindings/manual/jsb_dragonbones_manual.cpp b/native/cocos/scripting/js-bindings/manual/jsb_dragonbones_manual.cpp index 60be57b760..142732d1e0 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_dragonbones_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_dragonbones_manual.cpp @@ -417,28 +417,42 @@ bool register_all_dragonbones_manual(se::Object* obj) dragonBones::BaseObject::setObjectRecycleOrDestroyCallback([](dragonBones::BaseObject* obj, int type){ -// std::string typeName = typeid(*obj).name(); - auto cleanup = [=](){ - if (!se::ScriptEngine::getInstance()->isValid()) + std::string typeName = typeid(*obj).name(); + + se::Object* seObj = nullptr; + + auto iter = se::NativePtrToObjectMap::find(obj); + if (iter != se::NativePtrToObjectMap::end()) + { + // Save se::Object pointer for being used in cleanup method. + seObj = iter->second; + // Unmap native and js object since native object was destroyed. + // Otherwise, it may trigger 'assertion' in se::Object::setPrivateData later + // since native obj is already released and the new native object may be assigned with + // the same address. + se::NativePtrToObjectMap::erase(iter); + } + else + { + // CCLOG("Didn't find %s, %p in map", typeName, obj); + // assert(false); + return; + } + + std::string typeNameStr = typeName; + auto cleanup = [seObj, typeNameStr](){ + + auto se = se::ScriptEngine::getInstance(); + if (!se->isValid() || se->isInCleanup()) return; se::AutoHandleScope hs; - se::ScriptEngine::getInstance()->clearException(); + se->clearException(); - auto iter = se::NativePtrToObjectMap::find(obj); - if (iter != se::NativePtrToObjectMap::end()) - { -// CCLOG("%s: %p was recycled!", typeName.c_str(), obj); - se::Object* seObj = iter->second; - seObj->clearPrivateData(); - seObj->unroot(); - seObj->decRef(); - } - else - { -// CCLOG("Didn't find %s, %p in map", typeName.c_str(), obj); - // assert(false); - } + // The native <-> JS mapping was cleared in the callback above. + // seObj->clearPrivateData isn't needed since the JS object will be garbage collected after unroot and decRef. + seObj->unroot(); + seObj->decRef(); }; if (!se::ScriptEngine::getInstance()->isGarbageCollecting()) diff --git a/native/cocos/scripting/js-bindings/manual/jsb_spine_manual.cpp b/native/cocos/scripting/js-bindings/manual/jsb_spine_manual.cpp index 8fa90712eb..df5c4a48b2 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_spine_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_spine_manual.cpp @@ -279,23 +279,37 @@ static bool js_register_spine_TrackEntry(se::Object* obj) __jsb_spine_TrackEntry_proto = cls->getProto(); spTrackEntry_setDisposeCallback([](spTrackEntry* entry){ - auto cleanup = [entry](){ + se::Object* seObj = nullptr; - if (!se::ScriptEngine::getInstance()->isValid()) + auto iter = se::NativePtrToObjectMap::find(entry); + if (iter != se::NativePtrToObjectMap::end()) + { + // Save se::Object pointer for being used in cleanup method. + seObj = iter->second; + // Unmap native and js object since native object was destroyed. + // Otherwise, it may trigger 'assertion' in se::Object::setPrivateData later + // since native obj is already released and the new native object may be assigned with + // the same address. + se::NativePtrToObjectMap::erase(iter); + } + else + { + return; + } + + auto cleanup = [seObj](){ + + auto se = se::ScriptEngine::getInstance(); + if (!se->isValid() || se->isInCleanup()) return; se::AutoHandleScope hs; - se::ScriptEngine::getInstance()->clearException(); + se->clearException(); - auto iter = se::NativePtrToObjectMap::find(entry); - if (iter != se::NativePtrToObjectMap::end()) - { - CCLOGINFO("spTrackEntry %p was recycled!", entry); - se::Object* seObj = iter->second; - seObj->clearPrivateData(); - seObj->unroot(); - seObj->decRef(); - } + // The native <-> JS mapping was cleared in the callback above. + // seObj->clearPrivateData isn't needed since the JS object will be garbage collected after unroot and decRef. + seObj->unroot(); + seObj->decRef(); }; if (!se::ScriptEngine::getInstance()->isGarbageCollecting()) From c3b8a63377f39604edb621416407c3f8589f8d83 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 18 Jan 2018 15:08:36 +0800 Subject: [PATCH 13/35] Don't trigger an assertion if can't find se::Object by a touch. Warning instead. (#1076) --- .../js-bindings/manual/jsb_cocos2dx_manual.cpp | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp b/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp index 167c91c4f3..fe02ad8e2f 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp @@ -853,8 +853,14 @@ static void onAfterDispatchTouchEvent(Event* event) for (auto&& touch : touches) { auto iter = se::NativePtrToObjectMap::find(touch); - assert(iter != se::NativePtrToObjectMap::end()); - iter->second->unroot(); + if (iter != se::NativePtrToObjectMap::end()) + { + iter->second->unroot(); + } + else + { + CCLOGWARN("Could not find touch %p, it's possible while restarting game and not all touches are released!", touch); + } } } } From 2abda7c5155da2c8f602e7ef7a301d6171bfb277 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 19 Jan 2018 19:10:09 +0800 Subject: [PATCH 14/35] Resolve delete targetScheduler map element wrongly. (#1079) * Resolve delete targetScheduler map element wrongly. * fix warning --- .../scripting/js-bindings/manual/jsb_node.cpp | 102 +++++++++++++----- 1 file changed, 75 insertions(+), 27 deletions(-) diff --git a/native/cocos/scripting/js-bindings/manual/jsb_node.cpp b/native/cocos/scripting/js-bindings/manual/jsb_node.cpp index 3ae43f37d4..3b047fd708 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_node.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_node.cpp @@ -176,6 +176,38 @@ static const char* SCHEDULE_FUNC_ID_KEY = "__seScheFuncId"; static std::unordered_map> __js_target_schedulekey_map; static std::unordered_map> __js_target_schedule_update_map; +#if COCOS2D_DEBUG > 1 +static void printElementsInTargetSchedulerMap() +{ + SE_LOGD("--------------------------\nschedule target count: %d\n", (int)__js_target_schedulekey_map.size()); + for (const auto& e1 : __js_target_schedulekey_map) + { + uint32_t targetID = e1.first; + const auto& functions = e1.second; + std::string functionIDStr; + if (!functions.empty()) + functionIDStr.append("["); + + for (const auto& fn : functions) + { + assert(fn.second.getFuncId() == fn.first); + assert(fn.second.getTargetId() == targetID); + char idStr[20] = {0}; + snprintf(idStr, sizeof(idStr), "%u", fn.first); + functionIDStr.append(idStr); + functionIDStr.append(","); + } + if (!functions.empty()) + { + functionIDStr = functionIDStr.substr(0, functionIDStr.size()-1); + functionIDStr.append("]"); + } + SE_LOGD("schedule target: %u, functions: %s\n", e1.first, functionIDStr.c_str()); + } + SE_LOGD("-------------------------- \n"); +} +#endif + static bool isScheduleExist(uint32_t jsFuncId, uint32_t jsTargetId, const ScheduleElement** outElement) { bool found = false; @@ -235,7 +267,7 @@ static bool isScheduleExist(const std::string& key, uint32_t jsTargetId, const S return found; } -static void removeSchedule(uint32_t jsFuncId, uint32_t jsTargetId, bool needDetachChild) +static void removeSchedule(const std::string& key, uint32_t jsFuncId, uint32_t jsTargetId, bool needDetachChild) { auto funcObjKeyMapIter = __js_target_schedulekey_map.find(jsTargetId); if (funcObjKeyMapIter != __js_target_schedulekey_map.end()) @@ -245,17 +277,20 @@ static void removeSchedule(uint32_t jsFuncId, uint32_t jsTargetId, bool needDeta auto iter = funcMap.find(jsFuncId); if (iter != funcMap.end()) { - se::Object* target = iter->second.getTarget(); - se::Object* func = iter->second.getFunc(); - if (needDetachChild) + if (iter->second.getKey() == key) { - target->detachObject(func); + se::Object* target = iter->second.getTarget(); + se::Object* func = iter->second.getFunc(); + if (needDetachChild) + { + target->detachObject(func); + } + + func->decRef(); + target->decRef(); + + funcMap.erase(iter); } - - func->decRef(); - target->decRef(); - - funcMap.erase(iter); } if (funcMap.empty()) @@ -420,22 +455,25 @@ static bool isTargetExistInScheduler(uint32_t targetId) class UnscheduleNotifier { public: - UnscheduleNotifier(uint32_t funcId, uint32_t targetId) - : _funcId(funcId) + UnscheduleNotifier(const std::string& key, uint32_t funcId, uint32_t targetId) + : _key(key) + , _funcId(funcId) , _targetId(targetId) { } ~UnscheduleNotifier() { -// SE_LOGD("~UnscheduleNotifier, targetId: %u, funcId: %u\n", _targetId, _funcId); - +#if COCOS2D_DEBUG > 1 + SE_LOGD("~UnscheduleNotifier, key: %s, targetId: %u, funcId: %u\n", _key.c_str(), _targetId, _funcId); +#endif se::ScriptEngine::getInstance()->clearException(); se::AutoHandleScope hs; - removeSchedule(_funcId, _targetId, false); + removeSchedule(_key, _funcId, _targetId, false); } private: + std::string _key; uint32_t _funcId; uint32_t _targetId; }; @@ -476,7 +514,7 @@ static bool Scheduler_scheduleCommon(Scheduler* scheduler, const se::Value& jsTh if (found && !key.empty()) { - removeSchedule(funcId, targetId, true); + removeSchedule(key, funcId, targetId, true); scheduler->unschedule(key, reinterpret_cast(targetId)); } } @@ -509,7 +547,7 @@ static bool Scheduler_scheduleCommon(Scheduler* scheduler, const se::Value& jsTh se::Object* target = jsThis.toObject(); insertSchedule(funcId, targetId, ScheduleElement(target, jsFunc.toObject(), key, targetId, funcId)); - std::shared_ptr unscheduleNotifier = std::make_shared(funcId, targetId); + std::shared_ptr unscheduleNotifier = std::make_shared(key, funcId, targetId); if (toRootTarget) { @@ -815,7 +853,7 @@ static bool Scheduler_unscheduleCommon(Scheduler* scheduler, const se::Value& js if (found && !key.empty()) { - removeSchedule(funcId, targetId, true); + removeSchedule(key, funcId, targetId, true); scheduler->unschedule(key, reinterpret_cast(targetId)); } else @@ -1132,13 +1170,9 @@ static bool js_cocos2dx_Scheduler_schedule(se::State& s) { const auto& args = s.args(); int argc = (int)args.size(); -#if 0//COCOS2D_DEBUG > 0 - SE_LOGD("--------------------------\nschedule target count: %d\n", (int)__js_target_schedulekey_map.size()); - for (const auto& e1 : __js_target_schedulekey_map) - { - SE_LOGD("schedule target: %p, functions: %d\n", e1.first, (int)e1.second.size()); - } - SE_LOGD("-------------------------- \n"); +#if COCOS2D_DEBUG > 1 + SE_LOGD("js_cocos2dx_Scheduler_schedule begin ...\n"); + printElementsInTargetSchedulerMap(); #endif // @@ -1198,7 +1232,12 @@ static bool js_cocos2dx_Scheduler_schedule(se::State& s) SE_PRECONDITION2(ok, false, "Converting 'isPaused' argument failed"); } - return Scheduler_scheduleCommon(cobj, jsThis, jsFunc, interval, repeat, delay, isPaused, !isBindedObject, "cc.Scheduler.schedule"); + bool ret = Scheduler_scheduleCommon(cobj, jsThis, jsFunc, interval, repeat, delay, isPaused, !isBindedObject, "cc.Scheduler.schedule"); +#if COCOS2D_DEBUG > 1 + SE_LOGD("js_cocos2dx_Scheduler_schedule end ...\n"); + printElementsInTargetSchedulerMap(); +#endif + return ret; } SE_REPORT_ERROR("wrong number of arguments: %d, expected: %s", argc, ">=2"); @@ -1209,6 +1248,10 @@ SE_BIND_FUNC(js_cocos2dx_Scheduler_schedule) static bool js_cocos2dx_Scheduler_unschedule(se::State& s) { +#if COCOS2D_DEBUG > 1 + SE_LOGD("js_cocos2dx_Scheduler_unschedule begin ...\n"); + printElementsInTargetSchedulerMap(); +#endif const auto& args = s.args(); int argc = (int)args.size(); @@ -1227,7 +1270,12 @@ static bool js_cocos2dx_Scheduler_unschedule(se::State& s) jsTarget = args[0]; } Scheduler* cobj = (Scheduler*)s.nativeThisObject(); - return Scheduler_unscheduleCommon(cobj, jsTarget, jsFuncOrKey); + bool ret = Scheduler_unscheduleCommon(cobj, jsTarget, jsFuncOrKey); +#if COCOS2D_DEBUG > 1 + SE_LOGD("js_cocos2dx_Scheduler_unschedule end ...\n"); + printElementsInTargetSchedulerMap(); +#endif + return ret; } SE_REPORT_ERROR("wrong number of arguments: %d, expected: %s", argc, ">=2"); return false; From a4d0759f58ec1bf366490dc818f5ad50adc6b78f Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Fri, 19 Jan 2018 19:11:37 +0800 Subject: [PATCH 15/35] did merge 1.6 (#1078) * fix fireball/issues/6475 * Fix unscheduleAllCallbacks not working for schedules by key --- .../android/java/src/org/cocos2dx/lib/Cocos2dxVideoView.java | 1 - 1 file changed, 1 deletion(-) diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoView.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoView.java index 67e15a697d..09c34cc1c0 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoView.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoView.java @@ -422,7 +422,6 @@ public class Cocos2dxVideoView extends SurfaceView implements MediaPlayerControl mCurrentState = STATE_PLAYBACK_COMPLETED; mTargetState = STATE_PLAYBACK_COMPLETED; - release(true); if (mOnVideoEventListener != null) { mOnVideoEventListener.onVideoEvent(mViewTag,EVENT_COMPLETED); } From 6e6c3b6e96f374b2f86216ddfa02097158685e04 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sun, 21 Jan 2018 16:10:23 +0800 Subject: [PATCH 16/35] cc.Scheduler.schedule(...) argument count be 3. (#1080) --- .../scripting/js-bindings/manual/jsb_node.cpp | 40 +++++++++++-------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/native/cocos/scripting/js-bindings/manual/jsb_node.cpp b/native/cocos/scripting/js-bindings/manual/jsb_node.cpp index 3b047fd708..a6c9763e7f 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_node.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_node.cpp @@ -1176,7 +1176,7 @@ static bool js_cocos2dx_Scheduler_schedule(se::State& s) #endif // - if (argc >= 4) + if (argc >= 3) { Scheduler* cobj = (Scheduler*)s.nativeThisObject(); @@ -1194,7 +1194,6 @@ static bool js_cocos2dx_Scheduler_schedule(se::State& s) jsThis = args[0]; } - bool isBindedObject = jsThis.toObject()->getPrivateData() != nullptr; // SE_LOGD("%s, is binded object: %s\n", __FUNCTION__, isBindedObject ? "true" : "false"); @@ -1209,27 +1208,34 @@ static bool js_cocos2dx_Scheduler_schedule(se::State& s) ok = seval_to_float(args[2], &interval); SE_PRECONDITION2(ok, false, "Converting 'interval' argument failed"); - - if (argc == 4) + if (argc == 4 && args[3].isBoolean()) { // callback, target, interval, paused - ok = seval_to_boolean(args[3], &isPaused); - SE_PRECONDITION2(ok, false, "Converting 'isPaused' argument failed"); + isPaused = args[3].toBoolean(); } - else if (argc >= 6) + else { // callback, target, interval, repeat, delay, paused - // repeat - ok = seval_to_uint32(args[3], &repeat); - SE_PRECONDITION2(ok, false, "Converting 'interval' argument failed"); + if (argc >= 4) + { + // repeat + ok = seval_to_uint32(args[3], &repeat); + SE_PRECONDITION2(ok, false, "Converting 'interval' argument failed"); + } - // delay - ok = seval_to_float(args[4], &delay); - SE_PRECONDITION2(ok, false, "Converting 'delay' argument failed"); + if (argc >= 5) + { + // delay + ok = seval_to_float(args[4], &delay); + SE_PRECONDITION2(ok, false, "Converting 'delay' argument failed"); + } - // isPaused - ok = seval_to_boolean(args[5], &isPaused); - SE_PRECONDITION2(ok, false, "Converting 'isPaused' argument failed"); + if (argc >= 6) + { + // isPaused + ok = seval_to_boolean(args[5], &isPaused); + SE_PRECONDITION2(ok, false, "Converting 'isPaused' argument failed"); + } } bool ret = Scheduler_scheduleCommon(cobj, jsThis, jsFunc, interval, repeat, delay, isPaused, !isBindedObject, "cc.Scheduler.schedule"); @@ -1240,7 +1246,7 @@ static bool js_cocos2dx_Scheduler_schedule(se::State& s) return ret; } - SE_REPORT_ERROR("wrong number of arguments: %d, expected: %s", argc, ">=2"); + SE_REPORT_ERROR("wrong number of arguments: %d, expected: %s", argc, ">=3"); return false; } SE_BIND_FUNC(js_cocos2dx_Scheduler_schedule) From 918a7cc4d965b7d7866380172d7fba9dba171372 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 23 Jan 2018 09:32:41 +0800 Subject: [PATCH 17/35] Fix redundant zero while se::Value::toStringForce for a float number. (#1081) --- native/cocos/scripting/js-bindings/jswrapper/Value.cpp | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/native/cocos/scripting/js-bindings/jswrapper/Value.cpp b/native/cocos/scripting/js-bindings/jswrapper/Value.cpp index 7a1bb6d3fd..eff11625f6 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/Value.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/Value.cpp @@ -509,12 +509,8 @@ namespace se { } else if (_type == Type::Number) { - char tmp[350] = {0}; - double remainder = fmod(_u._number, 1.0); - if (std::abs(remainder) > 0) - snprintf(tmp, sizeof(tmp), "%lf", _u._number); - else - snprintf(tmp, sizeof(tmp), "%d", (int32_t)_u._number); + char tmp[50] = {0}; + snprintf(tmp, sizeof(tmp), "%.17g", _u._number); ret = tmp; } else if (_type == Type::Object) From 50e386792c122fb135ca0f1e9b8f7c70d6c05b63 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 29 Jan 2018 10:50:39 +0800 Subject: [PATCH 18/35] Make dragonbones::CCFactory constructor public. (#1083) * Make dragonbones::CCFactory constructor public. * Adds auto_api.js --- .../dragonbones/cocos2dx/CCFactory.h | 5 +- .../dragonbones/core/BaseObject.cpp | 13 ++-- .../api/jsb_cocos2dx_dragonbones_auto_api.js | 9 +++ .../auto/jsb_cocos2dx_dragonbones_auto.cpp | 23 ++++++- .../auto/jsb_cocos2dx_dragonbones_auto.hpp | 1 + .../js-bindings/jswrapper/v8/Object.cpp | 61 ------------------- native/tools/tojs/cocos2dx_dragonbones.ini | 2 +- 7 files changed, 42 insertions(+), 72 deletions(-) diff --git a/native/cocos/editor-support/dragonbones/cocos2dx/CCFactory.h b/native/cocos/editor-support/dragonbones/cocos2dx/CCFactory.h index 4f1eef77bd..329fe06f3d 100644 --- a/native/cocos/editor-support/dragonbones/cocos2dx/CCFactory.h +++ b/native/cocos/editor-support/dragonbones/cocos2dx/CCFactory.h @@ -12,10 +12,9 @@ class CCFactory : public BaseFactory public: static CCFactory* getInstance(); static void destroyInstance(); -private: + CCFactory(); ~CCFactory(); - DRAGONBONES_DISALLOW_COPY_AND_ASSIGN(CCFactory); protected: virtual TextureAtlasData* _generateTextureAtlasData(TextureAtlasData* textureAtlasData, void* textureAtlas) const override; @@ -32,6 +31,8 @@ public: private: void _initTextureAtlasData(TextureAtlasData* atlasData); + + DRAGONBONES_DISALLOW_COPY_AND_ASSIGN(CCFactory); }; DRAGONBONES_NAMESPACE_END diff --git a/native/cocos/editor-support/dragonbones/core/BaseObject.cpp b/native/cocos/editor-support/dragonbones/core/BaseObject.cpp index 0ead7068af..380636d3d7 100644 --- a/native/cocos/editor-support/dragonbones/core/BaseObject.cpp +++ b/native/cocos/editor-support/dragonbones/core/BaseObject.cpp @@ -28,14 +28,12 @@ void BaseObject::_returnObject(BaseObject* object) DRAGONBONES_ASSERT(false, "The object aleady in pool."); } + object->_isInPool = true; if (_recycleOrDestroyCallback != nullptr) _recycleOrDestroyCallback(object, 0); } else { - if (_recycleOrDestroyCallback != nullptr) - _recycleOrDestroyCallback(object, 1); - delete object; } } @@ -129,8 +127,6 @@ void BaseObject::clearPool(std::size_t classTypeIndex) } } - - BaseObject::BaseObject() : hashCode(BaseObject::_hashCode++) , _isInPool(false) @@ -140,6 +136,9 @@ BaseObject::BaseObject() BaseObject::~BaseObject() { + if (_recycleOrDestroyCallback != nullptr) + _recycleOrDestroyCallback(this, 1); + auto iter = std::find(__allDragonBonesObjects.begin(), __allDragonBonesObjects.end(), this); if (iter != __allDragonBonesObjects.end()) { @@ -150,8 +149,10 @@ BaseObject::~BaseObject() void BaseObject::returnToPool() { _onClear(); + // _returnObject make delete this BaseObject, + // so after the function invocation, any other operations of + // this object should not be done. _returnObject(this); - _isInPool = true; } std::vector& BaseObject::getAllObjects() diff --git a/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_dragonbones_auto_api.js b/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_dragonbones_auto_api.js index fe7f9b3bcf..23acb5ca28 100644 --- a/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_dragonbones_auto_api.js +++ b/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_dragonbones_auto_api.js @@ -1583,4 +1583,13 @@ getInstance : function ( return dragonBones::CCFactory; }, +/** + * @method CCFactory + * @constructor + */ +CCFactory : function ( +) +{ +}, + }; diff --git a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_dragonbones_auto.cpp b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_dragonbones_auto.cpp index c4fbc43ca9..ddfd0650fa 100644 --- a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_dragonbones_auto.cpp +++ b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_dragonbones_auto.cpp @@ -4875,7 +4875,7 @@ static bool js_cocos2dx_dragonbones_CCFactory_getInstance(se::State& s) CC_UNUSED bool ok = true; if (argc == 0) { dragonBones::CCFactory* result = dragonBones::CCFactory::getInstance(); - ok &= native_ptr_to_rooted_seval((dragonBones::CCFactory*)result, &s.rval()); + ok &= native_ptr_to_seval((dragonBones::CCFactory*)result, &s.rval()); SE_PRECONDITION2(ok, false, "js_cocos2dx_dragonbones_CCFactory_getInstance : Error processing arguments"); return true; } @@ -4884,19 +4884,38 @@ static bool js_cocos2dx_dragonbones_CCFactory_getInstance(se::State& s) } SE_BIND_FUNC(js_cocos2dx_dragonbones_CCFactory_getInstance) +SE_DECLARE_FINALIZE_FUNC(js_dragonBones_CCFactory_finalize) + +static bool js_cocos2dx_dragonbones_CCFactory_constructor(se::State& s) +{ + dragonBones::CCFactory* cobj = new (std::nothrow) dragonBones::CCFactory(); + s.thisObject()->setPrivateData(cobj); + se::NonRefNativePtrCreatedByCtorMap::emplace(cobj); + return true; +} +SE_BIND_CTOR(js_cocos2dx_dragonbones_CCFactory_constructor, __jsb_dragonBones_CCFactory_class, js_dragonBones_CCFactory_finalize) + + extern se::Object* __jsb_dragonBones_BaseFactory_proto; static bool js_dragonBones_CCFactory_finalize(se::State& s) { CCLOGINFO("jsbindings: finalizing JS object %p (dragonBones::CCFactory)", s.nativeThisObject()); + auto iter = se::NonRefNativePtrCreatedByCtorMap::find(s.nativeThisObject()); + if (iter != se::NonRefNativePtrCreatedByCtorMap::end()) + { + se::NonRefNativePtrCreatedByCtorMap::erase(iter); + dragonBones::CCFactory* cobj = (dragonBones::CCFactory*)s.nativeThisObject(); + delete cobj; + } return true; } SE_BIND_FINALIZE_FUNC(js_dragonBones_CCFactory_finalize) bool js_register_cocos2dx_dragonbones_CCFactory(se::Object* obj) { - auto cls = se::Class::create("CCFactory", obj, __jsb_dragonBones_BaseFactory_proto, nullptr); + auto cls = se::Class::create("CCFactory", obj, __jsb_dragonBones_BaseFactory_proto, _SE(js_cocos2dx_dragonbones_CCFactory_constructor)); cls->defineFunction("getTextureDisplay", _SE(js_cocos2dx_dragonbones_CCFactory_getTextureDisplay)); cls->defineFunction("getSoundEventManater", _SE(js_cocos2dx_dragonbones_CCFactory_getSoundEventManater)); diff --git a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_dragonbones_auto.hpp b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_dragonbones_auto.hpp index 9b134d6628..9091a59ce7 100644 --- a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_dragonbones_auto.hpp +++ b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_dragonbones_auto.hpp @@ -287,4 +287,5 @@ SE_DECLARE_FUNC(js_cocos2dx_dragonbones_CCFactory_buildArmatureDisplay); SE_DECLARE_FUNC(js_cocos2dx_dragonbones_CCFactory_parseTextureAtlasData); SE_DECLARE_FUNC(js_cocos2dx_dragonbones_CCFactory_destroyInstance); SE_DECLARE_FUNC(js_cocos2dx_dragonbones_CCFactory_getInstance); +SE_DECLARE_FUNC(js_cocos2dx_dragonbones_CCFactory_CCFactory); diff --git a/native/cocos/scripting/js-bindings/jswrapper/v8/Object.cpp b/native/cocos/scripting/js-bindings/jswrapper/v8/Object.cpp index 2ed6e97604..9bad7be321 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/v8/Object.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/v8/Object.cpp @@ -603,67 +603,6 @@ namespace se { return ret.IsJust() && ret.FromJust(); } -// void Object::getAsFloat32Array(float **ptr, unsigned int *length) { -// float *pt; -// unsigned int len; -// -// v8::Local value = _obj.handle(__isolate); -// -// v8::Local myarr = _obj.handle(__isolate).As(); -// len = myarr->Length(); -// pt = (float *) ((char *) myarr->Buffer()->GetContents().Data() + myarr->ByteOffset()); -// -// *length = len; -// *ptr = pt; -// } -// -// void Object::getAsUint8Array(unsigned char **ptr, unsigned int *length) { -// unsigned char *pt; -// unsigned int len; -// -// v8::Local value = _obj.handle(__isolate); -// -// v8::Local myarr = _obj.handle(__isolate).As(); -// -// len = myarr->Length(); -// pt = (unsigned char *) myarr->Buffer()->GetContents().Data() + myarr->ByteOffset(); -// -// *length = len; -// *ptr = pt; -// } -// -// void Object::getAsUint16Array(unsigned short **ptr, unsigned int *length) { -// unsigned short *pt; -// unsigned int len; -// -// v8::Local value = _obj.handle(__isolate); -// -// v8::Local myarr = _obj.handle(__isolate).As(); -// -// len = myarr->Length(); -// pt = (unsigned short *) myarr->Buffer()->GetContents().Data(); -// -// *length = len; -// *ptr = pt; -// } -// -// void Object::getAsUint32Array(unsigned int **ptr, unsigned int *length) { -// unsigned int *pt; -// unsigned int len; -// -// v8::Local value = _obj.handle(__isolate); -// -// v8::Local myarr = _obj.handle(__isolate).As(); -// -// len = myarr->Length(); -// -// //ArrayBuffer::Contents float_c=pt=myarr->Buffer()->GetContents(); -// pt = (unsigned int *) myarr->Buffer()->GetContents().Data(); -// -// *length = len; -// *ptr = pt; -// } - bool Object::getAllKeys(std::vector* allKeys) const { assert(allKeys != nullptr); diff --git a/native/tools/tojs/cocos2dx_dragonbones.ini b/native/tools/tojs/cocos2dx_dragonbones.ini index c2ad0a0c43..20932ef8ad 100644 --- a/native/tools/tojs/cocos2dx_dragonbones.ini +++ b/native/tools/tojs/cocos2dx_dragonbones.ini @@ -69,4 +69,4 @@ rename_functions = CCArmatureDisplay::[getArmature=armature addEvent=addEventLis rename_classes = -classes_owned_by_cpp = DragonBonesData Armature CCSlot WorldClock Animation Slot BaseFactory BaseObject TextureData CCTextureData TextureAtlasData CCTextureAtlasData AnimationState EventObject Bone Transform Matrix TransformObject ArmatureData BoneData SlotData SkinData AnimationData CCFactory +classes_owned_by_cpp = DragonBonesData Armature CCSlot WorldClock Animation Slot BaseFactory BaseObject TextureData CCTextureData TextureAtlasData CCTextureAtlasData AnimationState EventObject Bone Transform Matrix TransformObject ArmatureData BoneData SlotData SkinData AnimationData From fd523f4fe194e60923223baa9b9ddc6a0adf7c73 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 31 Jan 2018 10:14:34 +0800 Subject: [PATCH 19/35] Fixes docs mistake. (#1085) --- native/cocos/scripting/js-bindings/docs/JSB2.0-learning-en.md | 2 ++ native/cocos/scripting/js-bindings/docs/JSB2.0-learning-zh.md | 2 ++ 2 files changed, 4 insertions(+) diff --git a/native/cocos/scripting/js-bindings/docs/JSB2.0-learning-en.md b/native/cocos/scripting/js-bindings/docs/JSB2.0-learning-en.md index 091780c832..6b220e2221 100644 --- a/native/cocos/scripting/js-bindings/docs/JSB2.0-learning-en.md +++ b/native/cocos/scripting/js-bindings/docs/JSB2.0-learning-en.md @@ -525,6 +525,8 @@ namespace ns { static bool js_SomeClass_finalize(se::State& s) { + ns::SomeClass* cobj = (ns::SomeClass*)s.nativeThisObject(); + delete cobj; return true; } SE_BIND_FINALIZE_FUNC(js_SomeClass_finalize) diff --git a/native/cocos/scripting/js-bindings/docs/JSB2.0-learning-zh.md b/native/cocos/scripting/js-bindings/docs/JSB2.0-learning-zh.md index 816ab94d2d..a1f16a1aa1 100644 --- a/native/cocos/scripting/js-bindings/docs/JSB2.0-learning-zh.md +++ b/native/cocos/scripting/js-bindings/docs/JSB2.0-learning-zh.md @@ -519,6 +519,8 @@ namespace ns { static bool js_SomeClass_finalize(se::State& s) { + ns::SomeClass* cobj = (ns::SomeClass*)s.nativeThisObject(); + delete cobj; return true; } SE_BIND_FINALIZE_FUNC(js_SomeClass_finalize) From c462b3c702f5ff59430fd733f34a870d4a507a9f Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 31 Jan 2018 17:47:29 +0800 Subject: [PATCH 20/35] Binds cc.Scheduler.pauseAllTargets and cc.Scheduler.pauseAllTargetsWithMinPriority. (#1087) --- .../scripting/js-bindings/manual/jsb_node.cpp | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/native/cocos/scripting/js-bindings/manual/jsb_node.cpp b/native/cocos/scripting/js-bindings/manual/jsb_node.cpp index a6c9763e7f..0bf3bfbbb0 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_node.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_node.cpp @@ -1450,6 +1450,74 @@ static bool js_cocos2dx_Scheduler_isTargetPaused(se::State& s) } SE_BIND_FUNC(js_cocos2dx_Scheduler_isTargetPaused) +static void fillScheduleTargetArray(se::Object* ret, const std::set& targets) +{ + uint32_t index = 0; + for (void* target : targets) + { + uint32_t targetID = (uint32_t)reinterpret_cast(target); + auto iter = __js_target_schedulekey_map.find(targetID); + if (iter != __js_target_schedulekey_map.end()) + { + se::Object* targetObj = iter->second.begin()->second.getTarget(); + ret->setArrayElement(index, se::Value(targetObj)); + ++index; + } + else + { + auto updateIter = __js_target_schedule_update_map.find(targetID); + if (updateIter != __js_target_schedule_update_map.end()) + { + se::Object* targetObj = updateIter->second.second; + ret->setArrayElement(index, se::Value(targetObj)); + ++index; + } + } + } +} + +static bool js_cocos2dx_Scheduler_pauseAllTargets(se::State& s) +{ + const auto& args = s.args(); + int argc = (int)args.size(); + if (argc == 0) + { + Scheduler* cobj = (Scheduler*)s.nativeThisObject(); + std::set targets = cobj->pauseAllTargets(); + se::HandleObject ret(se::Object::createArrayObject((uint32_t)targets.size())); + fillScheduleTargetArray(ret.get(), targets); + s.rval().setObject(ret); + return true; + } + + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 0); + return false; +} +SE_BIND_FUNC(js_cocos2dx_Scheduler_pauseAllTargets) + +static bool js_cocos2dx_Scheduler_pauseAllTargetsWithMinPriority(se::State& s) +{ + const auto& args = s.args(); + int argc = (int)args.size(); + if (argc == 1) + { + Scheduler* cobj = (Scheduler*)s.nativeThisObject(); + int minPriority = 0; + bool ok = seval_to_int32(args[0], &minPriority); + SE_PRECONDITION2(ok, false, "Converting 'minPriority' argument failed"); + + std::set targets = cobj->pauseAllTargetsWithMinPriority(minPriority); + se::HandleObject ret(se::Object::createArrayObject((uint32_t)targets.size())); + fillScheduleTargetArray(ret.get(), targets); + s.rval().setObject(ret); + return true; + } + + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 1); + return false; +} +SE_BIND_FUNC(js_cocos2dx_Scheduler_pauseAllTargetsWithMinPriority) + static void resumeAllSchedulesForTarget(Node* node, se::Object* jsThis) { node->getScheduler()->resumeTarget(jsThis); @@ -1596,6 +1664,8 @@ bool jsb_register_Node_manual(se::Object* global) schedulerProto->defineFunction("pauseTarget", _SE(js_cocos2dx_Scheduler_pauseTarget)); schedulerProto->defineFunction("resumeTarget", _SE(js_cocos2dx_Scheduler_resumeTarget)); schedulerProto->defineFunction("isTargetPaused", _SE(js_cocos2dx_Scheduler_isTargetPaused)); + schedulerProto->defineFunction("pauseAllTargets", _SE(js_cocos2dx_Scheduler_pauseAllTargets)); + schedulerProto->defineFunction("pauseAllTargetsWithMinPriority", _SE(js_cocos2dx_Scheduler_pauseAllTargetsWithMinPriority)); #if STANDALONE_TEST cls->defineFunction("addChild", _SE(Node_addChild)); From eb1d2e46cfd8ecce88e89a0af68bc609ee63908f Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 5 Feb 2018 10:46:41 +0800 Subject: [PATCH 21/35] Removes unused Texture2D::forceDeleteALLTexture2D which was added from runtime. (#1090) --- native/cocos/renderer/CCTexture2D.cpp | 14 -------------- native/cocos/renderer/CCTexture2D.h | 2 -- 2 files changed, 16 deletions(-) diff --git a/native/cocos/renderer/CCTexture2D.cpp b/native/cocos/renderer/CCTexture2D.cpp index 1fb42b4118..a5ce31da2b 100644 --- a/native/cocos/renderer/CCTexture2D.cpp +++ b/native/cocos/renderer/CCTexture2D.cpp @@ -431,16 +431,6 @@ void Texture2D::convertRGBA8888ToRGB5A1(const unsigned char* data, ssize_t dataL } // converter function end ////////////////////////////////////////////////////////////////////////// -static std::unordered_set s_allGLTexture2D; - -void Texture2D::forceDeleteALLTexture2D() -{ - auto copyMap = s_allGLTexture2D; - for (auto&& it: copyMap) { - delete it; - } - s_allGLTexture2D.clear(); -} Texture2D::Texture2D() : _pixelFormat(Texture2D::PixelFormat::DEFAULT) @@ -457,15 +447,11 @@ Texture2D::Texture2D() , _valid(true) , _alphaTexture(nullptr) { - s_allGLTexture2D.insert(this); _antialiasEnabled = Director::getInstance()->getOpenGLView()->isAntiAliasEnabled(); } Texture2D::~Texture2D() { - if (s_allGLTexture2D.find(this) != s_allGLTexture2D.end()) { - s_allGLTexture2D.erase(this); - } #if CC_ENABLE_CACHE_TEXTURE_DATA VolatileTextureMgr::removeTexture(this); #endif diff --git a/native/cocos/renderer/CCTexture2D.h b/native/cocos/renderer/CCTexture2D.h index 90061efaad..7f413319ec 100644 --- a/native/cocos/renderer/CCTexture2D.h +++ b/native/cocos/renderer/CCTexture2D.h @@ -179,8 +179,6 @@ public: */ static Texture2D::PixelFormat getDefaultAlphaPixelFormat(); - static void forceDeleteALLTexture2D(); - public: /** * @js ctor From e7c6fc492be4a75483b07d9a936da1dacf3fa6cd Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 7 Feb 2018 18:29:03 +0800 Subject: [PATCH 22/35] Fix memory leak which will cause slow down on games those use lot of actions. (#1094) --- native/cocos/2d/CCActionManager.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/native/cocos/2d/CCActionManager.cpp b/native/cocos/2d/CCActionManager.cpp index c29d232ca4..e8bed6fce6 100644 --- a/native/cocos/2d/CCActionManager.cpp +++ b/native/cocos/2d/CCActionManager.cpp @@ -238,9 +238,7 @@ void ActionManager::removeAllActionsFromTarget(Node *target) element->currentAction->retain(); element->currentActionSalvaged = true; } - - ccArrayRemoveAllObjects(element->actions); - + #if CC_ENABLE_GC_FOR_NATIVE_OBJECTS auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine(); if (sEngine) @@ -256,6 +254,8 @@ void ActionManager::removeAllActionsFromTarget(Node *target) } } #endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS + + ccArrayRemoveAllObjects(element->actions); if (_currentTarget == element) { From 5df0d63573a0048f426a187cc1d793998b0d9af5 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 7 Feb 2018 19:02:01 +0800 Subject: [PATCH 23/35] Adds JS interfaces for getting JSBinding object count. (#1095) __jsc__.getJSBindingObjectCount returns the mapping size of Ref's sub class object and non-Ref class but lifecycle controlled by C++. __jsc__.getJSBindingObjectCountNonRefCreatedInJS returns the mapping size of Non-Ref class object and JS object created in JS. --- .../js-bindings/manual/jsb_global.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/native/cocos/scripting/js-bindings/manual/jsb_global.cpp b/native/cocos/scripting/js-bindings/manual/jsb_global.cpp index 6d4358eb62..de768cf864 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_global.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_global.cpp @@ -818,6 +818,22 @@ static bool js_performance_now(se::State& s) } SE_BIND_FUNC(js_performance_now) +static bool JSB_getJSBindingObjectCount(se::State& s) +{ + size_t size = se::NativePtrToObjectMap::size(); + s.rval().setUlong(size); + return true; +} +SE_BIND_FUNC(JSB_getJSBindingObjectCount) + +static bool JSB_getJSBindingObjectCountNonRefAndCreatedInJS(se::State& s) +{ + size_t size = se::NonRefNativePtrCreatedByCtorMap::size(); + s.rval().setUlong(size); + return true; +} +SE_BIND_FUNC(JSB_getJSBindingObjectCountNonRefAndCreatedInJS) + bool jsb_register_global_variables(se::Object* global) { global->defineFunction("require", _SE(require)); @@ -832,6 +848,8 @@ bool jsb_register_global_variables(se::Object* global) __jscObj->defineFunction("garbageCollect", _SE(jsc_garbageCollect)); __jscObj->defineFunction("dumpNativePtrToSeObjectMap", _SE(jsc_dumpNativePtrToSeObjectMap)); + __jscObj->defineFunction("getJSBindingObjectCount", _SE(JSB_getJSBindingObjectCount)); + __jscObj->defineFunction("getJSBindingObjectCountNonRefCreatedInJS", _SE(JSB_getJSBindingObjectCountNonRefAndCreatedInJS)); global->defineFunction("__getPlatform", _SE(JSBCore_platform)); global->defineFunction("__getOS", _SE(JSBCore_os)); From 5a14a7953bf0c9957cacd6564f8bd3b03e7202ed Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 8 Feb 2018 15:11:42 +0800 Subject: [PATCH 24/35] Crash fix for cc.spawn (#1098) --- native/cocos/2d/CCActionInterval.cpp | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/native/cocos/2d/CCActionInterval.cpp b/native/cocos/2d/CCActionInterval.cpp index 4cad4c04a3..412df090fa 100644 --- a/native/cocos/2d/CCActionInterval.cpp +++ b/native/cocos/2d/CCActionInterval.cpp @@ -263,6 +263,11 @@ bool Sequence::init(const Vector& arrayOfActions) { FiniteTimeAction *action = arrayOfActions.at(i); prev = createWithTwoActions(prev, action); + + // The owner 'prev' is a pure C++ object, 'createWithTwoActions' in the previous line + // will not be able to find a relevant JS object associated with 'prev' object. + // So 'retainScriptObject' in 'initWithTwoActions' will fail to hold 'prev' object. + // The workaround is that we need to associate 'action' to Sequence object like the following code. #if CC_ENABLE_GC_FOR_NATIVE_OBJECTS auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine(); if (sEngine) @@ -757,6 +762,11 @@ bool Spawn::init(const Vector& arrayOfActions) { FiniteTimeAction* action = arrayOfActions.at(i); prev = createWithTwoActions(prev, action); + + // The owner 'prev' is a pure C++ object, 'createWithTwoActions' in the previous line + // will not be able to find a relevant JS object associated with 'prev' object. + // So 'retainScriptObject' in 'initWithTwoActions' will fail to hold 'prev' object. + // The workaround is that we need to associate 'action' to Spawn object like the following code. #if CC_ENABLE_GC_FOR_NATIVE_OBJECTS auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine(); if (sEngine) @@ -800,13 +810,17 @@ bool Spawn::initWithTwoActions(FiniteTimeAction *action1, FiniteTimeAction *acti _one->retain(); _two->retain(); - + + // NOTE: We should retainScriptObject for action1 and action2 rather than _one and _two. + // It's because _one & _two actions are pure C++ objects and Sequence::initWithTwoActions + // can't retainScriptObject for action1 and action2. action1 or action2 will be hung up + // and they may be garbage collected whenever, which may cause crash bug that really hard to find. #if CC_ENABLE_GC_FOR_NATIVE_OBJECTS auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine(); if (sEngine) { - sEngine->retainScriptObject(this, _one); - sEngine->retainScriptObject(this, _two); + sEngine->retainScriptObject(this, action1); + sEngine->retainScriptObject(this, action2); } #endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS From 31c25306bf0c984085f5698dbd975445ee5d6007 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 8 Feb 2018 15:50:24 +0800 Subject: [PATCH 25/35] Removes unused code in CallFunc. (#1099) --- native/cocos/2d/CCActionInstant.cpp | 1 - native/cocos/2d/CCActionInstant.h | 38 +++-------------------------- 2 files changed, 3 insertions(+), 36 deletions(-) diff --git a/native/cocos/2d/CCActionInstant.cpp b/native/cocos/2d/CCActionInstant.cpp index e257fde431..c90b337f3a 100644 --- a/native/cocos/2d/CCActionInstant.cpp +++ b/native/cocos/2d/CCActionInstant.cpp @@ -348,7 +348,6 @@ bool CallFunc::initWithFunction(const std::function &func) CallFunc::~CallFunc() { - CC_SAFE_RELEASE(_selectorTarget); } CallFunc* CallFunc::clone() const diff --git a/native/cocos/2d/CCActionInstant.h b/native/cocos/2d/CCActionInstant.h index 0a58f93645..2a909ac43c 100644 --- a/native/cocos/2d/CCActionInstant.h +++ b/native/cocos/2d/CCActionInstant.h @@ -41,7 +41,7 @@ NS_CC_BEGIN /** @class ActionInstant * @brief Instant actions are immediate actions. They don't have a duration like the IntervalAction actions. **/ -class CC_DLL ActionInstant : public FiniteTimeAction // +class CC_DLL ActionInstant : public FiniteTimeAction { public: // @@ -315,7 +315,7 @@ private: /** @class CallFunc * @brief Calls a 'callback'. */ -class CC_DLL CallFunc : public ActionInstant // +class CC_DLL CallFunc : public ActionInstant { public: /** Creates the action with the callback of type std::function. @@ -334,28 +334,6 @@ public: */ virtual void execute(); - /** Get the selector target. - * - * @return The selector target. - */ - inline Ref* getTargetCallback() - { - return _selectorTarget; - } - - /** Set the selector target. - * - * @param sel The selector target. - */ - inline void setTargetCallback(Ref* sel) - { - if (sel != _selectorTarget) - { - CC_SAFE_RETAIN(sel); - CC_SAFE_RELEASE(_selectorTarget); - _selectorTarget = sel; - } - } // // Overrides // @@ -368,9 +346,7 @@ public: CC_CONSTRUCTOR_ACCESS: CallFunc() - : _selectorTarget(nullptr) - , _callFunc(nullptr) - , _function(nullptr) + : _function(nullptr) { } virtual ~CallFunc(); @@ -381,14 +357,6 @@ CC_CONSTRUCTOR_ACCESS: bool initWithFunction(const std::function& func); protected: - /** Target that will be called */ - Ref* _selectorTarget; - - union - { - SEL_CallFunc _callFunc; - SEL_CallFuncN _callFuncN; - }; /** function that will be called */ std::function _function; From 380b27b02ce75f0ef35bf4dd9c1006eaa5431e60 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 9 Feb 2018 12:53:29 +0800 Subject: [PATCH 26/35] fixed #1031: Potential Crash in JSB_WebSocketDelegate::onClose (#1103) --- .../scripting/js-bindings/manual/jsb_websocket.cpp | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/native/cocos/scripting/js-bindings/manual/jsb_websocket.cpp b/native/cocos/scripting/js-bindings/manual/jsb_websocket.cpp index 178cb28361..d5a2f493bd 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_websocket.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_websocket.cpp @@ -42,7 +42,6 @@ se::Class* __jsb_WebSocket_class = nullptr; class JSB_WebSocketDelegate : public Ref, public WebSocket::Delegate { public: - JSB_WebSocketDelegate() { } @@ -188,6 +187,10 @@ public: SE_REPORT_ERROR("Can't get onclose function!"); } + // Websocket instance is attached to global object in 'WebSocket_close' + // It's safe to detach it here since JS 'onclose' method has been already invoked. + se::ScriptEngine::getInstance()->getGlobalObject()->detachObject(wsObj); + } while(false); ws->release(); @@ -430,6 +433,15 @@ static bool WebSocket_close(se::State& s) { WebSocket* cobj = (WebSocket*)s.nativeThisObject(); cobj->closeAsync(); + // Attach current WebSocket instance to global object to prevent WebSocket instance + // being garbage collected after "ws.close(); ws = null;" + // There is a state that current WebSocket JS instance is being garbaged but its finalize + // callback has not be invoked. Then in "JSB_WebSocketDelegate::onClose", se::Object is + // still be able to be found and while invoking JS 'onclose' method, crash will happen since + // JS instance is invalid and is going to be collected. This bug is easiler reproduced on iOS + // because JavaScriptCore is more GC sensitive. + // Please note that we need to detach it from global object in "JSB_WebSocketDelegate::onClose". + se::ScriptEngine::getInstance()->getGlobalObject()->attachObject(s.thisObject()); return true; } SE_REPORT_ERROR("wrong number of arguments: %d, was expecting 0", argc); From 94f73ad6133987fca0102c60114cd5bcd7834716 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 9 Feb 2018 14:04:36 +0800 Subject: [PATCH 27/35] Updates version to 1.8.2 (#1105) --- native/cocos/cocos2d.cpp | 2 +- native/cocos/scripting/js-bindings/script/jsb_cocos2d.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/native/cocos/cocos2d.cpp b/native/cocos/cocos2d.cpp index 6ca64f60aa..be6a0ffe66 100644 --- a/native/cocos/cocos2d.cpp +++ b/native/cocos/cocos2d.cpp @@ -31,7 +31,7 @@ NS_CC_BEGIN CC_DLL const char* cocos2dVersion() { - return "1.7.0"; + return "Cocos2d-x-lite v1.8.2"; } NS_CC_END diff --git a/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js b/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js index 833973a05f..9c8399488c 100644 --- a/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js +++ b/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js @@ -26,7 +26,7 @@ // CCConfig.js // -cc.ENGINE_VERSION = "Cocos2d-x-lite v1.7.0"; +cc.ENGINE_VERSION = "Cocos2d-x-lite v1.8.2"; // Resolution policies From d4cfc6c37ed3eef7284a33be365836631c61b78a Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 9 Feb 2018 17:31:17 +0800 Subject: [PATCH 28/35] Fix mouse scroll event dispatching issue. (#1108) --- native/cocos/base/CCEvent.cpp | 5 +++++ native/cocos/base/CCEvent.h | 2 ++ native/cocos/base/CCEventMouse.cpp | 12 ++++++++++++ native/cocos/base/CCEventMouse.h | 1 + native/cocos/base/CCEventTouch.cpp | 3 +++ native/cocos/base/CCEventTouch.h | 9 +++++---- .../cocos/platform/desktop/CCGLViewImpl-desktop.cpp | 4 ++++ 7 files changed, 32 insertions(+), 4 deletions(-) diff --git a/native/cocos/base/CCEvent.cpp b/native/cocos/base/CCEvent.cpp index d6d7a7be1f..60a49676a4 100644 --- a/native/cocos/base/CCEvent.cpp +++ b/native/cocos/base/CCEvent.cpp @@ -37,5 +37,10 @@ Event::~Event() { } +void Event::reset() +{ + _isStopped = false; + _currentTarget = nullptr; +} NS_CC_END diff --git a/native/cocos/base/CCEvent.h b/native/cocos/base/CCEvent.h index e2e3eb0515..9521d65225 100644 --- a/native/cocos/base/CCEvent.h +++ b/native/cocos/base/CCEvent.h @@ -87,6 +87,8 @@ public: */ inline Node* getCurrentTarget() { return _currentTarget; }; + virtual void reset(); + protected: /** Sets current target */ inline void setCurrentTarget(Node* target) { _currentTarget = target; }; diff --git a/native/cocos/base/CCEventMouse.cpp b/native/cocos/base/CCEventMouse.cpp index 888939dead..a925aafe30 100644 --- a/native/cocos/base/CCEventMouse.cpp +++ b/native/cocos/base/CCEventMouse.cpp @@ -81,4 +81,16 @@ Vec2 EventMouse::getDelta() const { return getLocation() - getPreviousLocation(); } + +void EventMouse::reset() +{ + Event::reset(); + _mouseButton = -1; + _x = 0.0f; + _y = 0.0f; + _scrollX = 0.0f; + _scrollY = 0.0f; + _startPointCaptured = false; +} + NS_CC_END diff --git a/native/cocos/base/CCEventMouse.h b/native/cocos/base/CCEventMouse.h index e28d5ef4ee..1c6b771db8 100644 --- a/native/cocos/base/CCEventMouse.h +++ b/native/cocos/base/CCEventMouse.h @@ -172,6 +172,7 @@ public: */ Vec2 getStartLocationInView() const; + virtual void reset() override; private: virtual ~EventMouse() {} diff --git a/native/cocos/base/CCEventTouch.cpp b/native/cocos/base/CCEventTouch.cpp index ca30c2715c..eccd6b81b3 100644 --- a/native/cocos/base/CCEventTouch.cpp +++ b/native/cocos/base/CCEventTouch.cpp @@ -29,12 +29,15 @@ NS_CC_BEGIN EventTouch::EventTouch() : Event(Type::TOUCH) +, _eventCode(EventCode::INVALID) { _touches.reserve(MAX_TOUCHES); } void EventTouch::reset() { + Event::reset(); + _eventCode = EventCode::INVALID; _touches.clear(); } diff --git a/native/cocos/base/CCEventTouch.h b/native/cocos/base/CCEventTouch.h index d9f56ef5c9..e2df5d8e4a 100644 --- a/native/cocos/base/CCEventTouch.h +++ b/native/cocos/base/CCEventTouch.h @@ -50,10 +50,11 @@ public: /** EventCode Touch event code.*/ enum class EventCode { - BEGAN, + BEGAN = 0, MOVED, ENDED, - CANCELLED + CANCELLED, + INVALID = -1, }; /** @@ -74,6 +75,8 @@ public: */ inline const std::vector& getTouches() const { return _touches; }; + virtual void reset() override; + #if TOUCH_PERF_DEBUG /** Set the event code. * @@ -90,8 +93,6 @@ public: private: virtual ~EventTouch() {} - void reset(); - EventCode _eventCode; std::vector _touches; diff --git a/native/cocos/platform/desktop/CCGLViewImpl-desktop.cpp b/native/cocos/platform/desktop/CCGLViewImpl-desktop.cpp index 35bda4f19f..76463d9d7d 100644 --- a/native/cocos/platform/desktop/CCGLViewImpl-desktop.cpp +++ b/native/cocos/platform/desktop/CCGLViewImpl-desktop.cpp @@ -678,6 +678,7 @@ void GLViewImpl::onGLFWMouseCallBack(GLFWwindow* window, int button, int action, if(GLFW_PRESS == action) { EventMouse* event = __mouseDownEvent; + event->reset(); event->setCursorPosition(cursorX, cursorY); event->setMouseButton(button); Director::getInstance()->getEventDispatcher()->dispatchEvent(event); @@ -685,6 +686,7 @@ void GLViewImpl::onGLFWMouseCallBack(GLFWwindow* window, int button, int action, else if(GLFW_RELEASE == action) { EventMouse* event = __mouseUpEvent; + event->reset(); event->setCursorPosition(cursorX, cursorY); event->setMouseButton(button); Director::getInstance()->getEventDispatcher()->dispatchEvent(event); @@ -719,6 +721,7 @@ void GLViewImpl::onGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y) float cursorY = (_viewPortRect.origin.y + _viewPortRect.size.height - _mouseY) / _scaleY; EventMouse* event = __mouseMoveEvent; + event->reset(); // Set current button if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS) { @@ -739,6 +742,7 @@ void GLViewImpl::onGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y) void GLViewImpl::onGLFWMouseScrollCallback(GLFWwindow* window, double x, double y) { EventMouse* event = __mouseScrollEvent; + event->reset(); //Because OpenGL and cocos2d-x uses different Y axis, we need to convert the coordinate here float cursorX = (_mouseX - _viewPortRect.origin.x) / _scaleX; float cursorY = (_viewPortRect.origin.y + _viewPortRect.size.height - _mouseY) / _scaleY; From a195bffcade93fa368cca7faade8ea19132f2648 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sun, 11 Feb 2018 13:54:37 +0800 Subject: [PATCH 29/35] Ignore infinite loop in Exception handling. (#1110) --- .../js-bindings/jswrapper/jsc/ScriptEngine.cpp | 4 +++- .../scripting/js-bindings/jswrapper/jsc/Utils.cpp | 13 ++++++++++--- .../scripting/js-bindings/jswrapper/jsc/Utils.hpp | 2 +- 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/native/cocos/scripting/js-bindings/jswrapper/jsc/ScriptEngine.cpp b/native/cocos/scripting/js-bindings/jswrapper/jsc/ScriptEngine.cpp index 56f1b3bd84..341b90c747 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/jsc/ScriptEngine.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/jsc/ScriptEngine.cpp @@ -354,7 +354,9 @@ namespace se { ScriptEngine::ExceptionInfo ScriptEngine::_formatException(JSValueRef exception) { ExceptionInfo ret; - internal::forceConvertJsValueToStdString(_cx, exception, &ret.message); + + // Ignore Exception in forceConvertJsValueToStdString invocation to avoid infinite loop. + internal::forceConvertJsValueToStdString(_cx, exception, &ret.message, true); JSType type = JSValueGetType(_cx, exception); diff --git a/native/cocos/scripting/js-bindings/jswrapper/jsc/Utils.cpp b/native/cocos/scripting/js-bindings/jswrapper/jsc/Utils.cpp index d68a3fe0f1..cefee58096 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/jsc/Utils.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/jsc/Utils.cpp @@ -217,20 +217,27 @@ namespace se { } } - void forceConvertJsValueToStdString(JSContextRef cx, JSValueRef jsval, std::string* ret) + void forceConvertJsValueToStdString(JSContextRef cx, JSValueRef jsval, std::string* ret, bool ignoreException/* = false */) { JSValueRef exception = nullptr; JSStringRef jsstr = JSValueToStringCopy(cx, jsval, &exception); if (exception != nullptr) { - ScriptEngine::getInstance()->_clearException(exception); + // NOTE: ignoreException is true in ScriptEngine::_formatException because it's already in the _clearException process. + // Adds this flag to avoid infinite loop of _clearException -> _formatException -> forceConvertJsValueToStdString -> _clearException -> ... + if (!ignoreException) + { + ScriptEngine::getInstance()->_clearException(exception); + } ret->clear(); } else { jsStringToStdString(cx, jsstr, ret); } - JSStringRelease(jsstr); + + if (jsstr != nullptr) + JSStringRelease(jsstr); } void jsStringToStdString(JSContextRef cx, JSStringRef jsStr, std::string* ret) diff --git a/native/cocos/scripting/js-bindings/jswrapper/jsc/Utils.hpp b/native/cocos/scripting/js-bindings/jswrapper/jsc/Utils.hpp index 90b87308fb..f1576891fa 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/jsc/Utils.hpp +++ b/native/cocos/scripting/js-bindings/jswrapper/jsc/Utils.hpp @@ -50,7 +50,7 @@ namespace se { void jsToSeValue(JSContextRef cx, JSValueRef jsval, Value* v); void seToJsValue(JSContextRef cx, const Value& v, JSValueRef* jsval); - void forceConvertJsValueToStdString(JSContextRef cx, JSValueRef jsval, std::string* ret); + void forceConvertJsValueToStdString(JSContextRef cx, JSValueRef jsval, std::string* ret, bool ignoreException = false); void jsStringToStdString(JSContextRef cx, JSStringRef jsStr, std::string* ret); bool hasPrivate(JSObjectRef obj); From 6c134875d7dbbb7f88da4edb72669194a02d5ead Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Sun, 11 Feb 2018 14:47:15 +0800 Subject: [PATCH 30/35] [ci skip][AUTO]: updating jsbinding automatically (#1109) --- .../auto/api/jsb_cocos2dx_auto_api.js | 24 ++++++---- .../js-bindings/auto/jsb_cocos2dx_auto.cpp | 46 +++++++++++++------ .../js-bindings/auto/jsb_cocos2dx_auto.hpp | 5 +- 3 files changed, 50 insertions(+), 25 deletions(-) diff --git a/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_auto_api.js b/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_auto_api.js index c58dddef21..0b7681716f 100644 --- a/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_auto_api.js +++ b/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_auto_api.js @@ -467,13 +467,21 @@ Touch : function ( cc.Event = { /** - * @method isStopped - * @return {bool} + * @method reset */ -isStopped : function ( +reset : function ( ) { - return false; +}, + +/** + * @method getCurrentTarget + * @return {cc.Node} + */ +getCurrentTarget : function ( +) +{ + return cc.Node; }, /** @@ -487,13 +495,13 @@ getType : function ( }, /** - * @method getCurrentTarget - * @return {cc.Node} + * @method isStopped + * @return {bool} */ -getCurrentTarget : function ( +isStopped : function ( ) { - return cc.Node; + return false; }, /** diff --git a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp index c6db4e6228..dcb3e49438 100644 --- a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp +++ b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp @@ -1197,23 +1197,38 @@ bool js_register_cocos2dx_Touch(se::Object* obj) se::Object* __jsb_cocos2d_Event_proto = nullptr; se::Class* __jsb_cocos2d_Event_class = nullptr; -static bool js_cocos2dx_Event_isStopped(se::State& s) +static bool js_cocos2dx_Event_reset(se::State& s) { cocos2d::Event* cobj = (cocos2d::Event*)s.nativeThisObject(); - SE_PRECONDITION2(cobj, false, "js_cocos2dx_Event_isStopped : Invalid Native Object"); + SE_PRECONDITION2(cobj, false, "js_cocos2dx_Event_reset : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); - CC_UNUSED bool ok = true; if (argc == 0) { - bool result = cobj->isStopped(); - ok &= boolean_to_seval(result, &s.rval()); - SE_PRECONDITION2(ok, false, "js_cocos2dx_Event_isStopped : Error processing arguments"); + cobj->reset(); return true; } SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); return false; } -SE_BIND_FUNC(js_cocos2dx_Event_isStopped) +SE_BIND_FUNC(js_cocos2dx_Event_reset) + +static bool js_cocos2dx_Event_getCurrentTarget(se::State& s) +{ + cocos2d::Event* cobj = (cocos2d::Event*)s.nativeThisObject(); + SE_PRECONDITION2(cobj, false, "js_cocos2dx_Event_getCurrentTarget : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + cocos2d::Node* result = cobj->getCurrentTarget(); + ok &= native_ptr_to_seval((cocos2d::Node*)result, &s.rval()); + SE_PRECONDITION2(ok, false, "js_cocos2dx_Event_getCurrentTarget : Error processing arguments"); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_cocos2dx_Event_getCurrentTarget) static bool js_cocos2dx_Event_getType(se::State& s) { @@ -1233,23 +1248,23 @@ static bool js_cocos2dx_Event_getType(se::State& s) } SE_BIND_FUNC(js_cocos2dx_Event_getType) -static bool js_cocos2dx_Event_getCurrentTarget(se::State& s) +static bool js_cocos2dx_Event_isStopped(se::State& s) { cocos2d::Event* cobj = (cocos2d::Event*)s.nativeThisObject(); - SE_PRECONDITION2(cobj, false, "js_cocos2dx_Event_getCurrentTarget : Invalid Native Object"); + SE_PRECONDITION2(cobj, false, "js_cocos2dx_Event_isStopped : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); CC_UNUSED bool ok = true; if (argc == 0) { - cocos2d::Node* result = cobj->getCurrentTarget(); - ok &= native_ptr_to_seval((cocos2d::Node*)result, &s.rval()); - SE_PRECONDITION2(ok, false, "js_cocos2dx_Event_getCurrentTarget : Error processing arguments"); + bool result = cobj->isStopped(); + ok &= boolean_to_seval(result, &s.rval()); + SE_PRECONDITION2(ok, false, "js_cocos2dx_Event_isStopped : Error processing arguments"); return true; } SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); return false; } -SE_BIND_FUNC(js_cocos2dx_Event_getCurrentTarget) +SE_BIND_FUNC(js_cocos2dx_Event_isStopped) static bool js_cocos2dx_Event_stopPropagation(se::State& s) { @@ -1300,9 +1315,10 @@ bool js_register_cocos2dx_Event(se::Object* obj) { auto cls = se::Class::create("Event", obj, nullptr, _SE(js_cocos2dx_Event_constructor)); - cls->defineFunction("isStopped", _SE(js_cocos2dx_Event_isStopped)); - cls->defineFunction("getType", _SE(js_cocos2dx_Event_getType)); + cls->defineFunction("reset", _SE(js_cocos2dx_Event_reset)); cls->defineFunction("getCurrentTarget", _SE(js_cocos2dx_Event_getCurrentTarget)); + cls->defineFunction("getType", _SE(js_cocos2dx_Event_getType)); + cls->defineFunction("isStopped", _SE(js_cocos2dx_Event_isStopped)); cls->defineFunction("stopPropagation", _SE(js_cocos2dx_Event_stopPropagation)); cls->defineFinalizeFunction(_SE(js_cocos2d_Event_finalize)); cls->install(); diff --git a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp index 3647b8071e..e712e7bce4 100644 --- a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp +++ b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp @@ -68,9 +68,10 @@ extern se::Class* __jsb_cocos2d_Event_class; bool js_register_cocos2d_Event(se::Object* obj); bool register_all_cocos2dx(se::Object* obj); -SE_DECLARE_FUNC(js_cocos2dx_Event_isStopped); -SE_DECLARE_FUNC(js_cocos2dx_Event_getType); +SE_DECLARE_FUNC(js_cocos2dx_Event_reset); SE_DECLARE_FUNC(js_cocos2dx_Event_getCurrentTarget); +SE_DECLARE_FUNC(js_cocos2dx_Event_getType); +SE_DECLARE_FUNC(js_cocos2dx_Event_isStopped); SE_DECLARE_FUNC(js_cocos2dx_Event_stopPropagation); SE_DECLARE_FUNC(js_cocos2dx_Event_Event); From 38c09d7afa817786a6374093df5553a7a611ede8 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sun, 11 Feb 2018 17:25:13 +0800 Subject: [PATCH 31/35] Potential crash fix in cc.callFunc binding. (#1114) --- .../js-bindings/manual/jsb_cocos2dx_manual.cpp | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp b/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp index fe02ad8e2f..7838507aae 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp @@ -1468,14 +1468,21 @@ static bool js_cocos2dx_CallFunc_create(se::State& s) CallFuncN* ret = new (std::nothrow) CallFuncN; se::Object* jsobj = se::Object::createObjectWithClass(__jsb_cocos2d_CallFuncN_class); jsobj->setPrivateData(ret); + // Assign jsobj to s.rval() to avoid jsobj be swept by GC immediately. + // Because there is "jsobj->attachObject(funcVal.toObject());" in "js_cocos2dx_CallFunc_init" function. + // attachObject will do a function invocation which may mark 'jsobj' into an invalid state but without + // invoking CallFuncN's finalize callback immediately. + // AddressSanitizer in Xcode will prompt: heap-use-after-free on address. + s.rval().setObject(jsobj); - if (js_cocos2dx_CallFunc_init(ret, jsobj, args)) + if (!js_cocos2dx_CallFunc_init(ret, jsobj, args)) { - s.rval().setObject(jsobj); - return true; + s.rval().setUndefined(); + SE_REPORT_ERROR("js_cocos2dx_CallFunc_create: initWithFunction failed!"); + return false; } - SE_REPORT_ERROR("js_cocos2dx_CallFunc_create: initWithFunction failed!"); - return false; + + return true; } SE_REPORT_ERROR("js_cocos2dx_CallFunc_create: Invalid number of arguments"); return false; From a2a28b3bfdc52d4457813441e5f391ab01bb28cf Mon Sep 17 00:00:00 2001 From: James Chen Date: Sun, 11 Feb 2018 18:11:25 +0800 Subject: [PATCH 32/35] PR #1114 fix is incorrect, fix it again. (#1115) Potential crash fix in cc.callFunc binding. --- .../js-bindings/manual/jsb_cocos2dx_manual.cpp | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp b/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp index 7838507aae..cc831f18e9 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp @@ -1468,21 +1468,23 @@ static bool js_cocos2dx_CallFunc_create(se::State& s) CallFuncN* ret = new (std::nothrow) CallFuncN; se::Object* jsobj = se::Object::createObjectWithClass(__jsb_cocos2d_CallFuncN_class); jsobj->setPrivateData(ret); - // Assign jsobj to s.rval() to avoid jsobj be swept by GC immediately. + + // Assign jsobj to jsVal and auto root it to avoid jsobj be swept by GC immediately. // Because there is "jsobj->attachObject(funcVal.toObject());" in "js_cocos2dx_CallFunc_init" function. // attachObject will do a function invocation which may mark 'jsobj' into an invalid state but without // invoking CallFuncN's finalize callback immediately. // AddressSanitizer in Xcode will prompt: heap-use-after-free on address. - s.rval().setObject(jsobj); + se::Value jsVal; + jsVal.setObject(jsobj, true); // Pass true to indicate auto root / unroot by jsVal - if (!js_cocos2dx_CallFunc_init(ret, jsobj, args)) + if (js_cocos2dx_CallFunc_init(ret, jsobj, args)) { - s.rval().setUndefined(); - SE_REPORT_ERROR("js_cocos2dx_CallFunc_create: initWithFunction failed!"); - return false; + s.rval() = std::move(jsVal); + return true; } - return true; + SE_REPORT_ERROR("js_cocos2dx_CallFunc_create: initWithFunction failed!"); + return false; } SE_REPORT_ERROR("js_cocos2dx_CallFunc_create: Invalid number of arguments"); return false; From 89509a9e530f624cf31f322704ee0d0b354263dc Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 12 Feb 2018 17:03:03 +0800 Subject: [PATCH 33/35] [iOS] Potential crash fix in SE_BIND_CTOR macro. (#1116) --- .../js-bindings/jswrapper/chakracore/HelperMacros.h | 8 +++++++- .../scripting/js-bindings/jswrapper/jsc/HelperMacros.h | 8 +++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/native/cocos/scripting/js-bindings/jswrapper/chakracore/HelperMacros.h b/native/cocos/scripting/js-bindings/jswrapper/chakracore/HelperMacros.h index 36338d791a..7f86230ecc 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/chakracore/HelperMacros.h +++ b/native/cocos/scripting/js-bindings/jswrapper/chakracore/HelperMacros.h @@ -85,6 +85,11 @@ void funcName##Registry(void* nativeThisObject); +// NOTE: se::Object::createObjectWithClass(cls) will return a se::Object pointer which is watched by garbage collector. +// If there is a '_ctor' function of current class, '_property.toObject->call(...)' will be invoked which is an operation that may +// make garbage collector to mark the created JS object as a garbage and set it to an invalid state. +// If this happens, crash will be triggered. So please take care of the value returned from se::Object::createObjectWithClass. +// HOW TO FIX: Use a rooted se::Value to save the se::Object poiner returned by se::Object::createObjectWithClass. #define SE_BIND_CTOR(funcName, cls, finalizeCb) \ JsValueRef funcName##Registry(JsValueRef _callee, bool _isConstructCall, JsValueRef* _argv, unsigned short argc, void* _callbackState) \ { \ @@ -93,7 +98,8 @@ bool ret = true; \ se::ValueArray args; \ se::internal::jsToSeArgs(argc, _argv+1, &args); \ - se::Object* thisObject = se::Object::createObjectWithClass(cls); \ + se::Value thisVal(se::Object::createObjectWithClass(cls), true); \ + se::Object* thisObject = thisVal.toObject(); \ JsValueRef _jsRet = thisObject->_getJSObject(); \ se::State state(thisObject, args); \ ret = funcName(state); \ diff --git a/native/cocos/scripting/js-bindings/jswrapper/jsc/HelperMacros.h b/native/cocos/scripting/js-bindings/jswrapper/jsc/HelperMacros.h index ccf1f01450..1ed4f59f42 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/jsc/HelperMacros.h +++ b/native/cocos/scripting/js-bindings/jswrapper/jsc/HelperMacros.h @@ -89,13 +89,19 @@ void funcName##Registry(JSObjectRef _obj); +// NOTE: se::Object::createObjectWithClass(cls) will return a se::Object pointer which is watched by garbage collector. +// If there is a '_ctor' function of current class, '_property.toObject->call(...)' will be invoked which is an operation that may +// make garbage collector to mark the created JS object as a garbage and set it to an invalid state. +// If this happens, crash will be triggered. So please take care of the value returned from se::Object::createObjectWithClass. +// HOW TO FIX: Use a rooted se::Value to save the se::Object poiner returned by se::Object::createObjectWithClass. #define SE_BIND_CTOR(funcName, cls, finalizeCb) \ JSObjectRef funcName##Registry(JSContextRef _cx, JSObjectRef _constructor, size_t argc, const JSValueRef _argv[], JSValueRef* _exception) \ { \ bool ret = true; \ se::ValueArray args; \ se::internal::jsToSeArgs(_cx, argc, _argv, &args); \ - se::Object* thisObject = se::Object::createObjectWithClass(cls); \ + se::Value thisVal(se::Object::createObjectWithClass(cls), true); \ + se::Object* thisObject = thisVal.toObject(); \ JSValueRef _jsRet = JSValueMakeUndefined(_cx); \ se::State state(thisObject, args); \ ret = funcName(state); \ From cc1f3423d4366215c0ccbb782ba8c032c1b41bc5 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 22 Feb 2018 17:44:12 +0800 Subject: [PATCH 34/35] Reverts PR #1062 which may lead to other issues, fix it by another way. (#1117) * Fixes custom listener returned by cc.eventManager.addCustomListener isn't attached to cc.eventManager. * Reverts PR #1062 which may lead to other issues, fix it by another way. 1. JS LifeCycle control for GLProgram, GLProgramState. 2. jsb.registerNativeRef should be invoked in JS for cc.TMXTiledMap.getLayer/getObjectGroup/getObjectGroups, cc.TMXObjectGroup.getObject, cc.TMXObjectGroup.getObjects, cc.TMXObject.prototype.getNode. --- native/cocos/2d/CCActionInterval.cpp | 3 + native/cocos/2d/CCNode.cpp | 7 +- native/cocos/2d/CCNode.h | 2 +- native/cocos/renderer/CCGLProgramCache.cpp | 52 ++++++++- native/cocos/renderer/CCGLProgramCache.h | 8 ++ .../cocos/renderer/CCGLProgramStateCache.cpp | 32 +++++- native/cocos/renderer/CCGLProgramStateCache.h | 4 + native/cocos/renderer/CCTextureCache.cpp | 43 ++++---- native/cocos/renderer/CCTextureCache.h | 7 +- .../auto/api/jsb_cocos2dx_auto_api.js | 8 ++ .../js-bindings/auto/jsb_cocos2dx_auto.cpp | 16 +++ .../js-bindings/auto/jsb_cocos2dx_auto.hpp | 1 + .../js-bindings/manual/ScriptingCore.cpp | 36 +++--- .../manual/jsb_cocos2dx_manual.cpp | 104 +++++++++++++++++- .../scripting/js-bindings/script/jsb_boot.js | 10 ++ .../js-bindings/script/jsb_cocos2d.js | 59 +++++++++- 16 files changed, 329 insertions(+), 63 deletions(-) diff --git a/native/cocos/2d/CCActionInterval.cpp b/native/cocos/2d/CCActionInterval.cpp index 412df090fa..facf2c5b3b 100644 --- a/native/cocos/2d/CCActionInterval.cpp +++ b/native/cocos/2d/CCActionInterval.cpp @@ -290,6 +290,9 @@ bool Sequence::initWithTwoActions(FiniteTimeAction *actionOne, FiniteTimeAction return false; } + CCASSERT(actionOne != this, "actionOne should not be sequence self!"); + CCASSERT(actionTwo != this, "actionOne should not be sequence self!"); + float d = actionOne->getDuration() + actionTwo->getDuration(); ActionInterval::initWithDuration(d); diff --git a/native/cocos/2d/CCNode.cpp b/native/cocos/2d/CCNode.cpp index b252cad3f5..d90f11025f 100644 --- a/native/cocos/2d/CCNode.cpp +++ b/native/cocos/2d/CCNode.cpp @@ -693,11 +693,8 @@ void Node::setGLProgram(GLProgram* glProgram) { if (_glProgramState == nullptr || (_glProgramState && _glProgramState->getGLProgram() != glProgram)) { - CC_SAFE_RELEASE(_glProgramState); - _glProgramState = GLProgramState::getOrCreateWithGLProgram(glProgram); - _glProgramState->retain(); - - _glProgramState->setNodeBinding(this); + auto glProgramState = GLProgramState::getOrCreateWithGLProgram(glProgram); + setGLProgramState(glProgramState); } } diff --git a/native/cocos/2d/CCNode.h b/native/cocos/2d/CCNode.h index c396000608..c811ee4347 100644 --- a/native/cocos/2d/CCNode.h +++ b/native/cocos/2d/CCNode.h @@ -985,7 +985,7 @@ public: * Since v2.0, each rendering node must set its shader program. * It should be set in initialize phase. @code - node->setGLrProgram(GLProgramCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR)); + node->setGLProgram(GLProgramCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR)); @endcode * * @param glprogram The shader program. diff --git a/native/cocos/renderer/CCGLProgramCache.cpp b/native/cocos/renderer/CCGLProgramCache.cpp index 261f79ae30..fd3e3f371d 100644 --- a/native/cocos/renderer/CCGLProgramCache.cpp +++ b/native/cocos/renderer/CCGLProgramCache.cpp @@ -37,6 +37,11 @@ THE SOFTWARE. NS_CC_BEGIN +namespace { + GLProgramCache::GLProgramLifeCycleHook __glProgramCreateHook = nullptr; + GLProgramCache::GLProgramLifeCycleHook __glProgramDestroyHook = nullptr; +} + enum { kShaderType_PositionTextureColor, kShaderType_PositionTextureColor_noMVP, @@ -76,6 +81,8 @@ GLProgramCache* GLProgramCache::getInstance() void GLProgramCache::destroyInstance() { + if (_sharedGLProgramCache != nullptr) + _sharedGLProgramCache->cleanup(); CC_SAFE_RELEASE_NULL(_sharedGLProgramCache); } @@ -87,11 +94,8 @@ GLProgramCache::GLProgramCache() GLProgramCache::~GLProgramCache() { - for( auto it = _programs.begin(); it != _programs.end(); ++it ) { - (it->second)->release(); - } - CCLOGINFO("deallocing GLProgramCache: %p", this); + cleanup(); } bool GLProgramCache::init() @@ -107,6 +111,18 @@ bool GLProgramCache::init() return true; } +void GLProgramCache::cleanup() +{ + for(auto& e : _programs) + { + if (__glProgramDestroyHook != nullptr) + __glProgramDestroyHook(this, e.second); + + e.second->release(); + } + _programs.clear(); +} + void GLProgramCache::loadDefaultGLPrograms() { // Position Texture Color shader @@ -408,11 +424,18 @@ void GLProgramCache::addGLProgram(GLProgram* program, const std::string &key) if( prev == program ) return; + if (__glProgramDestroyHook != nullptr) + __glProgramDestroyHook(this, prev); + _programs.erase(key); CC_SAFE_RELEASE_NULL(prev); if (program) program->retain(); + + if (__glProgramCreateHook != nullptr) + __glProgramCreateHook(this, program); + _programs[key] = program; } @@ -430,4 +453,25 @@ std::string GLProgramCache::getShaderMacrosForLight() const return std::string(def); } +/* static */ +void GLProgramCache::setGLProgramCreateHook(GLProgramLifeCycleHook hook) +{ + __glProgramCreateHook = hook; +} + +/* static */ +void GLProgramCache::setGLProgramDestroyHook(GLProgramLifeCycleHook hook) +{ + __glProgramDestroyHook = hook; +} + +void GLProgramCache::notifyAllGLProgramsCreated() +{ + if (__glProgramCreateHook != nullptr) + { + for (const auto& e : _programs) + __glProgramCreateHook(this, e.second); + } +} + NS_CC_END diff --git a/native/cocos/renderer/CCGLProgramCache.h b/native/cocos/renderer/CCGLProgramCache.h index f0089688ed..804dea8cf1 100644 --- a/native/cocos/renderer/CCGLProgramCache.h +++ b/native/cocos/renderer/CCGLProgramCache.h @@ -84,12 +84,20 @@ public: /** reload default programs these are relative to light */ void reloadDefaultGLProgramsRelativeToLights(); + using GLProgramLifeCycleHook = void (*)(GLProgramCache*, GLProgram*); + static void setGLProgramCreateHook(GLProgramLifeCycleHook hook); + static void setGLProgramDestroyHook(GLProgramLifeCycleHook hook); + + void notifyAllGLProgramsCreated(); + private: /** @{ Init and load predefined shaders. */ bool init(); + void cleanup(); + void loadDefaultGLProgram(GLProgram *program, int type); /** @} diff --git a/native/cocos/renderer/CCGLProgramStateCache.cpp b/native/cocos/renderer/CCGLProgramStateCache.cpp index d6731b3b66..3b4716a0a9 100644 --- a/native/cocos/renderer/CCGLProgramStateCache.cpp +++ b/native/cocos/renderer/CCGLProgramStateCache.cpp @@ -27,9 +27,13 @@ THE SOFTWARE. #include "renderer/CCGLProgramState.h" #include "renderer/CCGLProgram.h" - NS_CC_BEGIN +namespace { + GLProgramStateCache::GLProgramStateLifeCycleHook __glProgramStateCreateHook = nullptr; + GLProgramStateCache::GLProgramStateLifeCycleHook __glProgramStateDestroyHook = nullptr; +} + GLProgramStateCache* GLProgramStateCache::s_instance = nullptr; GLProgramStateCache::GLProgramStateCache() @@ -38,7 +42,7 @@ GLProgramStateCache::GLProgramStateCache() GLProgramStateCache::~GLProgramStateCache() { - _glProgramStates.clear(); + removeAllGLProgramState(); } GLProgramStateCache* GLProgramStateCache::getInstance() @@ -65,6 +69,10 @@ GLProgramState* GLProgramStateCache::getGLProgramState(GLProgram* glprogram) auto ret = new (std::nothrow) GLProgramState; if(ret && ret->init(glprogram)) { _glProgramStates.insert(glprogram, ret); + + if (__glProgramStateCreateHook != nullptr) + __glProgramStateCreateHook(this, ret); + ret->release(); return ret; } @@ -80,6 +88,8 @@ void GLProgramStateCache::removeUnusedGLProgramState() if( value->getReferenceCount() == 1 ) { CCLOG("cocos2d: GLProgramStateCache: removing unused GLProgramState"); + if (__glProgramStateDestroyHook != nullptr) + __glProgramStateDestroyHook(this, value); //value->release(); it = _glProgramStates.erase(it); } else { @@ -90,8 +100,26 @@ void GLProgramStateCache::removeUnusedGLProgramState() void GLProgramStateCache::removeAllGLProgramState() { + if (__glProgramStateDestroyHook != nullptr) + { + for (const auto& e : _glProgramStates) + __glProgramStateDestroyHook(this, e.second); + } + _glProgramStates.clear(); } +/* static */ +void GLProgramStateCache::setGLProgramStateCreateHook(GLProgramStateLifeCycleHook hook) +{ + __glProgramStateCreateHook = hook; +} + +/* static */ +void GLProgramStateCache::setGLProgramStateDestroyHook(GLProgramStateLifeCycleHook hook) +{ + __glProgramStateDestroyHook = hook; +} + NS_CC_END diff --git a/native/cocos/renderer/CCGLProgramStateCache.h b/native/cocos/renderer/CCGLProgramStateCache.h index f23098ed3d..51e0e7beee 100644 --- a/native/cocos/renderer/CCGLProgramStateCache.h +++ b/native/cocos/renderer/CCGLProgramStateCache.h @@ -62,6 +62,10 @@ public: /**Remove unused GLProgramState.*/ void removeUnusedGLProgramState(); + using GLProgramStateLifeCycleHook = void (*)(GLProgramStateCache*, GLProgramState*); + static void setGLProgramStateCreateHook(GLProgramStateLifeCycleHook hook); + static void setGLProgramStateDestroyHook(GLProgramStateLifeCycleHook hook); + protected: GLProgramStateCache(); ~GLProgramStateCache(); diff --git a/native/cocos/renderer/CCTextureCache.cpp b/native/cocos/renderer/CCTextureCache.cpp index a9e1a745f2..92f7320635 100644 --- a/native/cocos/renderer/CCTextureCache.cpp +++ b/native/cocos/renderer/CCTextureCache.cpp @@ -41,12 +41,15 @@ THE SOFTWARE. #include "base/ccUtils.h" #include "base/CCNinePatchImageParser.h" - - using namespace std; NS_CC_BEGIN +namespace { + TextureCache::TextureLifeCycleHook __textureCreateHook = nullptr; + TextureCache::TextureLifeCycleHook __textureDestroyHook = nullptr; +} + // implementation TextureCache TextureCache* TextureCache::getInstance() @@ -56,8 +59,6 @@ TextureCache* TextureCache::getInstance() TextureCache::TextureCache() : _loadingThread(nullptr) -, _textureCreateHook(nullptr) -, _textureDestroyHook(nullptr) , _asyncRefCount(0) , _needQuit(false) { @@ -301,8 +302,8 @@ void TextureCache::addImageAsyncCallBack(float dt) texture->autorelease(); - if (_textureCreateHook != nullptr) - _textureCreateHook(this, texture); + if (__textureCreateHook != nullptr) + __textureCreateHook(this, texture); } else { texture = nullptr; CCLOG("cocos2d: failed to call TextureCache::addImageAsync(%s)", asyncStruct->filename.c_str()); @@ -365,8 +366,8 @@ Texture2D * TextureCache::addImage(const std::string &path) // texture already retained, no need to re-retain it _textures.insert( std::make_pair(fullpath, texture) ); - if (_textureCreateHook != nullptr) - _textureCreateHook(this, texture); + if (__textureCreateHook != nullptr) + __textureCreateHook(this, texture); //parse 9-patch info this->parseNinePatchImage(image, texture, path); @@ -419,8 +420,8 @@ Texture2D* TextureCache::addImage(Image *image, const std::string &key) texture->autorelease(); - if (_textureCreateHook != nullptr) - _textureCreateHook(this, texture); + if (__textureCreateHook != nullptr) + __textureCreateHook(this, texture); } else { @@ -494,8 +495,8 @@ cocos2d::Vector TextureCache::getAllTextures() const void TextureCache::removeAllTextures() { for( auto it=_textures.begin(); it!=_textures.end(); ++it ) { - if (_textureDestroyHook != nullptr) - _textureDestroyHook(this, it->second); + if (__textureDestroyHook != nullptr) + __textureDestroyHook(this, it->second); (it->second)->release(); } @@ -508,8 +509,8 @@ void TextureCache::removeUnusedTextures() Texture2D *tex = it->second; if( tex->getReferenceCount() == 1 ) { CCLOG("cocos2d: TextureCache: removing unused texture: %s", it->first.c_str()); - if (_textureDestroyHook != nullptr) - _textureDestroyHook(this, tex); + if (__textureDestroyHook != nullptr) + __textureDestroyHook(this, tex); tex->release(); it = _textures.erase(it); @@ -530,8 +531,8 @@ void TextureCache::removeTexture(Texture2D* texture) for( auto it=_textures.cbegin(); it!=_textures.cend(); /* nothing */ ) { if( it->second == texture ) { - if (_textureDestroyHook != nullptr) - _textureDestroyHook(this, texture); + if (__textureDestroyHook != nullptr) + __textureDestroyHook(this, texture); it->second->release(); it = _textures.erase(it); @@ -553,8 +554,8 @@ void TextureCache::removeTextureForKey(const std::string &textureKeyName) } if( it != _textures.end() ) { - if (_textureDestroyHook != nullptr) - _textureDestroyHook(this, it->second); + if (__textureDestroyHook != nullptr) + __textureDestroyHook(this, it->second); (it->second)->release(); _textures.erase(it); @@ -679,14 +680,16 @@ void TextureCache::renameTextureWithKey(const std::string& srcName, const std::s } } +/* static */ void TextureCache::setTextureCreateHook(TextureLifeCycleHook hook) { - _textureCreateHook = hook; + __textureCreateHook = hook; } +/* static */ void TextureCache::setTextureDestroyHook(TextureLifeCycleHook hook) { - _textureDestroyHook = hook; + __textureDestroyHook = hook; } #if CC_ENABLE_CACHE_TEXTURE_DATA diff --git a/native/cocos/renderer/CCTextureCache.h b/native/cocos/renderer/CCTextureCache.h index 73885d3050..84b5f8ecde 100644 --- a/native/cocos/renderer/CCTextureCache.h +++ b/native/cocos/renderer/CCTextureCache.h @@ -213,8 +213,8 @@ public: void renameTextureWithKey(const std::string& srcName, const std::string& dstName); using TextureLifeCycleHook = void (*)(TextureCache*, Texture2D*); - void setTextureCreateHook(TextureLifeCycleHook hook); - void setTextureDestroyHook(TextureLifeCycleHook hook); + static void setTextureCreateHook(TextureLifeCycleHook hook); + static void setTextureDestroyHook(TextureLifeCycleHook hook); private: void addImageAsyncCallBack(float dt); @@ -236,9 +236,6 @@ protected: std::thread* _loadingThread; - TextureLifeCycleHook _textureCreateHook; - TextureLifeCycleHook _textureDestroyHook; - int _asyncRefCount; bool _needQuit; }; diff --git a/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_auto_api.js b/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_auto_api.js index 0b7681716f..d6014e5657 100644 --- a/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_auto_api.js +++ b/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_auto_api.js @@ -14227,6 +14227,14 @@ GLProgram : function ( */ cc.ShaderCache = { +/** + * @method notifyAllGLProgramsCreated + */ +notifyAllGLProgramsCreated : function ( +) +{ +}, + /** * @method loadDefaultGLPrograms */ diff --git a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp index dcb3e49438..30805c884b 100644 --- a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp +++ b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp @@ -32612,6 +32612,21 @@ bool js_register_cocos2dx_GLProgram(se::Object* obj) se::Object* __jsb_cocos2d_GLProgramCache_proto = nullptr; se::Class* __jsb_cocos2d_GLProgramCache_class = nullptr; +static bool js_cocos2dx_GLProgramCache_notifyAllGLProgramsCreated(se::State& s) +{ + cocos2d::GLProgramCache* cobj = (cocos2d::GLProgramCache*)s.nativeThisObject(); + SE_PRECONDITION2(cobj, false, "js_cocos2dx_GLProgramCache_notifyAllGLProgramsCreated : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + if (argc == 0) { + cobj->notifyAllGLProgramsCreated(); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_cocos2dx_GLProgramCache_notifyAllGLProgramsCreated) + static bool js_cocos2dx_GLProgramCache_loadDefaultGLPrograms(se::State& s) { cocos2d::GLProgramCache* cobj = (cocos2d::GLProgramCache*)s.nativeThisObject(); @@ -32759,6 +32774,7 @@ bool js_register_cocos2dx_GLProgramCache(se::Object* obj) { auto cls = se::Class::create("ShaderCache", obj, nullptr, _SE(js_cocos2dx_GLProgramCache_constructor)); + cls->defineFunction("notifyAllGLProgramsCreated", _SE(js_cocos2dx_GLProgramCache_notifyAllGLProgramsCreated)); cls->defineFunction("loadDefaultShaders", _SE(js_cocos2dx_GLProgramCache_loadDefaultGLPrograms)); cls->defineFunction("reloadDefaultGLProgramsRelativeToLights", _SE(js_cocos2dx_GLProgramCache_reloadDefaultGLProgramsRelativeToLights)); cls->defineFunction("addProgram", _SE(js_cocos2dx_GLProgramCache_addGLProgram)); diff --git a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp index e712e7bce4..f288adfbd1 100644 --- a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp +++ b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp @@ -2128,6 +2128,7 @@ extern se::Class* __jsb_cocos2d_GLProgramCache_class; bool js_register_cocos2d_GLProgramCache(se::Object* obj); bool register_all_cocos2dx(se::Object* obj); +SE_DECLARE_FUNC(js_cocos2dx_GLProgramCache_notifyAllGLProgramsCreated); SE_DECLARE_FUNC(js_cocos2dx_GLProgramCache_loadDefaultGLPrograms); SE_DECLARE_FUNC(js_cocos2dx_GLProgramCache_reloadDefaultGLProgramsRelativeToLights); SE_DECLARE_FUNC(js_cocos2dx_GLProgramCache_addGLProgram); diff --git a/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp b/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp index c25968699e..b557589cb8 100644 --- a/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp +++ b/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp @@ -59,29 +59,29 @@ void ScriptingCore::retainScriptObject(Ref* owner, Ref* target) return; } - se::ScriptEngine::getInstance()->clearException(); - se::AutoHandleScope hs; - - se::Value targetVal; - se::Object* targetObj = nullptr; + // NOTE: If target isn't created from JS, we should return directly here. + // When JS invokes getter method, we should hack the getter method to invoke jsb.registerNativeRef. + // For example, you could refer to jsb_cocos2d.js, there are some code like: + /* + cc.TMXLayer.prototype._getTileAt = cc.TMXLayer.prototype.getTileAt; + cc.TMXLayer.prototype.getTileAt = function(x, y){ + var pos = y !== undefined ? cc.p(x, y) : x; + var ret = this._getTileAt(pos); + jsb.registerNativeRef(this, ret); // Re-attach the target since ret is created in C++ and retainScriptObject failed. + return ret; + }; + */ auto iterTarget = se::NativePtrToObjectMap::find(target); if (iterTarget == se::NativePtrToObjectMap::end()) { - se::Class* cls = JSBClassType::findClass(target); - if (cls == nullptr) - return; - - targetObj = se::Object::createObjectWithClass(cls); - targetVal.setObject(targetObj, true); - targetObj->setPrivateData(target); - target->retain(); // Retain the native object to unify the logic in finalize method of js object. - } - else - { - targetObj = iterTarget->second; + return; } - iterOwner->second->attachObject(targetObj); + assert(!se::ScriptEngine::getInstance()->isGarbageCollecting()); + se::ScriptEngine::getInstance()->clearException(); + se::AutoHandleScope hs; + + iterOwner->second->attachObject(iterTarget->second); } void ScriptingCore::rootScriptObject(Ref* target) diff --git a/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp b/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp index cc831f18e9..2b8dc48073 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp @@ -18,6 +18,8 @@ #include "storage/local-storage/LocalStorage.h" #include "cocos2d.h" +#include "renderer/CCGLProgramStateCache.h" + using namespace cocos2d; static bool jsb_cocos2dx_empty_func(se::State& s) @@ -912,6 +914,89 @@ static void onTextureDestroy(TextureCache* cache, Texture2D* texture) } } +static void onGLProgramCreate(GLProgramCache* cache, GLProgram* program) +{ + se::AutoHandleScope hs; + auto iterOwner = se::NativePtrToObjectMap::find(cache); + if (iterOwner == se::NativePtrToObjectMap::end()) + { + assert(false); + return; + } + + se::Value val; + bool fromCache = false; + native_ptr_to_seval(program, __jsb_cocos2d_GLProgram_class, &val, &fromCache); + if (!fromCache && val.isObject()) + { + iterOwner->second->attachObject(val.toObject()); + } + else + { + assert(false); + } +} + +static void onGLProgramDestroy(GLProgramCache* cache, GLProgram* program) +{ + se::AutoHandleScope hs; + auto iterOwner = se::NativePtrToObjectMap::find(cache); + if (iterOwner == se::NativePtrToObjectMap::end()) + { + assert(false); + return; + } + + se::Value val; + bool fromCache = false; + native_ptr_to_seval(program, __jsb_cocos2d_GLProgram_class, &val, &fromCache); + if (fromCache && val.isObject()) + { + iterOwner->second->detachObject(val.toObject()); + } + else + { + assert(false); + } +} + +static void onGLProgramStateCreate(GLProgramStateCache* cache, GLProgramState* state) +{ + se::AutoHandleScope hs; + // NOTE: GLProgramStateCache is a private class in cocos2dx, it isn't included in cocos2d.h and also didn't expose to JS + // Since it's a singleton class, we could attach 'state' argument to global object instead. + se::Object* global = se::ScriptEngine::getInstance()->getGlobalObject(); + se::Value val; + bool fromCache = false; + native_ptr_to_seval(state, __jsb_cocos2d_GLProgramState_class, &val, &fromCache); + if (!fromCache && val.isObject()) + { + global->attachObject(val.toObject()); + } + else + { + assert(false); + } +} + +static void onGLProgramStateDestroy(GLProgramStateCache* cache, GLProgramState* state) +{ + se::AutoHandleScope hs; + // NOTE: 'state' argument is attached to global object, therefore we need to detach it from global object. + se::Object* global = se::ScriptEngine::getInstance()->getGlobalObject(); + se::Value val; + bool fromCache = false; + native_ptr_to_seval(state, __jsb_cocos2d_GLProgramState_class, &val, &fromCache); + if (fromCache && val.isObject()) + { + global->detachObject(val.toObject()); + } + else + { + assert(false); + } +} + static bool register_eventlistener(se::Object* obj) { se::Value v; @@ -943,12 +1028,6 @@ static bool register_eventlistener(se::Object* obj) assert(v.isObject()); v.toObject()->defineFunction("create", _SE(js_EventListenerCustom_create)); - Director::getInstance()->getEventDispatcher()->setBeforeDispatchEventHook(Event::Type::TOUCH, onBeforeDispatchTouchEvent); - Director::getInstance()->getEventDispatcher()->setAfterDispatchEventHook(Event::Type::TOUCH, onAfterDispatchTouchEvent); - - Director::getInstance()->getTextureCache()->setTextureCreateHook(onTextureCreate); - Director::getInstance()->getTextureCache()->setTextureDestroyHook(onTextureDestroy); - se::ScriptEngine::getInstance()->clearException(); return true; @@ -2001,6 +2080,19 @@ bool register_all_cocos2dx_manual(se::Object* obj) register_empty_retain_release(obj); register_texture2d_manual(obj); register_tilemap_manual(obj); + + Director::getInstance()->getEventDispatcher()->setBeforeDispatchEventHook(Event::Type::TOUCH, onBeforeDispatchTouchEvent); + Director::getInstance()->getEventDispatcher()->setAfterDispatchEventHook(Event::Type::TOUCH, onAfterDispatchTouchEvent); + + TextureCache::setTextureCreateHook(onTextureCreate); + TextureCache::setTextureDestroyHook(onTextureDestroy); + + GLProgramCache::setGLProgramCreateHook(onGLProgramCreate); + GLProgramCache::setGLProgramDestroyHook(onGLProgramDestroy); + + GLProgramStateCache::setGLProgramStateCreateHook(onGLProgramStateCreate); + GLProgramStateCache::setGLProgramStateDestroyHook(onGLProgramStateDestroy); + return true; } diff --git a/native/cocos/scripting/js-bindings/script/jsb_boot.js b/native/cocos/scripting/js-bindings/script/jsb_boot.js index 659c240420..7c34a15575 100755 --- a/native/cocos/scripting/js-bindings/script/jsb_boot.js +++ b/native/cocos/scripting/js-bindings/script/jsb_boot.js @@ -74,6 +74,13 @@ cc.view.getTargetDensityDPI = function() {return cc.macro.DENSITYDPI_DEVICE;}; cc.eventManager = cc.director.getEventDispatcher(); +cc.EventDispatcher.prototype._addCustomListener = cc.EventDispatcher.prototype.addCustomListener; +cc.EventDispatcher.prototype.addCustomListener = function(eventName, callback) { + var ret = this._addCustomListener(eventName, callback); + jsb.registerNativeRef(cc.eventManager, ret); + return ret; +}; + cc.eventManager._resizeListener = cc.eventManager.addCustomListener('window-resize', function () { cc.winSize = cc.director.getWinSize(); cc.visibleRect.init(); @@ -82,6 +89,9 @@ cc.eventManager._resizeListener = cc.eventManager.addCustomListener('window-resi cc.configuration = cc.Configuration.getInstance(); cc.textureCache = cc.director.getTextureCache(); cc.shaderCache = cc.ShaderCache.getInstance(); +// The first time we invoke cc.ShaderCache.getInstance, notifyAllGLProgramsCreated needs to be called. +// It should be invoked only once. +cc.shaderCache.notifyAllGLProgramsCreated(); cc.plistParser = cc.PlistParser.getInstance(); // File utils (Temporary, won't be accessible) diff --git a/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js b/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js index 9c8399488c..0653e5e22f 100644 --- a/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js +++ b/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js @@ -629,15 +629,45 @@ cc.TMXTiledMap.prototype.allLayers = function(){ length = locChildren.length; for(var i = 0; i< length; i++){ var layer = locChildren[i]; - if(layer && layer instanceof cc.TMXLayer) + if(layer && layer instanceof cc.TMXLayer) { + jsb.registerNativeRef(this, layer); retArr.push(layer); + } } return retArr; }; + +cc.TMXTiledMap.prototype._getLayer = cc.TMXTiledMap.prototype.getLayer; +cc.TMXTiledMap.prototype.getLayer = function(layerName) { + var ret = this._getLayer(layerName); + jsb.registerNativeRef(this, ret); + return ret; +}; + +cc.TMXTiledMap.prototype._getObjectGroup = cc.TMXTiledMap.prototype.getObjectGroup; +cc.TMXTiledMap.prototype.getObjectGroup = function(groupName) { + var ret = this._getObjectGroup(groupName); + jsb.registerNativeRef(this, ret); + return ret; +}; + +cc.TMXTiledMap.prototype._getObjectGroups = cc.TMXTiledMap.prototype.getObjectGroups; +cc.TMXTiledMap.prototype.getObjectGroups = function() { + var ret = this._getObjectGroups(); + if (ret && ret instanceof Array) { + for (var i = 0, len = ret.length; i < len; ++i) { + jsb.registerNativeRef(this, ret[i]); + } + } + return ret; +}; + cc.TMXLayer.prototype._getTileAt = cc.TMXLayer.prototype.getTileAt; cc.TMXLayer.prototype.getTileAt = function(x, y){ var pos = y !== undefined ? cc.p(x, y) : x; - return this._getTileAt(pos); + var ret = this._getTileAt(pos); + jsb.registerNativeRef(this, ret); + return ret; }; cc.TMXLayer.prototype._getTileGIDAt = cc.TMXLayer.prototype.getTileGIDAt; cc.TMXLayer.prototype.getTileGIDAt = function(x, y){ @@ -671,6 +701,31 @@ cc.TMXLayer.prototype.getPositonAt = function(x, y){ cc.TMXLayer.prototype.tileFlagsAt = cc.TMXLayer.prototype.getTileFlagsAt; +cc.TMXObjectGroup.prototype._getObject = cc.TMXObjectGroup.prototype.getObject; +cc.TMXObjectGroup.prototype.getObject = function(objectName) { + var ret = this._getObject(objectName); + jsb.registerNativeRef(this, ret); + return ret; +}; + +cc.TMXObjectGroup.prototype._getObjects = cc.TMXObjectGroup.prototype.getObjects; +cc.TMXObjectGroup.prototype.getObjects = function() { + var ret = this._getObjects(); + if (ret && ret instanceof Array) { + for (var i = 0, len = ret.length; i < len; ++i) { + jsb.registerNativeRef(this, ret[i]); + } + } + return ret; +}; + +cc.TMXObject.prototype._getNode = cc.TMXObject.prototype.getNode; +cc.TMXObject.prototype.getNode = function() { + var ret = this._getNode(); + jsb.registerNativeRef(this, ret); + return ret; +}; + // // setBlendFunc JS API Wrapper // From e033dc5509b326059c0dcd353d231028f049555c Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 23 Feb 2018 10:21:17 +0800 Subject: [PATCH 35/35] Fixes AnySDK framework crash after restarting game. (#1120) --- .../js-bindings/manualanysdkbindings.cpp | 19 +++++++++++++++++++ .../js-bindings/manualanysdkbindings.cpp | 19 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/native/extensions/anysdk/js-bindings/manualanysdkbindings.cpp b/native/extensions/anysdk/js-bindings/manualanysdkbindings.cpp index 6a1adae474..815b53ecb5 100644 --- a/native/extensions/anysdk/js-bindings/manualanysdkbindings.cpp +++ b/native/extensions/anysdk/js-bindings/manualanysdkbindings.cpp @@ -884,6 +884,15 @@ public: std_map.erase(iter); } } + + static void purge() + { + for (auto& e : std_map) + { + delete e.second; + } + std_map.clear(); + } private: se::Value _jsThis; se::Value _jsFunc; @@ -1614,6 +1623,16 @@ bool register_all_anysdk_manual(se::Object* obj) __jsb_anysdk_framework_ProtocolREC_proto->defineFunction("setResultListener", _SE(jsb_anysdk_framework_ProtocolREC_setResultListener)); __jsb_anysdk_framework_ProtocolREC_proto->defineFunction("removeListener", _SE(jsb_anysdk_framework_ProtocolREC_removeListener)); + se::ScriptEngine::getInstance()->addBeforeCleanupHook([](){ + ProtocolAdsResultListener::purge(); + ProtocolYAPResultListener::purge(); + ProtocolPushActionListener::purge(); + ProtocolUserActionListener::purge(); + ProtocolSocialListener::purge(); + ProtocolRECListener::purge(); + ProtocolCustomListener::purge(); + }); + se::ScriptEngine::getInstance()->clearException(); return true; } diff --git a/native/extensions/anysdk/platform/ios/appstore/js-bindings/manualanysdkbindings.cpp b/native/extensions/anysdk/platform/ios/appstore/js-bindings/manualanysdkbindings.cpp index 3efffd2b51..0fad0a1370 100644 --- a/native/extensions/anysdk/platform/ios/appstore/js-bindings/manualanysdkbindings.cpp +++ b/native/extensions/anysdk/platform/ios/appstore/js-bindings/manualanysdkbindings.cpp @@ -884,6 +884,15 @@ public: std_map.erase(iter); } } + + static void purge() + { + for (auto& e : std_map) + { + delete e.second; + } + std_map.clear(); + } private: se::Value _jsThis; se::Value _jsFunc; @@ -1614,6 +1623,16 @@ bool register_all_anysdk_manual(se::Object* obj) __jsb_anysdk_framework_ProtocolREC_proto->defineFunction("setResultListener", _SE(jsb_anysdk_framework_ProtocolREC_setResultListener)); __jsb_anysdk_framework_ProtocolREC_proto->defineFunction("removeListener", _SE(jsb_anysdk_framework_ProtocolREC_removeListener)); + se::ScriptEngine::getInstance()->addBeforeCleanupHook([](){ + ProtocolAdsResultListener::purge(); + ProtocolYAPResultListener::purge(); + ProtocolPushActionListener::purge(); + ProtocolUserActionListener::purge(); + ProtocolSocialListener::purge(); + ProtocolRECListener::purge(); + ProtocolCustomListener::purge(); + }); + se::ScriptEngine::getInstance()->clearException(); return true; }