From 87ca37f50f6f4d612aae19f3a94cf34d5ff9d5e4 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 18 May 2016 14:09:37 +0800 Subject: [PATCH] Add AssetsManagerEx to extension --- .../cocos2d_libs.xcodeproj/project.pbxproj | 56 + native/cocos/network/CCDownloader-apple.mm | 4 +- native/cocos/network/CCDownloader.cpp | 2 +- native/cocos/network/CCDownloader.h | 2 +- native/cocos/network/HttpClient-android.cpp | 2 +- native/cocos/network/HttpRequest.h | 8 +- .../jsb_cocos2dx_extension_manual.cpp | 8 + .../script/extension/jsb_cocos2d_extension.js | 40 + native/extensions/Android.mk | 4 + .../assets-manager/AssetsManagerEx.cpp | 998 ++++++++++++++++++ .../assets-manager/AssetsManagerEx.h | 275 +++++ .../assets-manager/CCEventAssetsManagerEx.cpp | 46 + .../assets-manager/CCEventAssetsManagerEx.h | 99 ++ .../CCEventListenerAssetsManagerEx.cpp | 98 ++ .../CCEventListenerAssetsManagerEx.h | 86 ++ native/extensions/assets-manager/Manifest.cpp | 511 +++++++++ native/extensions/assets-manager/Manifest.h | 232 ++++ native/extensions/cocos-ext.h | 4 + native/tools/tojs/cocos2dx_extension.ini | 13 +- 19 files changed, 2476 insertions(+), 12 deletions(-) create mode 100644 native/extensions/assets-manager/AssetsManagerEx.cpp create mode 100644 native/extensions/assets-manager/AssetsManagerEx.h create mode 100644 native/extensions/assets-manager/CCEventAssetsManagerEx.cpp create mode 100644 native/extensions/assets-manager/CCEventAssetsManagerEx.h create mode 100644 native/extensions/assets-manager/CCEventListenerAssetsManagerEx.cpp create mode 100644 native/extensions/assets-manager/CCEventListenerAssetsManagerEx.h create mode 100644 native/extensions/assets-manager/Manifest.cpp create mode 100644 native/extensions/assets-manager/Manifest.h diff --git a/native/build/cocos2d_libs.xcodeproj/project.pbxproj b/native/build/cocos2d_libs.xcodeproj/project.pbxproj index e99b24f711..a662db87ca 100644 --- a/native/build/cocos2d_libs.xcodeproj/project.pbxproj +++ b/native/build/cocos2d_libs.xcodeproj/project.pbxproj @@ -1409,6 +1409,22 @@ B63990CD1A490AFE00B07923 /* CCAsyncTaskPool.cpp in Sources */ = {isa = PBXBuildFile; fileRef = B63990CA1A490AFE00B07923 /* CCAsyncTaskPool.cpp */; }; B63990CE1A490AFE00B07923 /* CCAsyncTaskPool.h in Headers */ = {isa = PBXBuildFile; fileRef = B63990CB1A490AFE00B07923 /* CCAsyncTaskPool.h */; }; B63990CF1A490AFE00B07923 /* CCAsyncTaskPool.h in Headers */ = {isa = PBXBuildFile; fileRef = B63990CB1A490AFE00B07923 /* CCAsyncTaskPool.h */; }; + BA679B301CEC373000F875FA /* AssetsManagerEx.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BA679B281CEC373000F875FA /* AssetsManagerEx.cpp */; }; + BA679B311CEC373000F875FA /* AssetsManagerEx.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BA679B281CEC373000F875FA /* AssetsManagerEx.cpp */; }; + BA679B321CEC373000F875FA /* AssetsManagerEx.h in Headers */ = {isa = PBXBuildFile; fileRef = BA679B291CEC373000F875FA /* AssetsManagerEx.h */; }; + BA679B331CEC373000F875FA /* AssetsManagerEx.h in Headers */ = {isa = PBXBuildFile; fileRef = BA679B291CEC373000F875FA /* AssetsManagerEx.h */; }; + BA679B341CEC373000F875FA /* CCEventAssetsManagerEx.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BA679B2A1CEC373000F875FA /* CCEventAssetsManagerEx.cpp */; }; + BA679B351CEC373000F875FA /* CCEventAssetsManagerEx.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BA679B2A1CEC373000F875FA /* CCEventAssetsManagerEx.cpp */; }; + BA679B361CEC373000F875FA /* CCEventAssetsManagerEx.h in Headers */ = {isa = PBXBuildFile; fileRef = BA679B2B1CEC373000F875FA /* CCEventAssetsManagerEx.h */; }; + BA679B371CEC373000F875FA /* CCEventAssetsManagerEx.h in Headers */ = {isa = PBXBuildFile; fileRef = BA679B2B1CEC373000F875FA /* CCEventAssetsManagerEx.h */; }; + BA679B381CEC373000F875FA /* CCEventListenerAssetsManagerEx.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BA679B2C1CEC373000F875FA /* CCEventListenerAssetsManagerEx.cpp */; }; + BA679B391CEC373000F875FA /* CCEventListenerAssetsManagerEx.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BA679B2C1CEC373000F875FA /* CCEventListenerAssetsManagerEx.cpp */; }; + BA679B3A1CEC373000F875FA /* CCEventListenerAssetsManagerEx.h in Headers */ = {isa = PBXBuildFile; fileRef = BA679B2D1CEC373000F875FA /* CCEventListenerAssetsManagerEx.h */; }; + BA679B3B1CEC373000F875FA /* CCEventListenerAssetsManagerEx.h in Headers */ = {isa = PBXBuildFile; fileRef = BA679B2D1CEC373000F875FA /* CCEventListenerAssetsManagerEx.h */; }; + BA679B3C1CEC373000F875FA /* Manifest.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BA679B2E1CEC373000F875FA /* Manifest.cpp */; }; + BA679B3D1CEC373000F875FA /* Manifest.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BA679B2E1CEC373000F875FA /* Manifest.cpp */; }; + BA679B3E1CEC373000F875FA /* Manifest.h in Headers */ = {isa = PBXBuildFile; fileRef = BA679B2F1CEC373000F875FA /* Manifest.h */; }; + BA679B3F1CEC373000F875FA /* Manifest.h in Headers */ = {isa = PBXBuildFile; fileRef = BA679B2F1CEC373000F875FA /* Manifest.h */; }; C50306691B60B583001E6D43 /* CCBoneNode.cpp in Sources */ = {isa = PBXBuildFile; fileRef = C50306631B60B583001E6D43 /* CCBoneNode.cpp */; }; C503066A1B60B583001E6D43 /* CCBoneNode.h in Headers */ = {isa = PBXBuildFile; fileRef = C50306641B60B583001E6D43 /* CCBoneNode.h */; }; C503066B1B60B583001E6D43 /* CCSkeletonNode.cpp in Sources */ = {isa = PBXBuildFile; fileRef = C50306651B60B583001E6D43 /* CCSkeletonNode.cpp */; }; @@ -2232,6 +2248,14 @@ B5CE6DC71B3C05BA002B0419 /* UIRadioButton.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = UIRadioButton.h; sourceTree = ""; }; B63990CA1A490AFE00B07923 /* CCAsyncTaskPool.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = CCAsyncTaskPool.cpp; path = ../base/CCAsyncTaskPool.cpp; sourceTree = ""; }; B63990CB1A490AFE00B07923 /* CCAsyncTaskPool.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CCAsyncTaskPool.h; path = ../base/CCAsyncTaskPool.h; sourceTree = ""; }; + BA679B281CEC373000F875FA /* AssetsManagerEx.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = AssetsManagerEx.cpp; path = "assets-manager/AssetsManagerEx.cpp"; sourceTree = ""; }; + BA679B291CEC373000F875FA /* AssetsManagerEx.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AssetsManagerEx.h; path = "assets-manager/AssetsManagerEx.h"; sourceTree = ""; }; + BA679B2A1CEC373000F875FA /* CCEventAssetsManagerEx.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = CCEventAssetsManagerEx.cpp; path = "assets-manager/CCEventAssetsManagerEx.cpp"; sourceTree = ""; }; + BA679B2B1CEC373000F875FA /* CCEventAssetsManagerEx.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CCEventAssetsManagerEx.h; path = "assets-manager/CCEventAssetsManagerEx.h"; sourceTree = ""; }; + BA679B2C1CEC373000F875FA /* CCEventListenerAssetsManagerEx.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = CCEventListenerAssetsManagerEx.cpp; path = "assets-manager/CCEventListenerAssetsManagerEx.cpp"; sourceTree = ""; }; + BA679B2D1CEC373000F875FA /* CCEventListenerAssetsManagerEx.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CCEventListenerAssetsManagerEx.h; path = "assets-manager/CCEventListenerAssetsManagerEx.h"; sourceTree = ""; }; + BA679B2E1CEC373000F875FA /* Manifest.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = Manifest.cpp; path = "assets-manager/Manifest.cpp"; sourceTree = ""; }; + BA679B2F1CEC373000F875FA /* Manifest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Manifest.h; path = "assets-manager/Manifest.h"; sourceTree = ""; }; C50306631B60B583001E6D43 /* CCBoneNode.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCBoneNode.cpp; sourceTree = ""; }; C50306641B60B583001E6D43 /* CCBoneNode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCBoneNode.h; sourceTree = ""; }; C50306651B60B583001E6D43 /* CCSkeletonNode.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCSkeletonNode.cpp; sourceTree = ""; }; @@ -3138,6 +3162,7 @@ 46A167981807AF4D005B8026 /* extensions */ = { isa = PBXGroup; children = ( + BA679B271CEC371100F875FA /* assets-manager */, A60A9D5A1C200DD00070800A /* PhysicsSprite */, 46A167D21807AF4D005B8026 /* cocos-ext.h */, 46A168321807AF4E005B8026 /* ExtensionMacros.h */, @@ -3580,6 +3605,21 @@ name = Armature; sourceTree = ""; }; + BA679B271CEC371100F875FA /* assets-manager */ = { + isa = PBXGroup; + children = ( + BA679B281CEC373000F875FA /* AssetsManagerEx.cpp */, + BA679B291CEC373000F875FA /* AssetsManagerEx.h */, + BA679B2A1CEC373000F875FA /* CCEventAssetsManagerEx.cpp */, + BA679B2B1CEC373000F875FA /* CCEventAssetsManagerEx.h */, + BA679B2C1CEC373000F875FA /* CCEventListenerAssetsManagerEx.cpp */, + BA679B2D1CEC373000F875FA /* CCEventListenerAssetsManagerEx.h */, + BA679B2E1CEC373000F875FA /* Manifest.cpp */, + BA679B2F1CEC373000F875FA /* Manifest.h */, + ); + name = "assets-manager"; + sourceTree = ""; + }; C50306621B60B56C001E6D43 /* Skeleton */ = { isa = PBXGroup; children = ( @@ -3770,6 +3810,7 @@ B29A7E0F19EE1B7700872B35 /* SkeletonJson.h in Headers */, B29A7E2919EE1B7700872B35 /* SkeletonData.h in Headers */, 50ABBED11925AB6F00A911A9 /* TGAlib.h in Headers */, + BA679B321CEC373000F875FA /* AssetsManagerEx.h in Headers */, 1A57019F180BCB590088DEC7 /* CCFont.h in Headers */, 1A5701A3180BCB590088DEC7 /* CCFontAtlas.h in Headers */, 15AE18E919AAD35000C27E9E /* CCActionManagerEx.h in Headers */, @@ -3879,6 +3920,7 @@ 15AE190419AAD35000C27E9E /* CCComRender.h in Headers */, B29A7E1919EE1B7700872B35 /* Event.h in Headers */, 15AE18AA19AAD33D00C27E9E /* CocosBuilder.h in Headers */, + BA679B3A1CEC373000F875FA /* CCEventListenerAssetsManagerEx.h in Headers */, 50ABC0071926664800A911A9 /* CCApplicationProtocol.h in Headers */, B29A7E1D19EE1B7700872B35 /* PolygonBatch.h in Headers */, 50ABBD4E1925AB0000A911A9 /* MathUtil.h in Headers */, @@ -3906,6 +3948,7 @@ 15AE1B5C19AADA9900C27E9E /* UITextAtlas.h in Headers */, 1A5702FC180BCE750088DEC7 /* CCTMXXMLParser.h in Headers */, 15AE1B6019AADA9900C27E9E /* UITextField.h in Headers */, + BA679B3E1CEC373000F875FA /* Manifest.h in Headers */, 15AE1B5619AADA9900C27E9E /* UIScrollView.h in Headers */, ED3057891BEC773E0083C3ED /* tinyxml2.h in Headers */, 50ABBDBB1925AB4100A911A9 /* CCTextureAtlas.h in Headers */, @@ -3986,6 +4029,7 @@ A679D0F81C74BA3600620A6C /* CCArmatureAnimation.h in Headers */, 50ABBEBD1925AB6F00A911A9 /* ccUtils.h in Headers */, A0534A651B872FFD006B03E5 /* CCDownloader-apple.h in Headers */, + BA679B361CEC373000F875FA /* CCEventAssetsManagerEx.h in Headers */, 50ABC0231926664800A911A9 /* CCGLViewImpl-desktop.h in Headers */, A63CF0081CD9CF3500A6971D /* CCUIPasswordTextField.h in Headers */, 15AE188D19AAD33D00C27E9E /* CCLabelBMFontLoader.h in Headers */, @@ -4244,6 +4288,7 @@ 1A57020B180BCBDF0088DEC7 /* CCMotionStreak.h in Headers */, 15AE194619AAD35100C27E9E /* CCComAttribute.h in Headers */, 1A570213180BCBF40088DEC7 /* CCProgressTimer.h in Headers */, + BA679B331CEC373000F875FA /* AssetsManagerEx.h in Headers */, 1A570217180BCBF40088DEC7 /* CCRenderTexture.h in Headers */, 1A570224180BCC1A0088DEC7 /* CCParticleBatchNode.h in Headers */, B29A7E2019EE1B7700872B35 /* BoneData.h in Headers */, @@ -4305,11 +4350,13 @@ 1A5702FD180BCE750088DEC7 /* CCTMXXMLParser.h in Headers */, A679D1411C74C49B00620A6C /* CCBatchNode.h in Headers */, 15AE1B8D19AADA9A00C27E9E /* UIScale9Sprite.h in Headers */, + BA679B3B1CEC373000F875FA /* CCEventListenerAssetsManagerEx.h in Headers */, 15AE18AC19AAD33D00C27E9E /* CCBAnimationManager.h in Headers */, 292DB14219B4574100A80320 /* UIEditBoxImpl.h in Headers */, 1A570303180BCE890088DEC7 /* CCParallaxNode.h in Headers */, 50ABBE2A1925AB6F00A911A9 /* CCAutoreleasePool.h in Headers */, 1A57030F180BCF190088DEC7 /* CCComponent.h in Headers */, + BA679B371CEC373000F875FA /* CCEventAssetsManagerEx.h in Headers */, 85505F071B60E3BA003F2CD4 /* CCSkeletonNode.h in Headers */, 15AE18B019AAD33D00C27E9E /* CCBKeyframe.h in Headers */, 15AE18C419AAD33D00C27E9E /* CCLayerGradientLoader.h in Headers */, @@ -4394,6 +4441,7 @@ B29A7DEC19EE1B7700872B35 /* MeshAttachment.h in Headers */, 50ABBEAE1925AB6F00A911A9 /* ccTypes.h in Headers */, 15AE185819AAD31200C27E9E /* CDAudioManager.h in Headers */, + BA679B3F1CEC373000F875FA /* Manifest.h in Headers */, 15AE1BF819AAE01E00C27E9E /* CCControlStepper.h in Headers */, 50ABBE261925AB6F00A911A9 /* base64.h in Headers */, 15AE1BF619AAE01E00C27E9E /* CCControlSlider.h in Headers */, @@ -4574,6 +4622,7 @@ 15AE18A619AAD33D00C27E9E /* CCScrollViewLoader.cpp in Sources */, 50ABBE591925AB6F00A911A9 /* CCEventKeyboard.cpp in Sources */, B29A7DDF19EE1B7700872B35 /* IkConstraintData.c in Sources */, + BA679B381CEC373000F875FA /* CCEventListenerAssetsManagerEx.cpp in Sources */, 1A57007D180BC5A10088DEC7 /* CCActionInterval.cpp in Sources */, 15AE189F19AAD33D00C27E9E /* CCNodeLoaderLibrary.cpp in Sources */, 1A570081180BC5A10088DEC7 /* CCActionManager.cpp in Sources */, @@ -4637,6 +4686,7 @@ 1A5701C7180BCB5A0088DEC7 /* CCLabelTextFormatter.cpp in Sources */, 15AE18A819AAD33D00C27E9E /* CCSpriteLoader.cpp in Sources */, 50ABBE711925AB6F00A911A9 /* CCEventListenerMouse.cpp in Sources */, + BA679B341CEC373000F875FA /* CCEventAssetsManagerEx.cpp in Sources */, 1A5701DE180BCB8C0088DEC7 /* CCLayer.cpp in Sources */, 15AE1B5919AADA9900C27E9E /* UIText.cpp in Sources */, ED30577E1BEC76C90083C3ED /* ioapi_mem.cpp in Sources */, @@ -4741,6 +4791,7 @@ A679D1211C74BB3A00620A6C /* CCUtilMath.cpp in Sources */, 50ABBD931925AB4100A911A9 /* CCGLProgramState.cpp in Sources */, ED30579C1BEC77B70083C3ED /* ConvertUTFWrapper.cpp in Sources */, + BA679B301CEC373000F875FA /* AssetsManagerEx.cpp in Sources */, B29A7DCB19EE1B7700872B35 /* Skeleton.c in Sources */, 50ABBEB31925AB6F00A911A9 /* CCUserDefault-apple.mm in Sources */, 29394CF619B01DBA00D2DE1A /* UIWebViewImpl-ios.mm in Sources */, @@ -4815,6 +4866,7 @@ 50ABBE5D1925AB6F00A911A9 /* CCEventListener.cpp in Sources */, B29A7E2D19EE1B7700872B35 /* Slot.c in Sources */, B5CE6DC81B3C05BA002B0419 /* UIRadioButton.cpp in Sources */, + BA679B3C1CEC373000F875FA /* Manifest.cpp in Sources */, 4D76BE3A1A4AAF0A00102962 /* CCActionTimelineNode.cpp in Sources */, 50ABBD601925AB0000A911A9 /* Vec4.cpp in Sources */, 50ABC05F1926664800A911A9 /* CCApplication-mac.mm in Sources */, @@ -4888,6 +4940,7 @@ 15AE1BEF19AAE01E00C27E9E /* CCControlHuePicker.cpp in Sources */, 15AE197B19AAD35700C27E9E /* CCFrame.cpp in Sources */, B29A7E3E19EE1B7700872B35 /* AnimationState.c in Sources */, + BA679B391CEC373000F875FA /* CCEventListenerAssetsManagerEx.cpp in Sources */, 1A57006E180BC5A10088DEC7 /* CCActionEase.cpp in Sources */, 50ABBD8C1925AB4100A911A9 /* CCGLProgram.cpp in Sources */, 1A570072180BC5A10088DEC7 /* CCActionGrid.cpp in Sources */, @@ -4933,10 +4986,12 @@ 50ABBEC01925AB6F00A911A9 /* CCValue.cpp in Sources */, 50ABBD591925AB0000A911A9 /* Vec2.cpp in Sources */, 15AE192419AAD35100C27E9E /* CocoLoader.cpp in Sources */, + BA679B3D1CEC373000F875FA /* Manifest.cpp in Sources */, A679D1481C74C49B00620A6C /* CCDecorativeDisplay.cpp in Sources */, 85505F041B60E3AB003F2CD4 /* CCBoneNode.cpp in Sources */, 50ABBE421925AB6F00A911A9 /* CCDirector.cpp in Sources */, 15AE1C0319AAE01E00C27E9E /* CCTableView.cpp in Sources */, + BA679B311CEC373000F875FA /* AssetsManagerEx.cpp in Sources */, 1A57007E180BC5A10088DEC7 /* CCActionInterval.cpp in Sources */, 15AE1BF319AAE01E00C27E9E /* CCControlSaturationBrightnessPicker.cpp in Sources */, 1A570082180BC5A10088DEC7 /* CCActionManager.cpp in Sources */, @@ -4981,6 +5036,7 @@ 1A5701B6180BCB590088DEC7 /* CCFontFreeType.cpp in Sources */, 50ABBEAC1925AB6F00A911A9 /* ccTypes.cpp in Sources */, 15AE196A19AAD35100C27E9E /* DictionaryHelper.cpp in Sources */, + BA679B351CEC373000F875FA /* CCEventAssetsManagerEx.cpp in Sources */, 1A5701BA180BCB5A0088DEC7 /* CCLabel.cpp in Sources */, 15AE18AD19AAD33D00C27E9E /* CCBFileLoader.cpp in Sources */, B5CE6DC91B3C05BA002B0419 /* UIRadioButton.cpp in Sources */, diff --git a/native/cocos/network/CCDownloader-apple.mm b/native/cocos/network/CCDownloader-apple.mm index 5c77a55d79..0abd3ef6ba 100644 --- a/native/cocos/network/CCDownloader-apple.mm +++ b/native/cocos/network/CCDownloader-apple.mm @@ -553,7 +553,9 @@ namespace cocos2d { namespace network { if ('/' == [destPath characterAtIndex:0]) { - destURL = [NSURL fileURLWithPath:destPath]; + // absolute path, need add prefix + NSString *prefix = @"file://"; + destURL = [NSURL URLWithString:[prefix stringByAppendingString: destPath]]; break; } diff --git a/native/cocos/network/CCDownloader.cpp b/native/cocos/network/CCDownloader.cpp index 561077d60b..bce110f4b3 100644 --- a/native/cocos/network/CCDownloader.cpp +++ b/native/cocos/network/CCDownloader.cpp @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2013 cocos2d-x.org + Copyright (c) 2015-2016 cocos2d-x.org http://www.cocos2d-x.org diff --git a/native/cocos/network/CCDownloader.h b/native/cocos/network/CCDownloader.h index f105ce549d..41730421b8 100644 --- a/native/cocos/network/CCDownloader.h +++ b/native/cocos/network/CCDownloader.h @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2013 cocos2d-x.org + Copyright (c) 2015-2016 cocos2d-x.org http://www.cocos2d-x.org diff --git a/native/cocos/network/HttpClient-android.cpp b/native/cocos/network/HttpClient-android.cpp index e2712a008a..c3fb82394e 100644 --- a/native/cocos/network/HttpClient-android.cpp +++ b/native/cocos/network/HttpClient-android.cpp @@ -1,7 +1,7 @@ /**************************************************************************** Copyright (c) 2012 greathqy Copyright (c) 2012 cocos2d-x.org - Copyright (c) 2013-2014 Chukong Technologies Inc. + Copyright (c) 2013-2016 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/network/HttpRequest.h b/native/cocos/network/HttpRequest.h index 9190d43636..4687fa1028 100644 --- a/native/cocos/network/HttpRequest.h +++ b/native/cocos/network/HttpRequest.h @@ -328,10 +328,10 @@ public: * * @return std::vector the string vector of custom-defined headers. */ - inline std::vector getHeaders() const - { - return _headers; - } + inline std::vector getHeaders() const + { + return _headers; + } protected: // properties diff --git a/native/cocos/scripting/js-bindings/manual/extension/jsb_cocos2dx_extension_manual.cpp b/native/cocos/scripting/js-bindings/manual/extension/jsb_cocos2dx_extension_manual.cpp index 3af69c8174..e468dae708 100644 --- a/native/cocos/scripting/js-bindings/manual/extension/jsb_cocos2dx_extension_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/extension/jsb_cocos2dx_extension_manual.cpp @@ -872,6 +872,8 @@ bool js_load_remote_image(JSContext *cx, uint32_t argc, jsval *vp) extern JSObject* jsb_cocos2d_extension_ScrollView_prototype; extern JSObject* jsb_cocos2d_extension_TableView_prototype; extern JSObject* jsb_cocos2d_extension_Control_prototype; +extern JSObject* jsb_cocos2d_extension_AssetsManagerEx_prototype; +extern JSObject* jsb_cocos2d_extension_Manifest_prototype; void register_all_cocos2dx_extension_manual(JSContext* cx, JS::HandleObject global) { @@ -880,6 +882,12 @@ void register_all_cocos2dx_extension_manual(JSContext* cx, JS::HandleObject glob JS::RootedObject tmpObj(cx); get_or_create_js_obj(cx, global, "cc", &ccObj); + JS::RootedObject am(cx, jsb_cocos2d_extension_AssetsManagerEx_prototype); + JS_DefineFunction(cx, am, "retain", js_cocos2dx_retain, 0, JSPROP_ENUMERATE | JSPROP_PERMANENT); + JS_DefineFunction(cx, am, "release", js_cocos2dx_release, 0, JSPROP_ENUMERATE | JSPROP_PERMANENT); + JS::RootedObject manifest(cx, jsb_cocos2d_extension_Manifest_prototype); + JS_DefineFunction(cx, manifest, "retain", js_cocos2dx_retain, 0, JSPROP_ENUMERATE | JSPROP_PERMANENT); + JS_DefineFunction(cx, manifest, "release", js_cocos2dx_release, 0, JSPROP_ENUMERATE | JSPROP_PERMANENT); tmpObj.set(jsb_cocos2d_extension_ScrollView_prototype); JS_DefineFunction(cx, tmpObj, "setDelegate", js_cocos2dx_CCScrollView_setDelegate, 1, JSPROP_ENUMERATE | JSPROP_PERMANENT); JS::RootedObject tableview(cx, jsb_cocos2d_extension_TableView_prototype); diff --git a/native/cocos/scripting/js-bindings/script/extension/jsb_cocos2d_extension.js b/native/cocos/scripting/js-bindings/script/extension/jsb_cocos2d_extension.js index 3e038c088d..87dca831ee 100644 --- a/native/cocos/scripting/js-bindings/script/extension/jsb_cocos2d_extension.js +++ b/native/cocos/scripting/js-bindings/script/extension/jsb_cocos2d_extension.js @@ -20,6 +20,34 @@ * THE SOFTWARE. */ +/** + * @type {Object} + * @name jsb.AssetsManager + * jsb.AssetsManager is the native AssetsManager for your game resources or scripts. + * please refer to this document to know how to use it: http://www.cocos2d-x.org/docs/manual/framework/html5/v3/assets-manager/en + * Only available in JSB + */ +jsb.AssetsManager = cc.AssetsManager; +delete cc.AssetsManager; +/** + * @type {Object} + * @name jsb.EventListenerAssetsManager + * jsb.EventListenerAssetsManager is the native event listener for AssetsManager. + * please refer to this document to know how to use it: http://www.cocos2d-x.org/docs/manual/framework/html5/v3/assets-manager/en + * Only available in JSB + */ +jsb.EventListenerAssetsManager = cc.EventListenerAssetsManager; +delete cc.EventListenerAssetsManager; +/** + * @type {Object} + * @name jsb.EventAssetsManager + * jsb.EventAssetsManager is the native event for AssetsManager. + * please refer to this document to know how to use it: http://www.cocos2d-x.org/docs/manual/framework/html5/v3/assets-manager/en + * Only available in JSB + */ +jsb.EventAssetsManager = cc.EventAssetsManager; +delete cc.EventAssetsManager; + // move from jsb_cocos2d //start------------------------------ cc.ControlButton.extend = cc.Class.extend; @@ -197,6 +225,18 @@ cc.AUTOREPEAT_DELTATIME = 0.15; cc.AUTOREPEAT_INCREASETIME_INCREMENT = 12; +jsb.EventAssetsManager.ERROR_NO_LOCAL_MANIFEST = 0; +jsb.EventAssetsManager.ERROR_DOWNLOAD_MANIFEST = 1; +jsb.EventAssetsManager.ERROR_PARSE_MANIFEST = 2; +jsb.EventAssetsManager.NEW_VERSION_FOUND = 3; +jsb.EventAssetsManager.ALREADY_UP_TO_DATE = 4; +jsb.EventAssetsManager.UPDATE_PROGRESSION = 5; +jsb.EventAssetsManager.ASSET_UPDATED = 6; +jsb.EventAssetsManager.ERROR_UPDATING = 7; +jsb.EventAssetsManager.UPDATE_FINISHED = 8; +jsb.EventAssetsManager.UPDATE_FAILED = 9; +jsb.EventAssetsManager.ERROR_DECOMPRESS = 10; + cc.ScrollView.extend = cc.Class.extend; cc.TableView.extend = cc.Class.extend; cc.TableViewCell.extend = cc.Class.extend; diff --git a/native/extensions/Android.mk b/native/extensions/Android.mk index 0cb02aa472..5207a25daa 100644 --- a/native/extensions/Android.mk +++ b/native/extensions/Android.mk @@ -10,6 +10,10 @@ LOCAL_ARM_MODE := arm endif LOCAL_SRC_FILES := \ +assets-manager/Manifest.cpp \ +assets-manager/AssetsManagerEx.cpp \ +assets-manager/CCEventAssetsManagerEx.cpp \ +assets-manager/CCEventListenerAssetsManagerEx.cpp \ GUI/CCControlExtension/CCControl.cpp \ GUI/CCControlExtension/CCControlButton.cpp \ GUI/CCControlExtension/CCControlColourPicker.cpp \ diff --git a/native/extensions/assets-manager/AssetsManagerEx.cpp b/native/extensions/assets-manager/AssetsManagerEx.cpp new file mode 100644 index 0000000000..7acf8570d2 --- /dev/null +++ b/native/extensions/assets-manager/AssetsManagerEx.cpp @@ -0,0 +1,998 @@ +/**************************************************************************** + Copyright (c) 2014 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ +#include "AssetsManagerEx.h" +#include "CCEventListenerAssetsManagerEx.h" +#include "base/CCString.h" +#include "base/CCDirector.h" + +#include + +#ifdef MINIZIP_FROM_SYSTEM +#include +#else // from our embedded sources +#include "unzip.h" +#endif +#include "base/CCAsyncTaskPool.h" + +using namespace cocos2d; +using namespace std; + +NS_CC_EXT_BEGIN + +#define VERSION_FILENAME "version.manifest" +#define TEMP_MANIFEST_FILENAME "project.manifest.temp" +#define MANIFEST_FILENAME "project.manifest" + +#define BUFFER_SIZE 8192 +#define MAX_FILENAME 512 + +#define DEFAULT_CONNECTION_TIMEOUT 8 + +const std::string AssetsManagerEx::VERSION_ID = "@version"; +const std::string AssetsManagerEx::MANIFEST_ID = "@manifest"; + +// Implementation of AssetsManagerEx + +AssetsManagerEx::AssetsManagerEx(const std::string& manifestUrl, const std::string& storagePath) +: _updateState(State::UNCHECKED) +, _assets(nullptr) +, _storagePath("") +, _cacheVersionPath("") +, _cacheManifestPath("") +, _tempManifestPath("") +, _manifestUrl(manifestUrl) +, _localManifest(nullptr) +, _tempManifest(nullptr) +, _remoteManifest(nullptr) +, _waitToUpdate(false) +, _percent(0) +, _percentByFile(0) +, _totalToDownload(0) +, _totalWaitToDownload(0) +, _inited(false) +{ + // Init variables + _eventDispatcher = Director::getInstance()->getEventDispatcher(); + std::string pointer = StringUtils::format("%p", this); + _eventName = EventListenerAssetsManagerEx::LISTENER_ID + pointer; + _fileUtils = FileUtils::getInstance(); + _updateState = State::UNCHECKED; + + _downloader = std::shared_ptr(new network::Downloader); +// _downloader->setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT); + _downloader->onTaskError = bind(&AssetsManagerEx::onError, this, placeholders::_1, placeholders::_2, placeholders::_3, placeholders::_4); + _downloader->onTaskProgress = [this](const network::DownloadTask& task, + int64_t bytesReceived, + int64_t totalBytesReceived, + int64_t totalBytesExpected) + { + this->onProgress(totalBytesExpected, totalBytesReceived, task.requestURL, task.identifier); + }; + _downloader->onFileTaskSuccess = [this](const network::DownloadTask& task) + { + this->onSuccess(task.requestURL, task.storagePath, task.identifier); + }; + setStoragePath(storagePath); + _cacheVersionPath = _storagePath + VERSION_FILENAME; + _cacheManifestPath = _storagePath + MANIFEST_FILENAME; + _tempManifestPath = _storagePath + TEMP_MANIFEST_FILENAME; + + initManifests(manifestUrl); +} + +AssetsManagerEx::~AssetsManagerEx() +{ + _downloader->onTaskError = (nullptr); + _downloader->onFileTaskSuccess = (nullptr); + _downloader->onTaskProgress = (nullptr); + CC_SAFE_RELEASE(_localManifest); + // _tempManifest could share a ptr with _remoteManifest or _localManifest + if (_tempManifest != _localManifest && _tempManifest != _remoteManifest) + CC_SAFE_RELEASE(_tempManifest); + CC_SAFE_RELEASE(_remoteManifest); +} + +AssetsManagerEx* AssetsManagerEx::create(const std::string& manifestUrl, const std::string& storagePath) +{ + AssetsManagerEx* ret = new (std::nothrow) AssetsManagerEx(manifestUrl, storagePath); + if (ret) + { + ret->autorelease(); + } + else + { + CC_SAFE_DELETE(ret); + } + return ret; +} + +void AssetsManagerEx::initManifests(const std::string& manifestUrl) +{ + _inited = true; + // Init and load local manifest + _localManifest = new (std::nothrow) Manifest(); + if (_localManifest) + { + loadLocalManifest(manifestUrl); + + // Init and load temporary manifest + _tempManifest = new (std::nothrow) Manifest(); + if (_tempManifest) + { + _tempManifest->parse(_tempManifestPath); + if (!_tempManifest->isLoaded() && _fileUtils->isFileExist(_tempManifestPath)) + _fileUtils->removeFile(_tempManifestPath); + } + else + { + _inited = false; + } + + // Init remote manifest for future usage + _remoteManifest = new (std::nothrow) Manifest(); + if (!_remoteManifest) + { + _inited = false; + } + } + else + { + _inited = false; + } + + if (!_inited) + { + CC_SAFE_DELETE(_localManifest); + CC_SAFE_DELETE(_tempManifest); + CC_SAFE_DELETE(_remoteManifest); + } +} + +void AssetsManagerEx::prepareLocalManifest() +{ + // An alias to assets + _assets = &(_localManifest->getAssets()); + + // Add search paths + _localManifest->prependSearchPaths(); +} + +void AssetsManagerEx::loadLocalManifest(const std::string& manifestUrl) +{ + Manifest *cachedManifest = nullptr; + // Find the cached manifest file + if (_fileUtils->isFileExist(_cacheManifestPath)) + { + cachedManifest = new (std::nothrow) Manifest(); + if (cachedManifest) { + cachedManifest->parse(_cacheManifestPath); + if (!cachedManifest->isLoaded()) + { + _fileUtils->removeFile(_cacheManifestPath); + CC_SAFE_RELEASE(cachedManifest); + cachedManifest = nullptr; + } + } + } + + // Load local manifest in app package + _localManifest->parse(_manifestUrl); + if (_localManifest->isLoaded()) + { + // Compare with cached manifest to determine which one to use + if (cachedManifest) { + if (strcmp(_localManifest->getVersion().c_str(), cachedManifest->getVersion().c_str()) > 0) + { + // Recreate storage, to empty the content + _fileUtils->removeDirectory(_storagePath); + _fileUtils->createDirectory(_storagePath); + CC_SAFE_RELEASE(cachedManifest); + } + else + { + CC_SAFE_RELEASE(_localManifest); + _localManifest = cachedManifest; + } + } + prepareLocalManifest(); + } + + // Fail to load local manifest + if (!_localManifest->isLoaded()) + { + CCLOG("AssetsManagerEx : No local manifest file found error.\n"); + dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ERROR_NO_LOCAL_MANIFEST); + } +} + +std::string AssetsManagerEx::basename(const std::string& path) const +{ + size_t found = path.find_last_of("/\\"); + + if (std::string::npos != found) + { + return path.substr(0, found); + } + else + { + return path; + } +} + +std::string AssetsManagerEx::get(const std::string& key) const +{ + auto it = _assets->find(key); + if (it != _assets->cend()) { + return _storagePath + it->second.path; + } + else return ""; +} + +const Manifest* AssetsManagerEx::getLocalManifest() const +{ + return _localManifest; +} + +const Manifest* AssetsManagerEx::getRemoteManifest() const +{ + return _remoteManifest; +} + +const std::string& AssetsManagerEx::getStoragePath() const +{ + return _storagePath; +} + +void AssetsManagerEx::setStoragePath(const std::string& storagePath) +{ + _storagePath = storagePath; + adjustPath(_storagePath); + _fileUtils->createDirectory(_storagePath); +} + +void AssetsManagerEx::adjustPath(std::string &path) +{ + if (path.size() > 0 && path[path.size() - 1] != '/') + { + path.append("/"); + } +} + +bool AssetsManagerEx::decompress(const std::string &zip) +{ + // Find root path for zip file + size_t pos = zip.find_last_of("/\\"); + if (pos == std::string::npos) + { + CCLOG("AssetsManagerEx : no root path specified for zip file %s\n", zip.c_str()); + return false; + } + const std::string rootPath = zip.substr(0, pos+1); + + // Open the zip file + unzFile zipfile = unzOpen(FileUtils::getInstance()->getSuitableFOpen(zip).c_str()); + if (! zipfile) + { + CCLOG("AssetsManagerEx : can not open downloaded zip file %s\n", zip.c_str()); + return false; + } + + // Get info about the zip file + unz_global_info global_info; + if (unzGetGlobalInfo(zipfile, &global_info) != UNZ_OK) + { + CCLOG("AssetsManagerEx : can not read file global info of %s\n", zip.c_str()); + unzClose(zipfile); + return false; + } + + // Buffer to hold data read from the zip file + char readBuffer[BUFFER_SIZE]; + // Loop to extract all files. + uLong i; + for (i = 0; i < global_info.number_entry; ++i) + { + // Get info about current file. + unz_file_info fileInfo; + char fileName[MAX_FILENAME]; + if (unzGetCurrentFileInfo(zipfile, + &fileInfo, + fileName, + MAX_FILENAME, + NULL, + 0, + NULL, + 0) != UNZ_OK) + { + CCLOG("AssetsManagerEx : can not read compressed file info\n"); + unzClose(zipfile); + return false; + } + const std::string fullPath = rootPath + fileName; + + // Check if this entry is a directory or a file. + const size_t filenameLength = strlen(fileName); + if (fileName[filenameLength-1] == '/') + { + //There are not directory entry in some case. + //So we need to create directory when decompressing file entry + if ( !_fileUtils->createDirectory(basename(fullPath)) ) + { + // Failed to create directory + CCLOG("AssetsManagerEx : can not create directory %s\n", fullPath.c_str()); + unzClose(zipfile); + return false; + } + } + else + { + // Entry is a file, so extract it. + // Open current file. + if (unzOpenCurrentFile(zipfile) != UNZ_OK) + { + CCLOG("AssetsManagerEx : can not extract file %s\n", fileName); + unzClose(zipfile); + return false; + } + + // Create a file to store current file. + FILE *out = fopen(FileUtils::getInstance()->getSuitableFOpen(fullPath).c_str(), "wb"); + if (!out) + { + CCLOG("AssetsManagerEx : can not create decompress destination file %s\n", fullPath.c_str()); + unzCloseCurrentFile(zipfile); + unzClose(zipfile); + return false; + } + + // Write current file content to destinate file. + int error = UNZ_OK; + do + { + error = unzReadCurrentFile(zipfile, readBuffer, BUFFER_SIZE); + if (error < 0) + { + CCLOG("AssetsManagerEx : can not read zip file %s, error code is %d\n", fileName, error); + fclose(out); + unzCloseCurrentFile(zipfile); + unzClose(zipfile); + return false; + } + + if (error > 0) + { + fwrite(readBuffer, error, 1, out); + } + } while(error > 0); + + fclose(out); + } + + unzCloseCurrentFile(zipfile); + + // Goto next entry listed in the zip file. + if ((i+1) < global_info.number_entry) + { + if (unzGoToNextFile(zipfile) != UNZ_OK) + { + CCLOG("AssetsManagerEx : can not read next file for decompressing\n"); + unzClose(zipfile); + return false; + } + } + } + + unzClose(zipfile); + return true; +} + +void AssetsManagerEx::decompressDownloadedZip() +{ + // Decompress all compressed files + for (auto it = _compressedFiles.begin(); it != _compressedFiles.end(); ++it) { + std::string zipfile = *it; + if (!decompress(zipfile)) + { + dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ERROR_DECOMPRESS, "", "Unable to decompress file " + zipfile); + } + _fileUtils->removeFile(zipfile); + } + _compressedFiles.clear(); +} + +void AssetsManagerEx::dispatchUpdateEvent(EventAssetsManagerEx::EventCode code, const std::string &assetId/* = ""*/, const std::string &message/* = ""*/, int curle_code/* = CURLE_OK*/, int curlm_code/* = CURLM_OK*/) +{ + EventAssetsManagerEx event(_eventName, this, code, _percent, _percentByFile, assetId, message, curle_code, curlm_code); + _eventDispatcher->dispatchEvent(&event); +} + +AssetsManagerEx::State AssetsManagerEx::getState() const +{ + return _updateState; +} + +void AssetsManagerEx::downloadVersion() +{ + if (_updateState > State::PREDOWNLOAD_VERSION) + return; + + std::string versionUrl = _localManifest->getVersionFileUrl(); + + if (versionUrl.size() > 0) + { + _updateState = State::DOWNLOADING_VERSION; + // Download version file asynchronously + _downloader->createDownloadFileTask(versionUrl, _cacheVersionPath, VERSION_ID); + } + // No version file found + else + { + CCLOG("AssetsManagerEx : No version file found, step skipped\n"); + _updateState = State::PREDOWNLOAD_MANIFEST; + downloadManifest(); + } +} + +void AssetsManagerEx::parseVersion() +{ + if (_updateState != State::VERSION_LOADED) + return; + + _remoteManifest->parseVersion(_cacheVersionPath); + + if (!_remoteManifest->isVersionLoaded()) + { + CCLOG("AssetsManagerEx : Fail to parse version file, step skipped\n"); + _updateState = State::PREDOWNLOAD_MANIFEST; + downloadManifest(); + } + else + { + if (_localManifest->versionEquals(_remoteManifest)) + { + _updateState = State::UP_TO_DATE; + dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ALREADY_UP_TO_DATE); + } + else + { + _updateState = State::NEED_UPDATE; + dispatchUpdateEvent(EventAssetsManagerEx::EventCode::NEW_VERSION_FOUND); + + // Wait to update so continue the process + if (_waitToUpdate) + { + _updateState = State::PREDOWNLOAD_MANIFEST; + downloadManifest(); + } + } + } +} + +void AssetsManagerEx::downloadManifest() +{ + if (_updateState != State::PREDOWNLOAD_MANIFEST) + return; + + std::string manifestUrl = _localManifest->getManifestFileUrl(); + if (manifestUrl.size() > 0) + { + _updateState = State::DOWNLOADING_MANIFEST; + // Download version file asynchronously + _downloader->createDownloadFileTask(manifestUrl, _tempManifestPath, MANIFEST_ID); + } + // No manifest file found + else + { + CCLOG("AssetsManagerEx : No manifest file found, check update failed\n"); + dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ERROR_DOWNLOAD_MANIFEST); + _updateState = State::UNCHECKED; + } +} + +void AssetsManagerEx::parseManifest() +{ + if (_updateState != State::MANIFEST_LOADED) + return; + + _remoteManifest->parse(_tempManifestPath); + + if (!_remoteManifest->isLoaded()) + { + CCLOG("AssetsManagerEx : Error parsing manifest file\n"); + dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ERROR_PARSE_MANIFEST); + _updateState = State::UNCHECKED; + } + else + { + if (_localManifest->versionEquals(_remoteManifest)) + { + _updateState = State::UP_TO_DATE; + dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ALREADY_UP_TO_DATE); + } + else + { + _updateState = State::NEED_UPDATE; + dispatchUpdateEvent(EventAssetsManagerEx::EventCode::NEW_VERSION_FOUND); + + if (_waitToUpdate) + { + startUpdate(); + } + } + } +} + +void AssetsManagerEx::startUpdate() +{ + if (_updateState != State::NEED_UPDATE) + return; + + _updateState = State::UPDATING; + // Clean up before update + _failedUnits.clear(); + _downloadUnits.clear(); + _compressedFiles.clear(); + _totalWaitToDownload = _totalToDownload = 0; + _percent = _percentByFile = _sizeCollected = _totalSize = 0; + _downloadedSize.clear(); + _totalEnabled = false; + + // Temporary manifest exists, resuming previous download + if (_tempManifest->isLoaded() && _tempManifest->versionEquals(_remoteManifest)) + { + _tempManifest->genResumeAssetsList(&_downloadUnits); + _totalWaitToDownload = _totalToDownload = (int)_downloadUnits.size(); + this->batchDownload(); + + std::string msg = StringUtils::format("Resuming from previous unfinished update, %d files remains to be finished.", _totalToDownload); + dispatchUpdateEvent(EventAssetsManagerEx::EventCode::UPDATE_PROGRESSION, "", msg); + } + // Check difference + else + { + // Temporary manifest not exists or out of date, + // it will be used to register the download states of each asset, + // in this case, it equals remote manifest. + _tempManifest->release(); + _tempManifest = _remoteManifest; + + std::unordered_map diff_map = _localManifest->genDiff(_remoteManifest); + if (diff_map.size() == 0) + { + updateSucceed(); + } + else + { + // Generate download units for all assets that need to be updated or added + std::string packageUrl = _remoteManifest->getPackageUrl(); + for (auto it = diff_map.begin(); it != diff_map.end(); ++it) + { + Manifest::AssetDiff diff = it->second; + + if (diff.type == Manifest::DiffType::DELETED) + { + _fileUtils->removeFile(_storagePath + diff.asset.path); + } + else + { + std::string path = diff.asset.path; + // Create path + _fileUtils->createDirectory(basename(_storagePath + path)); + + DownloadUnit unit; + unit.customId = it->first; + unit.srcUrl = packageUrl + path; + unit.storagePath = _storagePath + path; + _downloadUnits.emplace(unit.customId, unit); + } + } + // Set other assets' downloadState to SUCCESSED + auto &assets = _remoteManifest->getAssets(); + for (auto it = assets.cbegin(); it != assets.cend(); ++it) + { + const std::string &key = it->first; + auto diffIt = diff_map.find(key); + if (diffIt == diff_map.end()) + { + _tempManifest->setAssetDownloadState(key, Manifest::DownloadState::SUCCESSED); + } + } + _totalWaitToDownload = _totalToDownload = (int)_downloadUnits.size(); + this->batchDownload(); + + std::string msg = StringUtils::format("Start to update %d files from remote package.", _totalToDownload); + dispatchUpdateEvent(EventAssetsManagerEx::EventCode::UPDATE_PROGRESSION, "", msg); + } + } + + _waitToUpdate = false; +} + +void AssetsManagerEx::updateSucceed() +{ + // Every thing is correctly downloaded, do the following + // 1. rename temporary manifest to valid manifest + _fileUtils->renameFile(_storagePath, TEMP_MANIFEST_FILENAME, MANIFEST_FILENAME); + // 2. swap the localManifest + if (_localManifest != nullptr) + _localManifest->release(); + _localManifest = _remoteManifest; + _remoteManifest = nullptr; + // 3. make local manifest take effect + prepareLocalManifest(); + + + _updateState = State::UNZIPPING; + // 4. decompress all compressed files + //decompressDownloadedZip(); + + struct AsyncData + { + std::vector compressedFiles; + std::string errorCompressedFile; + }; + + AsyncData* asyncData = new AsyncData; + asyncData->compressedFiles = _compressedFiles; + _compressedFiles.clear(); + + std::function mainThread = [this](void* param) { + AsyncData* asyncData = (AsyncData*)param; + if (asyncData->errorCompressedFile.empty()) + { + // 5. Set update state + _updateState = State::UP_TO_DATE; + // 6. Notify finished event + dispatchUpdateEvent(EventAssetsManagerEx::EventCode::UPDATE_FINISHED); + } + else + { + _updateState = State::FAIL_TO_UPDATE; + dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ERROR_DECOMPRESS, "", "Unable to decompress file " + asyncData->errorCompressedFile); + } + + delete asyncData; + }; + AsyncTaskPool::getInstance()->enqueue(AsyncTaskPool::TaskType::TASK_OTHER, mainThread, (void*)asyncData, [this, asyncData]() { + // Decompress all compressed files + for (auto& zipFile : asyncData->compressedFiles) { + if (!decompress(zipFile)) + { + asyncData->errorCompressedFile = zipFile; + break; + } + _fileUtils->removeFile(zipFile); + } + }); +} + +void AssetsManagerEx::checkUpdate() +{ + if (!_inited){ + CCLOG("AssetsManagerEx : Manifests uninited.\n"); + dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ERROR_NO_LOCAL_MANIFEST); + return; + } + if (!_localManifest->isLoaded()) + { + CCLOG("AssetsManagerEx : No local manifest file found error.\n"); + dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ERROR_NO_LOCAL_MANIFEST); + return; + } + + switch (_updateState) { + case State::UNCHECKED: + case State::PREDOWNLOAD_VERSION: + { + downloadVersion(); + } + break; + case State::UP_TO_DATE: + { + dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ALREADY_UP_TO_DATE); + } + break; + case State::FAIL_TO_UPDATE: + case State::NEED_UPDATE: + { + dispatchUpdateEvent(EventAssetsManagerEx::EventCode::NEW_VERSION_FOUND); + } + break; + default: + break; + } +} + +void AssetsManagerEx::update() +{ + if (!_inited){ + CCLOG("AssetsManagerEx : Manifests uninited.\n"); + dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ERROR_NO_LOCAL_MANIFEST); + return; + } + if (!_localManifest->isLoaded()) + { + CCLOG("AssetsManagerEx : No local manifest file found error.\n"); + dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ERROR_NO_LOCAL_MANIFEST); + return; + } + + _waitToUpdate = true; + + switch (_updateState) { + case State::UNCHECKED: + { + _updateState = State::PREDOWNLOAD_VERSION; + } + case State::PREDOWNLOAD_VERSION: + { + downloadVersion(); + } + break; + case State::VERSION_LOADED: + { + parseVersion(); + } + break; + case State::PREDOWNLOAD_MANIFEST: + { + downloadManifest(); + } + break; + case State::MANIFEST_LOADED: + { + parseManifest(); + } + break; + case State::FAIL_TO_UPDATE: + case State::NEED_UPDATE: + { + // Manifest not loaded yet + if (!_remoteManifest->isLoaded()) + { + _waitToUpdate = true; + _updateState = State::PREDOWNLOAD_MANIFEST; + downloadManifest(); + } + else + { + startUpdate(); + } + } + break; + case State::UP_TO_DATE: + case State::UPDATING: + case State::UNZIPPING: + _waitToUpdate = false; + break; + default: + break; + } +} + +void AssetsManagerEx::updateAssets(const DownloadUnits& assets) +{ + if (!_inited){ + CCLOG("AssetsManagerEx : Manifests uninited.\n"); + dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ERROR_NO_LOCAL_MANIFEST); + return; + } + + if (_updateState != State::UPDATING && _localManifest->isLoaded() && _remoteManifest->isLoaded()) + { + int size = (int)(assets.size()); + if (size > 0) + { + _updateState = State::UPDATING; + _downloadUnits.clear(); + _downloadUnits = assets; + this->batchDownload(); + } + else if (size == 0 && _totalWaitToDownload == 0) + { + updateSucceed(); + } + } +} + +const DownloadUnits& AssetsManagerEx::getFailedAssets() const +{ + return _failedUnits; +} + +void AssetsManagerEx::downloadFailedAssets() +{ + CCLOG("AssetsManagerEx : Start update %lu failed assets.\n", _failedUnits.size()); + updateAssets(_failedUnits); +} + + +void AssetsManagerEx::onError(const network::DownloadTask& task, + int errorCode, + int errorCodeInternal, + const std::string& errorStr) +{ + // Skip version error occurred + if (task.identifier == VERSION_ID) + { + CCLOG("AssetsManagerEx : Fail to download version file, step skipped\n"); + _updateState = State::PREDOWNLOAD_MANIFEST; + downloadManifest(); + } + else if (task.identifier == MANIFEST_ID) + { + dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ERROR_DOWNLOAD_MANIFEST, task.identifier, errorStr, errorCode, errorCodeInternal); + } + else + { + auto unitIt = _downloadUnits.find(task.identifier); + // Found unit and add it to failed units + if (unitIt != _downloadUnits.end()) + { + _totalWaitToDownload--; + + DownloadUnit unit = unitIt->second; + _failedUnits.emplace(unit.customId, unit); + } + dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ERROR_UPDATING, task.identifier, errorStr, errorCode, errorCodeInternal); + } +} + +void AssetsManagerEx::onProgress(double total, double downloaded, const std::string &url, const std::string &customId) +{ + if (customId == VERSION_ID || customId == MANIFEST_ID) + { + _percent = 100 * downloaded / total; + // Notify progression event + dispatchUpdateEvent(EventAssetsManagerEx::EventCode::UPDATE_PROGRESSION, customId); + return; + } + else + { + // Calcul total downloaded + bool found = false; + double totalDownloaded = 0; + for (auto it = _downloadedSize.begin(); it != _downloadedSize.end(); ++it) + { + if (it->first == customId) + { + it->second = downloaded; + found = true; + } + totalDownloaded += it->second; + } + // Collect information if not registed + if (!found) + { + // Set download state to DOWNLOADING, this will run only once in the download process + _tempManifest->setAssetDownloadState(customId, Manifest::DownloadState::DOWNLOADING); + // Register the download size information + _downloadedSize.emplace(customId, downloaded); + _totalSize += total; + _sizeCollected++; + // All collected, enable total size + if (_sizeCollected == _totalToDownload) + { + _totalEnabled = true; + } + } + + if (_totalEnabled && _updateState == State::UPDATING) + { + float currentPercent = 100 * totalDownloaded / _totalSize; + // Notify at integer level change + if ((int)currentPercent != (int)_percent) { + _percent = currentPercent; + // Notify progression event + dispatchUpdateEvent(EventAssetsManagerEx::EventCode::UPDATE_PROGRESSION, customId); + } + } + } +} + +void AssetsManagerEx::onSuccess(const std::string &srcUrl, const std::string &storagePath, const std::string &customId) +{ + if (customId == VERSION_ID) + { + _updateState = State::VERSION_LOADED; + parseVersion(); + } + else if (customId == MANIFEST_ID) + { + _updateState = State::MANIFEST_LOADED; + parseManifest(); + } + else + { + auto &assets = _remoteManifest->getAssets(); + auto assetIt = assets.find(customId); + if (assetIt != assets.end()) + { + // Set download state to SUCCESSED + _tempManifest->setAssetDownloadState(customId, Manifest::DownloadState::SUCCESSED); + + // Add file to need decompress list + if (assetIt->second.compressed) { + _compressedFiles.push_back(storagePath); + } + } + + auto unitIt = _downloadUnits.find(customId); + if (unitIt != _downloadUnits.end()) + { + // Reduce count only when unit found in _downloadUnits + _totalWaitToDownload--; + + _percentByFile = 100 * (float)(_totalToDownload - _totalWaitToDownload) / _totalToDownload; + // Notify progression event + dispatchUpdateEvent(EventAssetsManagerEx::EventCode::UPDATE_PROGRESSION, ""); + } + // Notify asset updated event + dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ASSET_UPDATED, customId); + + unitIt = _failedUnits.find(customId); + // Found unit and delete it + if (unitIt != _failedUnits.end()) + { + // Remove from failed units list + _failedUnits.erase(unitIt); + } + + if (_totalWaitToDownload <= 0) + { + // Finished with error check + if (_failedUnits.size() > 0) + { + // Save current download manifest information for resuming + _tempManifest->saveToFile(_tempManifestPath); + + decompressDownloadedZip(); + + _updateState = State::FAIL_TO_UPDATE; + dispatchUpdateEvent(EventAssetsManagerEx::EventCode::UPDATE_FAILED); + } + else + { + updateSucceed(); + } + } + } +} + +void AssetsManagerEx::destroyDownloadedVersion() +{ + _fileUtils->removeFile(_cacheVersionPath); + _fileUtils->removeFile(_cacheManifestPath); +} + +void AssetsManagerEx::batchDownload() +{ + for(auto iter : _downloadUnits) + { + DownloadUnit& unit = iter.second; + _downloader->createDownloadFileTask(unit.srcUrl, unit.storagePath, unit.customId); + } +} + +NS_CC_EXT_END diff --git a/native/extensions/assets-manager/AssetsManagerEx.h b/native/extensions/assets-manager/AssetsManagerEx.h new file mode 100644 index 0000000000..e7fa32291f --- /dev/null +++ b/native/extensions/assets-manager/AssetsManagerEx.h @@ -0,0 +1,275 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __AssetsManagerEx__ +#define __AssetsManagerEx__ + +#include +#include +#include + +#include "base/CCEventDispatcher.h" +#include "platform/CCFileUtils.h" +#include "network/CCDownloader.h" + +#include "CCEventAssetsManagerEx.h" + +#include "Manifest.h" +#include "extensions/ExtensionMacros.h" +#include "extensions/ExtensionExport.h" +#include "json/document.h" + + +NS_CC_EXT_BEGIN + +/** + * @brief This class is used to auto update resources, such as pictures or scripts. + */ +class CC_EX_DLL AssetsManagerEx : public Ref +{ +public: + + //! Update states + enum class State + { + UNCHECKED, + PREDOWNLOAD_VERSION, + DOWNLOADING_VERSION, + VERSION_LOADED, + PREDOWNLOAD_MANIFEST, + DOWNLOADING_MANIFEST, + MANIFEST_LOADED, + NEED_UPDATE, + UPDATING, + UNZIPPING, + UP_TO_DATE, + FAIL_TO_UPDATE + }; + + const static std::string VERSION_ID; + const static std::string MANIFEST_ID; + + /** @brief Create function for creating a new AssetsManagerEx + @param manifestUrl The url for the local manifest file + @param storagePath The storage path for downloaded assets + @warning The cached manifest in your storage path have higher priority and will be searched first, + only if it doesn't exist, AssetsManagerEx will use the given manifestUrl. + */ + static AssetsManagerEx* create(const std::string &manifestUrl, const std::string &storagePath); + + /** @brief Check out if there is a new version of manifest. + * You may use this method before updating, then let user determine whether + * he wants to update resources. + */ + void checkUpdate(); + + /** @brief Update with the current local manifest. + */ + void update(); + + /** @brief Reupdate all failed assets under the current AssetsManagerEx context + */ + void downloadFailedAssets(); + + /** @brief Gets the current update state. + */ + State getState() const; + + /** @brief Gets storage path. + */ + const std::string& getStoragePath() const; + + /** @brief Function for retrieve the local manifest object + */ + const Manifest* getLocalManifest() const; + + /** @brief Function for retrieve the remote manifest object + */ + const Manifest* getRemoteManifest() const; + +CC_CONSTRUCTOR_ACCESS: + + AssetsManagerEx(const std::string& manifestUrl, const std::string& storagePath); + + virtual ~AssetsManagerEx(); + +protected: + + std::string basename(const std::string& path) const; + + std::string get(const std::string& key) const; + + void initManifests(const std::string& manifestUrl); + + void loadLocalManifest(const std::string& manifestUrl); + + void prepareLocalManifest(); + + void setStoragePath(const std::string& storagePath); + + void adjustPath(std::string &path); + + void dispatchUpdateEvent(EventAssetsManagerEx::EventCode code, const std::string &message = "", const std::string &assetId = "", int curle_code = 0, int curlm_code = 0); + + void downloadVersion(); + void parseVersion(); + void downloadManifest(); + void parseManifest(); + void startUpdate(); + void updateSucceed(); + bool decompress(const std::string &filename); + void decompressDownloadedZip(); + + /** @brief Update a list of assets under the current AssetsManagerEx context + */ + void updateAssets(const DownloadUnits& assets); + + /** @brief Retrieve all failed assets during the last update + */ + const DownloadUnits& getFailedAssets() const; + + /** @brief Function for destroying the downloaded version file and manifest file + */ + void destroyDownloadedVersion(); + + /** @brief Call back function for error handling, + the error will then be reported to user's listener registed in addUpdateEventListener + @param error The error object contains ErrorCode, message, asset url, asset key + @warning AssetsManagerEx internal use only + * @js NA + * @lua NA + */ + virtual void onError(const network::DownloadTask& task, + int errorCode, + int errorCodeInternal, + const std::string& errorStr); + + /** @brief Call back function for recording downloading percent of the current asset, + the progression will then be reported to user's listener registed in addUpdateProgressEventListener + @param total Total size to download for this asset + @param downloaded Total size already downloaded for this asset + @param url The url of this asset + @param customId The key of this asset + @warning AssetsManagerEx internal use only + * @js NA + * @lua NA + */ + virtual void onProgress(double total, double downloaded, const std::string &url, const std::string &customId); + + /** @brief Call back function for success of the current asset + the success event will then be send to user's listener registed in addUpdateEventListener + @param srcUrl The url of this asset + @param customId The key of this asset + @warning AssetsManagerEx internal use only + * @js NA + * @lua NA + */ + virtual void onSuccess(const std::string &srcUrl, const std::string &storagePath, const std::string &customId); + +private: + void batchDownload(); + + //! The event of the current AssetsManagerEx in event dispatcher + std::string _eventName; + + //! Reference to the global event dispatcher + EventDispatcher *_eventDispatcher; + //! Reference to the global file utils + FileUtils *_fileUtils; + + //! State of update + State _updateState; + + //! Downloader + std::shared_ptr _downloader; + + //! The reference to the local assets + const std::unordered_map *_assets; + + //! The path to store downloaded resources. + std::string _storagePath; + + //! The local path of cached version file + std::string _cacheVersionPath; + + //! The local path of cached manifest file + std::string _cacheManifestPath; + + //! The local path of cached temporary manifest file + std::string _tempManifestPath; + + //! The path of local manifest file + std::string _manifestUrl; + + //! Local manifest + Manifest *_localManifest; + + //! Local temporary manifest for download resuming + Manifest *_tempManifest; + + //! Remote manifest + Manifest *_remoteManifest; + + //! Whether user have requested to update + bool _waitToUpdate; + + //! All assets unit to download + DownloadUnits _downloadUnits; + + //! All failed units + DownloadUnits _failedUnits; + + //! All files to be decompressed + std::vector _compressedFiles; + + //! Download percent + float _percent; + + //! Download percent by file + float _percentByFile; + + //! Indicate whether the total size should be enabled + int _totalEnabled; + + //! Indicate the number of file whose total size have been collected + int _sizeCollected; + + //! Total file size need to be downloaded (sum of all file) + double _totalSize; + + //! Downloaded size for each file + std::unordered_map _downloadedSize; + + //! Total number of assets to download + int _totalToDownload; + //! Total number of assets still waiting to be downloaded + int _totalWaitToDownload; + + //! Marker for whether the assets manager is inited + bool _inited; +}; + +NS_CC_EXT_END + +#endif /* defined(__AssetsManagerEx__) */ diff --git a/native/extensions/assets-manager/CCEventAssetsManagerEx.cpp b/native/extensions/assets-manager/CCEventAssetsManagerEx.cpp new file mode 100644 index 0000000000..7eea7d1300 --- /dev/null +++ b/native/extensions/assets-manager/CCEventAssetsManagerEx.cpp @@ -0,0 +1,46 @@ +/**************************************************************************** + Copyright (c) 2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "CCEventAssetsManagerEx.h" +#include "base/ccMacros.h" +#include +#include "AssetsManagerEx.h" + +NS_CC_EXT_BEGIN + +EventAssetsManagerEx::EventAssetsManagerEx(const std::string& eventName, cocos2d::extension::AssetsManagerEx *manager, const EventCode &code, float percent/* = 0 */, float percentByFile/* = 0*/, const std::string& assetId/* = "" */, const std::string& message/* = "" */, int curle_code/* = CURLE_OK*/, int curlm_code/* = CURLM_OK*/) +: EventCustom(eventName) +, _code(code) +, _manager(manager) +, _message(message) +, _assetId(assetId) +, _curle_code(curle_code) +, _curlm_code(curlm_code) +, _percent(percent) +, _percentByFile(percentByFile) +{ +} + + +NS_CC_EXT_END diff --git a/native/extensions/assets-manager/CCEventAssetsManagerEx.h b/native/extensions/assets-manager/CCEventAssetsManagerEx.h new file mode 100644 index 0000000000..a94b39b1e6 --- /dev/null +++ b/native/extensions/assets-manager/CCEventAssetsManagerEx.h @@ -0,0 +1,99 @@ +/**************************************************************************** + Copyright (c) 2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __cocos2d_libs__CCEventAssetsManagerEx__ +#define __cocos2d_libs__CCEventAssetsManagerEx__ + +#include "base/CCEvent.h" +#include "base/CCEventCustom.h" +#include "extensions/ExtensionMacros.h" +#include "extensions/ExtensionExport.h" + +NS_CC_EXT_BEGIN + +class AssetsManagerEx; + +class CC_EX_DLL EventAssetsManagerEx : public cocos2d::EventCustom +{ +public: + + friend class AssetsManagerEx; + + //! Update events code + enum class EventCode + { + ERROR_NO_LOCAL_MANIFEST, + ERROR_DOWNLOAD_MANIFEST, + ERROR_PARSE_MANIFEST, + NEW_VERSION_FOUND, + ALREADY_UP_TO_DATE, + UPDATE_PROGRESSION, + ASSET_UPDATED, + ERROR_UPDATING, + UPDATE_FINISHED, + UPDATE_FAILED, + ERROR_DECOMPRESS + }; + + inline EventCode getEventCode() const { return _code; }; + + inline int getCURLECode() const { return _curle_code; }; + + inline int getCURLMCode() const { return _curlm_code; }; + + inline std::string getMessage() const { return _message; }; + + inline std::string getAssetId() const { return _assetId; }; + + inline cocos2d::extension::AssetsManagerEx *getAssetsManagerEx() const { return _manager; }; + + inline float getPercent() const { return _percent; }; + + inline float getPercentByFile() const { return _percentByFile; }; + +CC_CONSTRUCTOR_ACCESS: + /** Constructor */ + EventAssetsManagerEx(const std::string& eventName, cocos2d::extension::AssetsManagerEx *manager, const EventCode &code, float percent = 0, float percentByFile = 0, const std::string& assetId = "", const std::string& message = "", int curle_code = 0, int curlm_code = 0); + +private: + EventCode _code; + + cocos2d::extension::AssetsManagerEx *_manager; + + std::string _message; + + std::string _assetId; + + int _curle_code; + + int _curlm_code; + + float _percent; + + float _percentByFile; +}; + +NS_CC_EXT_END + +#endif /* defined(__cocos2d_libs__CCEventAssetsManagerEx__) */ diff --git a/native/extensions/assets-manager/CCEventListenerAssetsManagerEx.cpp b/native/extensions/assets-manager/CCEventListenerAssetsManagerEx.cpp new file mode 100644 index 0000000000..20c034876c --- /dev/null +++ b/native/extensions/assets-manager/CCEventListenerAssetsManagerEx.cpp @@ -0,0 +1,98 @@ +/**************************************************************************** + Copyright (c) 2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "CCEventListenerAssetsManagerEx.h" +#include "CCEventAssetsManagerEx.h" +#include "AssetsManagerEx.h" +#include "cocos2d.h" + +NS_CC_EXT_BEGIN + +const std::string EventListenerAssetsManagerEx::LISTENER_ID = "__cc_assets_manager_"; + +EventListenerAssetsManagerEx::EventListenerAssetsManagerEx() +: _onAssetsManagerExEvent(nullptr) +, _AssetsManagerEx(nullptr) +{ +} + +EventListenerAssetsManagerEx* EventListenerAssetsManagerEx::create(cocos2d::extension::AssetsManagerEx *AssetsManagerEx, const std::function& callback) +{ + EventListenerAssetsManagerEx* ret = new (std::nothrow) EventListenerAssetsManagerEx(); + if (ret && ret->init(AssetsManagerEx, callback)) + { + ret->autorelease(); + } + else + { + CC_SAFE_DELETE(ret); + } + return ret; +} + +bool EventListenerAssetsManagerEx::init(const AssetsManagerEx *AssetsManagerEx, const std::function& callback) +{ + bool ret = false; + + _AssetsManagerEx = AssetsManagerEx; + _onAssetsManagerExEvent = callback; + + auto func = [this](EventCustom *event) -> void + { + EventAssetsManagerEx *eventAssetsManagerEx = dynamic_cast(event); + _onAssetsManagerExEvent(eventAssetsManagerEx); + }; + std::string pointer = StringUtils::format("%p", AssetsManagerEx); + if (EventListenerCustom::init(LISTENER_ID + pointer, func)) + { + ret = true; + } + return ret; +} + +EventListenerAssetsManagerEx* EventListenerAssetsManagerEx::clone() +{ + EventListenerAssetsManagerEx* ret = new (std::nothrow) EventListenerAssetsManagerEx(); + if (ret && ret->init(_AssetsManagerEx, _onAssetsManagerExEvent)) + { + ret->autorelease(); + } + else + { + CC_SAFE_DELETE(ret); + } + return ret; +} + +bool EventListenerAssetsManagerEx::checkAvailable() +{ + bool ret = false; + if (EventListener::checkAvailable() && _AssetsManagerEx != nullptr && _onAssetsManagerExEvent != nullptr) + { + ret = true; + } + return ret; +} + +NS_CC_EXT_END \ No newline at end of file diff --git a/native/extensions/assets-manager/CCEventListenerAssetsManagerEx.h b/native/extensions/assets-manager/CCEventListenerAssetsManagerEx.h new file mode 100644 index 0000000000..03693d49ee --- /dev/null +++ b/native/extensions/assets-manager/CCEventListenerAssetsManagerEx.h @@ -0,0 +1,86 @@ +/**************************************************************************** + Copyright (c) 2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __cocos2d_libs__CCEventListenerAssetsManagerEx__ +#define __cocos2d_libs__CCEventListenerAssetsManagerEx__ + +#include "base/CCEventListener.h" +#include "base/CCEventListenerCustom.h" +#include "extensions/ExtensionMacros.h" +#include "extensions/ExtensionExport.h" + +NS_CC_EXT_BEGIN + +class EventAssetsManagerEx; +class AssetsManagerEx; + +/** + * Usage: + * auto dispatcher = Director::getInstance()->getEventDispatcher(); + * auto manager = AssetsManagerEx::create(manifestUrl, storagePath); + * Adds a listener: + * + * auto callback = [](EventAssetsManagerEx* event){ do_some_thing(); }; + * auto listener = EventListenerAssetsManagerEx::create(manager, callback); + * dispatcher->addEventListenerWithSceneGraphPriority(listener, one_node); + * + * Removes a listener + * + * dispatcher->removeEventListener(listener); + */ +class CC_EX_DLL EventListenerAssetsManagerEx : public cocos2d::EventListenerCustom +{ +public: + friend class AssetsManagerEx; + + /** Creates an event listener with type and callback. + * @param eventType The type of the event. + * @param callback The callback function when the specified event was emitted. + */ + static EventListenerAssetsManagerEx* create(AssetsManagerEx *AssetsManagerEx, const std::function& callback); + + /// Overrides + virtual bool checkAvailable() override; + virtual EventListenerAssetsManagerEx* clone() override; + +CC_CONSTRUCTOR_ACCESS: + /** Constructor */ + EventListenerAssetsManagerEx(); + + /** Initializes event with type and callback function */ + bool init(const AssetsManagerEx *AssetsManagerEx, const std::function& callback); + +protected: + static const std::string LISTENER_ID; + + std::function _onAssetsManagerExEvent; + + const AssetsManagerEx *_AssetsManagerEx; + + //friend class luaEventListenerAssetsManagerEx; +}; + +NS_CC_EXT_END + +#endif /* defined(__cocos2d_libs__CCEventListenerAssetsManagerEx__) */ diff --git a/native/extensions/assets-manager/Manifest.cpp b/native/extensions/assets-manager/Manifest.cpp new file mode 100644 index 0000000000..492720c000 --- /dev/null +++ b/native/extensions/assets-manager/Manifest.cpp @@ -0,0 +1,511 @@ +/**************************************************************************** + Copyright (c) 2014 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "Manifest.h" +#include "json/filestream.h" +#include "json/prettywriter.h" +#include "json/stringbuffer.h" + +#include + +#define KEY_VERSION "version" +#define KEY_PACKAGE_URL "packageUrl" +#define KEY_MANIFEST_URL "remoteManifestUrl" +#define KEY_VERSION_URL "remoteVersionUrl" +#define KEY_GROUP_VERSIONS "groupVersions" +#define KEY_ENGINE_VERSION "engineVersion" +#define KEY_ASSETS "assets" +#define KEY_COMPRESSED_FILES "compressedFiles" +#define KEY_SEARCH_PATHS "searchPaths" + +#define KEY_PATH "path" +#define KEY_MD5 "md5" +#define KEY_GROUP "group" +#define KEY_COMPRESSED "compressed" +#define KEY_COMPRESSED_FILE "compressedFile" +#define KEY_DOWNLOAD_STATE "downloadState" + +NS_CC_EXT_BEGIN + +Manifest::Manifest(const std::string& manifestUrl/* = ""*/) +: _versionLoaded(false) +, _loaded(false) +, _manifestRoot("") +, _remoteManifestUrl("") +, _remoteVersionUrl("") +, _version("") +, _engineVer("") +{ + // Init variables + _fileUtils = FileUtils::getInstance(); + if (manifestUrl.size() > 0) + parse(manifestUrl); +} + +void Manifest::loadJson(const std::string& url) +{ + clear(); + std::string content; + if (_fileUtils->isFileExist(url)) + { + // Load file content + content = _fileUtils->getStringFromFile(url); + + if (content.size() == 0) + { + CCLOG("Fail to retrieve local file content: %s\n", url.c_str()); + } + else + { + // Parse file with rapid json + _json.Parse<0>(content.c_str()); + // Print error + if (_json.HasParseError()) { + size_t offset = _json.GetErrorOffset(); + if (offset > 0) + offset--; + std::string errorSnippet = content.substr(offset, 10); + CCLOG("File parse error %d at <%s>\n", _json.GetParseError(), errorSnippet.c_str()); + } + } + } +} + +void Manifest::parseVersion(const std::string& versionUrl) +{ + loadJson(versionUrl); + + if (_json.IsObject()) + { + loadVersion(_json); + } +} + +void Manifest::parse(const std::string& manifestUrl) +{ + loadJson(manifestUrl); + + if (_json.IsObject()) + { + // Register the local manifest root + size_t found = manifestUrl.find_last_of("/\\"); + if (found != std::string::npos) + { + _manifestRoot = manifestUrl.substr(0, found+1); + } + loadManifest(_json); + } +} + +bool Manifest::isVersionLoaded() const +{ + return _versionLoaded; +} +bool Manifest::isLoaded() const +{ + return _loaded; +} + +bool Manifest::versionEquals(const Manifest *b) const +{ + // Check manifest version + if (_version != b->getVersion()) + { + return false; + } + // Check group versions + else + { + std::vector bGroups = b->getGroups(); + std::unordered_map bGroupVer = b->getGroupVerions(); + // Check group size + if (bGroups.size() != _groups.size()) + return false; + + // Check groups version + for (unsigned int i = 0; i < _groups.size(); ++i) { + std::string gid =_groups[i]; + // Check group name + if (gid != bGroups[i]) + return false; + // Check group version + if (_groupVer.at(gid) != bGroupVer.at(gid)) + return false; + } + } + return true; +} + +std::unordered_map Manifest::genDiff(const Manifest *b) const +{ + std::unordered_map diff_map; + std::unordered_map bAssets = b->getAssets(); + + std::string key; + Asset valueA; + Asset valueB; + std::unordered_map::const_iterator valueIt, it; + for (it = _assets.begin(); it != _assets.end(); ++it) + { + key = it->first; + valueA = it->second; + + // Deleted + valueIt = bAssets.find(key); + if (valueIt == bAssets.cend()) { + AssetDiff diff; + diff.asset = valueA; + diff.type = DiffType::DELETED; + diff_map.emplace(key, diff); + continue; + } + + // Modified + valueB = valueIt->second; + if (valueA.md5 != valueB.md5) { + AssetDiff diff; + diff.asset = valueB; + diff.type = DiffType::MODIFIED; + diff_map.emplace(key, diff); + } + } + + for (it = bAssets.begin(); it != bAssets.end(); ++it) + { + key = it->first; + valueB = it->second; + + // Added + valueIt = _assets.find(key); + if (valueIt == _assets.cend()) { + AssetDiff diff; + diff.asset = valueB; + diff.type = DiffType::ADDED; + diff_map.emplace(key, diff); + } + } + + return diff_map; +} + +void Manifest::genResumeAssetsList(DownloadUnits *units) const +{ + for (auto it = _assets.begin(); it != _assets.end(); ++it) + { + Asset asset = it->second; + + if (asset.downloadState != DownloadState::SUCCESSED) + { + DownloadUnit unit; + unit.customId = it->first; + unit.srcUrl = _packageUrl + asset.path; + unit.storagePath = _manifestRoot + asset.path; + units->emplace(unit.customId, unit); + } + } +} + +std::vector Manifest::getSearchPaths() const +{ + std::vector searchPaths; + searchPaths.push_back(_manifestRoot); + + for (int i = (int)_searchPaths.size()-1; i >= 0; i--) + { + std::string path = _searchPaths[i]; + if (path.size() > 0 && path[path.size() - 1] != '/') + path.append("/"); + path = _manifestRoot + path; + searchPaths.push_back(path); + } + return searchPaths; +} + +void Manifest::prependSearchPaths() +{ + std::vector searchPaths = FileUtils::getInstance()->getSearchPaths(); + std::vector::iterator iter = searchPaths.begin(); + bool needChangeSearchPaths = false; + if (std::find(searchPaths.begin(), searchPaths.end(), _manifestRoot) == searchPaths.end()) + { + searchPaths.insert(iter, _manifestRoot); + needChangeSearchPaths = true; + } + + for (int i = (int)_searchPaths.size()-1; i >= 0; i--) + { + std::string path = _searchPaths[i]; + if (path.size() > 0 && path[path.size() - 1] != '/') + path.append("/"); + path = _manifestRoot + path; + iter = searchPaths.begin(); + searchPaths.insert(iter, path); + needChangeSearchPaths = true; + } + if (needChangeSearchPaths) + { + FileUtils::getInstance()->setSearchPaths(searchPaths); + } +} + + +const std::string& Manifest::getPackageUrl() const +{ + return _packageUrl; +} + +const std::string& Manifest::getManifestFileUrl() const +{ + return _remoteManifestUrl; +} + +const std::string& Manifest::getVersionFileUrl() const +{ + return _remoteVersionUrl; +} + +const std::string& Manifest::getVersion() const +{ + return _version; +} + +const std::vector& Manifest::getGroups() const +{ + return _groups; +} + +const std::unordered_map& Manifest::getGroupVerions() const +{ + return _groupVer; +} + +const std::string& Manifest::getGroupVersion(const std::string &group) const +{ + return _groupVer.at(group); +} + +const std::unordered_map& Manifest::getAssets() const +{ + return _assets; +} + +void Manifest::setAssetDownloadState(const std::string &key, const Manifest::DownloadState &state) +{ + auto valueIt = _assets.find(key); + if (valueIt != _assets.end()) + { + valueIt->second.downloadState = state; + + // Update json object + if(_json.IsObject()) + { + if ( _json.HasMember(KEY_ASSETS) ) + { + rapidjson::Value &assets = _json[KEY_ASSETS]; + if (assets.IsObject()) + { + for (rapidjson::Value::MemberIterator itr = assets.MemberBegin(); itr != assets.MemberEnd(); ++itr) + { + std::string jkey = itr->name.GetString(); + if (jkey == key) { + rapidjson::Value &entry = itr->value; + if (entry.HasMember(KEY_DOWNLOAD_STATE) && entry[KEY_DOWNLOAD_STATE].IsInt()) + { + entry[KEY_DOWNLOAD_STATE].SetInt((int) state); + } + else + { + entry.AddMember(KEY_DOWNLOAD_STATE, (int)state, _json.GetAllocator()); + } + } + } + } + } + } + } +} + +void Manifest::clear() +{ + if (_versionLoaded || _loaded) + { + _groups.clear(); + _groupVer.clear(); + + _remoteManifestUrl = ""; + _remoteVersionUrl = ""; + _version = ""; + _engineVer = ""; + + _versionLoaded = false; + } + + if (_loaded) + { + _assets.clear(); + _searchPaths.clear(); + _loaded = false; + } +} + +Manifest::Asset Manifest::parseAsset(const std::string &path, const rapidjson::Value &json) +{ + Asset asset; + asset.path = path; + + if ( json.HasMember(KEY_MD5) && json[KEY_MD5].IsString() ) + { + asset.md5 = json[KEY_MD5].GetString(); + } + else asset.md5 = ""; + + if ( json.HasMember(KEY_PATH) && json[KEY_PATH].IsString() ) + { + asset.path = json[KEY_PATH].GetString(); + } + + if ( json.HasMember(KEY_COMPRESSED) && json[KEY_COMPRESSED].IsBool() ) + { + asset.compressed = json[KEY_COMPRESSED].GetBool(); + } + else asset.compressed = false; + + if ( json.HasMember(KEY_DOWNLOAD_STATE) && json[KEY_DOWNLOAD_STATE].IsInt() ) + { + asset.downloadState = (DownloadState)(json[KEY_DOWNLOAD_STATE].GetInt()); + } + else asset.downloadState = DownloadState::UNSTARTED; + + return asset; +} + +void Manifest::loadVersion(const rapidjson::Document &json) +{ + // Retrieve remote manifest url + if ( json.HasMember(KEY_MANIFEST_URL) && json[KEY_MANIFEST_URL].IsString() ) + { + _remoteManifestUrl = json[KEY_MANIFEST_URL].GetString(); + } + + // Retrieve remote version url + if ( json.HasMember(KEY_VERSION_URL) && json[KEY_VERSION_URL].IsString() ) + { + _remoteVersionUrl = json[KEY_VERSION_URL].GetString(); + } + + // Retrieve local version + if ( json.HasMember(KEY_VERSION) && json[KEY_VERSION].IsString() ) + { + _version = json[KEY_VERSION].GetString(); + } + + // Retrieve local group version + if ( json.HasMember(KEY_GROUP_VERSIONS) ) + { + const rapidjson::Value& groupVers = json[KEY_GROUP_VERSIONS]; + if (groupVers.IsObject()) + { + for (rapidjson::Value::ConstMemberIterator itr = groupVers.MemberBegin(); itr != groupVers.MemberEnd(); ++itr) + { + std::string group = itr->name.GetString(); + std::string version = "0"; + if (itr->value.IsString()) + { + version = itr->value.GetString(); + } + _groups.push_back(group); + _groupVer.emplace(group, version); + } + } + } + + // Retrieve local engine version + if ( json.HasMember(KEY_ENGINE_VERSION) && json[KEY_ENGINE_VERSION].IsString() ) + { + _engineVer = json[KEY_ENGINE_VERSION].GetString(); + } + + _versionLoaded = true; +} + +void Manifest::loadManifest(const rapidjson::Document &json) +{ + loadVersion(json); + + // Retrieve package url + if ( json.HasMember(KEY_PACKAGE_URL) && json[KEY_PACKAGE_URL].IsString() ) + { + _packageUrl = json[KEY_PACKAGE_URL].GetString(); + // Append automatically "/" + if (_packageUrl.size() > 0 && _packageUrl[_packageUrl.size() - 1] != '/') + { + _packageUrl.append("/"); + } + } + + // Retrieve all assets + if ( json.HasMember(KEY_ASSETS) ) + { + const rapidjson::Value& assets = json[KEY_ASSETS]; + if (assets.IsObject()) + { + for (rapidjson::Value::ConstMemberIterator itr = assets.MemberBegin(); itr != assets.MemberEnd(); ++itr) + { + std::string key = itr->name.GetString(); + Asset asset = parseAsset(key, itr->value); + _assets.emplace(key, asset); + } + } + } + + // Retrieve all search paths + if ( json.HasMember(KEY_SEARCH_PATHS) ) + { + const rapidjson::Value& paths = json[KEY_SEARCH_PATHS]; + if (paths.IsArray()) + { + for (rapidjson::SizeType i = 0; i < paths.Size(); ++i) + { + if (paths[i].IsString()) { + _searchPaths.push_back(paths[i].GetString()); + } + } + } + } + + _loaded = true; +} + +void Manifest::saveToFile(const std::string &filepath) +{ + rapidjson::StringBuffer buffer; + rapidjson::PrettyWriter writer(buffer); + _json.Accept(writer); + + std::ofstream output(filepath, std::ofstream::out); + if(!output.bad()) + output << buffer.GetString() << std::endl; +} + +NS_CC_EXT_END diff --git a/native/extensions/assets-manager/Manifest.h b/native/extensions/assets-manager/Manifest.h new file mode 100644 index 0000000000..437ffbdb1e --- /dev/null +++ b/native/extensions/assets-manager/Manifest.h @@ -0,0 +1,232 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __Manifest__ +#define __Manifest__ + +#include +#include +#include + +#include "extensions/ExtensionMacros.h" +#include "extensions/ExtensionExport.h" +#include "network/CCDownloader.h" +#include "platform/CCFileUtils.h" + +#include "json/document.h" + +NS_CC_EXT_BEGIN + +struct DownloadUnit +{ + std::string srcUrl; + std::string storagePath; + std::string customId; +}; + +typedef std::unordered_map DownloadUnits; + +class CC_EX_DLL Manifest : public Ref +{ +public: + + friend class AssetsManagerEx; + + //! The type of difference + enum class DiffType { + ADDED, + DELETED, + MODIFIED + }; + + enum class DownloadState { + UNSTARTED, + DOWNLOADING, + SUCCESSED + }; + + //! Asset object + struct Asset { + std::string md5; + std::string path; + bool compressed; + DownloadState downloadState; + }; + + //! Object indicate the difference between two Assets + struct AssetDiff { + Asset asset; + DiffType type; + }; + + /** @brief Check whether the version informations have been fully loaded + */ + bool isVersionLoaded() const; + + /** @brief Check whether the manifest have been fully loaded + */ + bool isLoaded() const; + + /** @brief Gets remote package url. + */ + const std::string& getPackageUrl() const; + + /** @brief Gets remote manifest file url. + */ + const std::string& getManifestFileUrl() const; + + /** @brief Gets remote version file url. + */ + const std::string& getVersionFileUrl() const; + + /** @brief Gets manifest version. + */ + const std::string& getVersion() const; + + /** @brief Get the search paths list related to the Manifest. + */ + std::vector getSearchPaths() const; + +protected: + + /** @brief Constructor for Manifest class + * @param manifestUrl Url of the local manifest + */ + Manifest(const std::string& manifestUrl = ""); + + /** @brief Load the json file into local json object + * @param url Url of the json file + */ + void loadJson(const std::string& url); + + /** @brief Parse the version file information into this manifest + * @param versionUrl Url of the local version file + */ + void parseVersion(const std::string& versionUrl); + + /** @brief Parse the manifest file information into this manifest + * @param manifestUrl Url of the local manifest + */ + void parse(const std::string& manifestUrl); + + /** @brief Check whether the version of this manifest equals to another. + * @param b The other manifest + */ + bool versionEquals(const Manifest *b) const; + + /** @brief Generate difference between this Manifest and another. + * @param b The other manifest + */ + std::unordered_map genDiff(const Manifest *b) const; + + /** @brief Generate resuming download assets list + * @param units The download units reference to be modified by the generation result + */ + void genResumeAssetsList(DownloadUnits *units) const; + + /** @brief Prepend all search paths to the FileUtils. + */ + void prependSearchPaths(); + + void loadVersion(const rapidjson::Document &json); + + void loadManifest(const rapidjson::Document &json); + + void saveToFile(const std::string &filepath); + + Asset parseAsset(const std::string &path, const rapidjson::Value &json); + + void clear(); + + /** @brief Gets all groups. + */ + const std::vector& getGroups() const; + + /** @brief Gets all groups version. + */ + const std::unordered_map& getGroupVerions() const; + + /** @brief Gets version for the given group. + * @param group Key of the requested group + */ + const std::string& getGroupVersion(const std::string &group) const; + + /** + * @brief Gets assets. + * @lua NA + */ + const std::unordered_map& getAssets() const; + + /** @brief Set the download state for an asset + * @param key Key of the asset to set + * @param state The current download state of the asset + */ + void setAssetDownloadState(const std::string &key, const DownloadState &state); + +private: + + //! Indicate whether the version informations have been fully loaded + bool _versionLoaded; + + //! Indicate whether the manifest have been fully loaded + bool _loaded; + + //! Reference to the global file utils + FileUtils *_fileUtils; + + //! The local manifest root + std::string _manifestRoot; + + //! The remote package url + std::string _packageUrl; + + //! The remote path of manifest file + std::string _remoteManifestUrl; + + //! The remote path of version file [Optional] + std::string _remoteVersionUrl; + + //! The version of local manifest + std::string _version; + + //! All groups exist in manifest [Optional] + std::vector _groups; + + //! The versions of all local group [Optional] + std::unordered_map _groupVer; + + //! The version of local engine + std::string _engineVer; + + //! Full assets list + std::unordered_map _assets; + + //! All search paths + std::vector _searchPaths; + + rapidjson::Document _json; +}; + +NS_CC_EXT_END +#endif /* defined(__Manifest__) */ diff --git a/native/extensions/cocos-ext.h b/native/extensions/cocos-ext.h index aa18d5744c..e81e221125 100644 --- a/native/extensions/cocos-ext.h +++ b/native/extensions/cocos-ext.h @@ -3,6 +3,10 @@ #include "ExtensionMacros.h" +#include "assets-manager/AssetsManagerEx.h" +#include "assets-manager/CCEventAssetsManagerEx.h" +#include "assets-manager/CCEventListenerAssetsManagerEx.h" +#include "assets-manager/Manifest.h" #include "GUI/CCControlExtension/CCControlExtensions.h" #include "GUI/CCScrollView/CCScrollView.h" diff --git a/native/tools/tojs/cocos2dx_extension.ini b/native/tools/tojs/cocos2dx_extension.ini index 2745115269..acd2ad87d8 100644 --- a/native/tools/tojs/cocos2dx_extension.ini +++ b/native/tools/tojs/cocos2dx_extension.ini @@ -29,7 +29,7 @@ replace_headers = cocos-ext.h::extensions/cocos-ext.h # what classes to produce code for. You can use regular expressions here. When testing the regular # expression, it will be enclosed in "^$", like this: "^Menu*$". -classes = Control.* ControlButton.* ScrollView$ TableView$ TableViewCell$ +classes = AssetsManagerEx Manifest EventListenerAssetsManagerEx EventAssetsManagerEx Control.* ControlButton.* ScrollView$ TableView$ TableViewCell$ # what should we skip? in the format ClassName::[function function] # ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also @@ -46,13 +46,18 @@ skip = ScrollView::[(g|s)etDelegate$], Control::[removeHandleOfControlEvent addHandleOfControlEvent], ControlUtils::[*], ControlSwitchSprite::[*], + ActionManagerEx::[initWithDictionary], ActionNode::[initWithDictionary], ActionObject::[initWithDictionary], - Manifest::[getAssets]] + Manifest::[getAssets], + AssetsManagerEx::[getFailedAssets updateAssets], + EventListenerAssetsManagerEx::[create init] rename_functions = -rename_classes = +rename_classes = AssetsManagerEx::AssetsManager, + EventAssetsManagerEx::EventAssetsManager, + EventListenerAssetsManagerEx::EventListenerAssetsManager # for all class names, should we remove something when registering in the target VM? remove_prefix = @@ -65,7 +70,7 @@ base_classes_to_skip = Ref # classes that create no constructor # Set is special and we will use a hand-written constructor -abstract_classes = +abstract_classes = Manifest # Determining whether to use script object(js object) to control the lifecycle of native(cpp) object or the other way around. Supported values are 'yes' or 'no'. script_control_cpp = no