diff --git a/native/cocos/base/CCRef.cpp b/native/cocos/base/CCRef.cpp index aae113614f..c2a657f7dc 100644 --- a/native/cocos/base/CCRef.cpp +++ b/native/cocos/base/CCRef.cpp @@ -130,6 +130,14 @@ void Ref::release() CCASSERT(false, "The reference shouldn't be 0 because it is still in autorelease pool."); } #endif + +#if CC_ENABLE_SCRIPT_BINDING + ScriptEngineProtocol* pEngine = ScriptEngineManager::getInstance()->getScriptEngine(); + if (pEngine != nullptr && pEngine->getScriptType() == kScriptTypeJavascript) + { + pEngine->removeObjectProxy(this); + } +#endif // CC_ENABLE_SCRIPT_BINDING #if CC_REF_LEAK_DETECTION untrackRef(this); diff --git a/native/cocos/base/CCScriptSupport.h b/native/cocos/base/CCScriptSupport.h index 7929d0d513..4efa284d3b 100644 --- a/native/cocos/base/CCScriptSupport.h +++ b/native/cocos/base/CCScriptSupport.h @@ -798,6 +798,10 @@ public: It tells the Garbage Collector that the associated Scripting object can be collected */ virtual void unrootObject(Ref* obj) {} + + /** Remove proxy for a native object + */ + virtual void removeObjectProxy(Ref* obj) {} /** Triggers the garbage collector */ virtual void garbageCollect() {} diff --git a/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp b/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp index 81f9bc7933..2c98338346 100644 --- a/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp +++ b/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp @@ -1473,12 +1473,6 @@ bool ScriptingCore::handleTouchesEvent(void* nativeObj, cocos2d::EventTouch::Eve ret = executeFunctionWithOwner(OBJECT_TO_JSVAL(p->obj), funcName.c_str(), 2, dataVal, jsvalRet); } - for (auto& touch : touches) - { - removeJSObject(_cx, touch); - } - removeJSObject(_cx, event); - return ret; } @@ -1508,9 +1502,6 @@ bool ScriptingCore::handleTouchEvent(void* nativeObj, cocos2d::EventTouch::Event ret = executeFunctionWithOwner(OBJECT_TO_JSVAL(p->obj), funcName.c_str(), 2, dataVal, jsvalRet); } - removeJSObject(_cx, touch); - removeJSObject(_cx, event); - return ret; } @@ -1533,8 +1524,6 @@ bool ScriptingCore::handleMouseEvent(void* nativeObj, cocos2d::EventMouse::Mouse js_type_class_t *typeClass = js_get_type_from_native((cocos2d::EventMouse*)event); jsval dataVal = OBJECT_TO_JSVAL(jsb_get_or_create_weak_jsobject(_cx, event, typeClass)); ret = executeFunctionWithOwner(OBJECT_TO_JSVAL(p->obj), funcName.c_str(), 1, &dataVal, jsvalRet); - - removeJSObject(_cx, event); } else CCLOG("ScriptingCore::handleMouseEvent native proxy NOT found"); @@ -1639,8 +1628,6 @@ bool ScriptingCore::handleKeyboardEvent(void* nativeObj, cocos2d::EventKeyboard: ret = executeFunctionWithOwner(OBJECT_TO_JSVAL(p->obj), "_onKeyReleased", 2, args); } - removeJSObject(_cx, event); - return ret; } @@ -1689,11 +1676,6 @@ int ScriptingCore::executeCustomTouchesEvent(EventTouch::EventCode eventType, jsval jsretArrVal = OBJECT_TO_JSVAL(jsretArr); executeFunctionWithOwner(OBJECT_TO_JSVAL(obj), funcName.c_str(), 1, &jsretArrVal); - for (auto& touch : touches) - { - removeJSObject(this->_cx, touch); - } - return 1; } @@ -1710,8 +1692,6 @@ int ScriptingCore::executeCustomTouchEvent(EventTouch::EventCode eventType, Touc executeFunctionWithOwner(OBJECT_TO_JSVAL(obj), funcName.c_str(), 1, &jsTouch, &retval); - removeJSObject(this->_cx, touch); - return 1; } @@ -1729,8 +1709,6 @@ int ScriptingCore::executeCustomTouchEvent(EventTouch::EventCode eventType, executeFunctionWithOwner(OBJECT_TO_JSVAL(obj), funcName.c_str(), 1, &jsTouch, retval); - removeJSObject(this->_cx, touch); - return 1; } @@ -1845,6 +1823,21 @@ void ScriptingCore::unrootObject(Ref* ref) else CCLOG("unrootObject: BUG. native not found: %p (%s)", ref, typeid(*ref).name()); } +void ScriptingCore::removeObjectProxy(Ref* obj) +{ + auto proxy = jsb_get_native_proxy(obj); + if (proxy) + { +#if ! CC_ENABLE_GC_FOR_NATIVE_OBJECTS + JS::RemoveObjectRoot(_cx, &proxy->obj); +#endif + // remove the proxy here, since this was a "stack" object, not heap + // when js_finalize will be called, it will fail, but + // the correct solution is to have a new finalize for event + jsb_remove_proxy(proxy); + } +} + void ScriptingCore::garbageCollect() { #if CC_TARGET_PLATFORM != CC_PLATFORM_WIN32 diff --git a/native/cocos/scripting/js-bindings/manual/ScriptingCore.h b/native/cocos/scripting/js-bindings/manual/ScriptingCore.h index 103e37e4e8..60bf3db79e 100644 --- a/native/cocos/scripting/js-bindings/manual/ScriptingCore.h +++ b/native/cocos/scripting/js-bindings/manual/ScriptingCore.h @@ -532,6 +532,10 @@ public: * This function is only called when compiled with CC_ENABLE_GC_FOR_NATIVE_OBJECTS=1 */ virtual void unrootObject(cocos2d::Ref* ref) override; + + /** Remove proxy for a native object + */ + virtual void removeObjectProxy(cocos2d::Ref* obj) override; /** * Calls the Garbage Collector 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 42481cc81d..c40fc3caec 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 @@ -738,7 +738,6 @@ bool js_cocos2dx_extension_EventListenerAssetsManagerEx_init(JSContext *cx, uint if (!succeed && JS_IsExceptionPending(cx)) { JS_ReportPendingException(cx); } - removeJSObject(cx, larg0); }; arg1 = lambda; } @@ -798,7 +797,6 @@ bool js_cocos2dx_extension_EventListenerAssetsManagerEx_create(JSContext *cx, ui if (!succeed && JS_IsExceptionPending(cx)) { JS_ReportPendingException(cx); } - removeJSObject(cx, larg0); }; arg1 = lambda; } @@ -1056,7 +1054,7 @@ void register_all_cocos2dx_extension_manual(JSContext* cx, JS::HandleObject glob tmpObj.set(tmpVal.toObjectOrNull()); JS_DefineFunction(cx, tmpObj, "create", js_cocos2dx_CCTableView_create, 3, JSPROP_READONLY | JSPROP_PERMANENT); - JS_DefineFunction(cx, jsbObj, "loadRemoteImg", js_load_remote_image, 2, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, jsbObj, "__loadRemoteImg", js_load_remote_image, 2, JSPROP_READONLY | JSPROP_PERMANENT); JS::RootedObject performance(cx); get_or_create_js_obj(cx, global, "performance", &performance); diff --git a/native/cocos/scripting/js-bindings/manual/jsb_event_dispatcher_manual.cpp b/native/cocos/scripting/js-bindings/manual/jsb_event_dispatcher_manual.cpp index 8434745f0d..2618f363d0 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_event_dispatcher_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_event_dispatcher_manual.cpp @@ -194,7 +194,6 @@ bool js_EventListenerAcceleration_create(JSContext *cx, uint32_t argc, jsval *vp if (!succeed && JS_IsExceptionPending(cx)) { JS_ReportPendingException(cx); } - removeJSObject(cx, event); }; arg0 = lambda; } @@ -267,7 +266,6 @@ bool js_EventListenerCustom_create(JSContext *cx, uint32_t argc, jsval *vp) if (!succeed && JS_IsExceptionPending(cx)) { JS_ReportPendingException(cx); } - removeJSObject(cx, event); }; arg1 = lambda; } @@ -324,7 +322,6 @@ bool js_EventDispatcher_addCustomEventListener(JSContext *cx, uint32_t argc, jsv if (!succeed && JS_IsExceptionPending(cx)) { JS_ReportPendingException(cx); } - removeJSObject(cx, event); }; arg1 = lambda; } diff --git a/native/cocos/scripting/js-bindings/script/ccui/jsb_ccui_create_apis.js b/native/cocos/scripting/js-bindings/script/ccui/jsb_ccui_create_apis.js index 4ea82acdf7..1e5637ccbe 100644 --- a/native/cocos/scripting/js-bindings/script/ccui/jsb_ccui_create_apis.js +++ b/native/cocos/scripting/js-bindings/script/ccui/jsb_ccui_create_apis.js @@ -20,6 +20,8 @@ * THE SOFTWARE. */ +'use strict'; + ccui.Widget.prototype.init = ccui.Widget.prototype._init; ccui.RichText.prototype.init = function(){ ccui.Widget.prototype.init.call(this); diff --git a/native/cocos/scripting/js-bindings/script/ccui/jsb_cocos2d_ui.js b/native/cocos/scripting/js-bindings/script/ccui/jsb_cocos2d_ui.js index 96964aa385..420cdace0e 100644 --- a/native/cocos/scripting/js-bindings/script/ccui/jsb_cocos2d_ui.js +++ b/native/cocos/scripting/js-bindings/script/ccui/jsb_cocos2d_ui.js @@ -29,7 +29,6 @@ var ccui = ccui || {}; cc.EditBox = ccui.EditBox; -delete ccui.EditBox; cc.Scale9Sprite = ccui.Scale9Sprite; 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 8db738808e..9041c22fab 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,8 @@ * THE SOFTWARE. */ +'use strict'; + /** * @type {Object} * @name jsb.AssetsManager @@ -28,7 +30,6 @@ * Only available in JSB */ jsb.AssetsManager = cc.AssetsManager; -delete cc.AssetsManager; /** * @type {Object} * @name jsb.Manifest @@ -36,7 +37,6 @@ delete cc.AssetsManager; * Only available in JSB */ jsb.Manifest = cc.Manifest; -delete cc.Manifest; /** * @type {Object} * @name jsb.EventListenerAssetsManager @@ -45,7 +45,6 @@ delete cc.Manifest; * Only available in JSB */ jsb.EventListenerAssetsManager = cc.EventListenerAssetsManager; -delete cc.EventListenerAssetsManager; /** * @type {Object} * @name jsb.EventAssetsManager @@ -54,33 +53,28 @@ delete cc.EventListenerAssetsManager; * Only available in JSB */ jsb.EventAssetsManager = cc.EventAssetsManager; -delete cc.EventAssetsManager; -// move from jsb_cocos2d -//start------------------------------ -cc.ControlButton.extend = cc.Class.extend; -cc.ControlColourPicker.extend = cc.Class.extend; -cc.ControlPotentiometer.extend = cc.Class.extend; -cc.ControlSlider.extend = cc.Class.extend; -cc.ControlStepper.extend = cc.Class.extend; -cc.ControlSwitch.extend = cc.Class.extend; -//end------------------------------ +jsb.EventListenerAssetsManager.prototype._ctor = function(assetsManager, callback) { + callback !== undefined && this.init(assetsManager, callback); +}; -// -// cocos2d constants -// -// This helper file should be required after jsb_cocos2d.js -// - -var cc = cc || {}; - -cc.SCROLLVIEW_DIRECTION_NONE = -1; -cc.SCROLLVIEW_DIRECTION_HORIZONTAL = 0; -cc.SCROLLVIEW_DIRECTION_VERTICAL = 1; -cc.SCROLLVIEW_DIRECTION_BOTH = 2; -cc.TABLEVIEW_FILL_TOPDOWN = 0; -cc.TABLEVIEW_FILL_BOTTOMUP = 1; +jsb.Manifest.DownloadState = { + UNSTARTED: 0, + DOWNLOADING: 1, + SUCCESSED: 2 +}; +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; /** * @constant @@ -203,54 +197,3 @@ cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_SENTENCE = 3; */ cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_ALL_CHARACTERS = 4; -cc.CONTROL_EVENT_TOTAL_NUMBER = 9; - -cc.CONTROL_EVENT_TOUCH_DOWN = 1 << 0; // A touch-down event in the control. -cc.CONTROL_EVENT_TOUCH_DRAG_INSIDE = 1 << 1; // An event where a finger is dragged inside the bounds of the control. -cc.CONTROL_EVENT_TOUCH_DRAG_OUTSIDE = 1 << 2; // An event where a finger is dragged just outside the bounds of the control. -cc.CONTROL_EVENT_TOUCH_DRAG_ENTER = 1 << 3; // An event where a finger is dragged into the bounds of the control. -cc.CONTROL_EVENT_TOUCH_DRAG_EXIT = 1 << 4; // An event where a finger is dragged from within a control to outside its bounds. -cc.CONTROL_EVENT_TOUCH_UP_INSIDE = 1 << 5; // A touch-up event in the control where the finger is inside the bounds of the control. -cc.CONTROL_EVENT_TOUCH_UP_OUTSIDE = 1 << 6; // A touch-up event in the control where the finger is outside the bounds of the control. -cc.CONTROL_EVENT_TOUCH_CANCEL = 1 << 7; // A system event canceling the current touches for the control. -cc.CONTROL_EVENT_VALUECHANGED = 1 << 8; // A touch dragging or otherwise manipulating a control; causing it to emit a series of different values. - -cc.CONTROL_STATE_NORMAL = 1 << 0; // The normal; or default state of a control梩hat is; enabled but neither selected nor highlighted. -cc.CONTROL_STATE_HIGHLIGHTED = 1 << 1; // Highlighted state of a control. A control enters this state when a touch down; drag inside or drag enter is performed. You can retrieve and set this value through the highlighted property. -cc.CONTROL_STATE_DISABLED = 1 << 2; // Disabled state of a control. This state indicates that the control is currently disabled. You can retrieve and set this value through the enabled property. -cc.CONTROL_STATE_SELECTED = 1 << 3; // Selected state of a control. This state indicates that the control is currently selected. You can retrieve and set this value through the selected property. -cc.CONTROL_STATE_INITIAL = 1 << 3; - -cc.CONTROL_ZOOM_ACTION_TAG = 0xCCCB0001; //CCControlButton.js - -cc.CONTROL_STEPPER_PARTMINUS = 0; //CCControlStepper.js -cc.CONTROL_STEPPER_PARTPLUS = 1; -cc.CONTROL_STEPPER_PARTNONE = 2; -cc.CONTROL_STEPPER_LABELCOLOR_ENABLED = cc.color(55, 55, 55); -cc.CONTROL_STEPPER_LABELCOLOR_DISABLED = cc.color(147, 147, 147); -cc.CONTROL_STEPPER_LABELFONT = "CourierNewPSMT"; -cc.AUTOREPEAT_DELTATIME = 0.15; -cc.AUTOREPEAT_INCREASETIME_INCREMENT = 12; - -jsb.Manifest.DownloadState = { - UNSTARTED: 0, - DOWNLOADING: 1, - SUCCESSED: 2 -}; - -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/cocos/scripting/js-bindings/script/extension/jsb_ext_create_apis.js b/native/cocos/scripting/js-bindings/script/extension/jsb_ext_create_apis.js deleted file mode 100644 index ef89057b17..0000000000 --- a/native/cocos/scripting/js-bindings/script/extension/jsb_ext_create_apis.js +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2014-2016 Chukong Technologies Inc. - * - * 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. - */ - -'use strict'; - -/************************************************************ - * - * Constructors with built in init function - * - ************************************************************/ - -jsb.EventListenerAssetsManager.prototype._ctor = function(assetsManager, callback) { - callback !== undefined && this.init(assetsManager, callback); -}; - -cc.ControlButton.prototype._ctor = function(label, backgroundSprite, fontSize, fontName, autoSizeWithLabel ){ - if (autoSizeWithLabel !== undefined && backgroundSprite) { - this.initWithLabelAndBackgroundSprite(label, backgroundSprite, autoSizeWithLabel); - } - else if(fontName !== undefined && fontSize !== undefined) { - this.initWithTitleAndFontNameAndFontSize(label, fontName, fontSize); - } - else if(backgroundSprite !== undefined) { - this.initWithLabelAndBackgroundSprite(label, backgroundSprite, true); - } - else if(label !== undefined) { - this.initWithBackgroundSprite(label); - } - else { - this.init(); - } -}; - -cc.ControlColourPicker.prototype._ctor = function(){ - this.init(); -}; - -cc.ControlPotentiometer.prototype._ctor = function(backgroundFile, progressFile, thumbFile){ - if (thumbFile != undefined) { - // Prepare track for potentiometer - var backgroundSprite = cc.Sprite.create(backgroundFile); - - // Prepare thumb for potentiometer - var thumbSprite = cc.Sprite.create(thumbFile); - - // Prepare progress for potentiometer - var progressTimer = cc.ProgressTimer.create(cc.Sprite.create(progressFile)); - this.initWithTrackSprite_ProgressTimer_ThumbSprite(backgroundSprite, progressTimer, thumbSprite); - } -}; - -cc.ControlSlider.prototype._ctor = function(bgFile, progressFile, thumbFile){ - if (thumbFile != undefined) { - // Prepare background for slider - bgSprite = cc.Sprite.create(bgFile); - - // Prepare progress for slider - progressSprite = cc.Sprite.create(progressFile); - - // Prepare thumb (menuItem) for slider - thumbSprite = cc.Sprite.create(thumbFile); - - this.initWithSprites(bgSprite, progressSprite, thumbSprite); - } -}; - -cc.ControlStepper.prototype._ctor = function(minusSprite, plusSprite){ - plusSprite !== undefined && this.initWithMinusSpriteAndPlusSprite(minusSprite, plusSprite); -}; - -cc.ControlSwitch.prototype._ctor = function(maskSprite, onSprite, offSprite, thumbSprite, onLabel, offLabel){ - offLabel !== undefined && this.initWithMaskSprite(maskSprite, onSprite, offSprite, thumbSprite, onLabel, offLabel); -}; - -cc.TableView.prototype._ctor = function(dataSouurce, size, container){ - container == undefined ? this._init(dataSouurce, size) : this._init(dataSouurce, size, container); -}; - -cc.ScrollView.prototype._ctor = function(size, container) { - size == undefined ? this.init() : (container ? this.initWithViewSize(size, container) : this.initWithViewSize(size)); -}; - - diff --git a/native/cocos/scripting/js-bindings/script/extension/jsb_ext_property_apis.js b/native/cocos/scripting/js-bindings/script/extension/jsb_ext_property_apis.js deleted file mode 100644 index 69605ef21b..0000000000 --- a/native/cocos/scripting/js-bindings/script/extension/jsb_ext_property_apis.js +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2014-2016 Chukong Technologies Inc. - * - * 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. - */ - -var _proto = cc.Control.prototype; -cc.defineGetterSetter(_proto, "opacityModifyRGB", _proto.isOpacityModifyRGB, _proto.setOpacityModifyRGB); -cc.defineGetterSetter(_proto, "state", _proto.getState); -cc.defineGetterSetter(_proto, "enabled", _proto.isEnabled, _proto.setEnabled); -cc.defineGetterSetter(_proto, "selected", _proto.isSelected, _proto.setSelected); -cc.defineGetterSetter(_proto, "highlighted", _proto.isHighlighted, _proto.setHighlighted); - -_proto = cc.ControlButton.prototype; -cc.defineGetterSetter(_proto, "color", _proto.getColor, _proto.setColor); -cc.defineGetterSetter(_proto, "opacity", _proto.getOpacity, _proto.setOpacity); -cc.defineGetterSetter(_proto, "adjustBackgroundImage", _proto.getAdjustBackgroundImage, _proto.setAdjustBackgroundImage); -cc.defineGetterSetter(_proto, "zoomOnTouchDown", _proto.getZoomOnTouchDown, _proto.setZoomOnTouchDown); -cc.defineGetterSetter(_proto, "preferredSize", _proto.getPreferredSize, _proto.setPreferredSize); -cc.defineGetterSetter(_proto, "labelAnchor", _proto.getLabelAnchorPoint, _proto.setLabelAnchorPoint); - -_proto = cc.ControlColourPicker.prototype; -cc.defineGetterSetter(_proto, "color", _proto.getColor, _proto.setColor); -cc.defineGetterSetter(_proto, "enabled", _proto.isEnabled, _proto.setEnabled); -cc.defineGetterSetter(_proto, "background", _proto.getBackground); - -_proto = cc.ControlHuePicker.prototype; -cc.defineGetterSetter(_proto, "enabled", _proto.isEnabled, _proto.setEnabled); -cc.defineGetterSetter(_proto, "hue", _proto.getHue, _proto.setHue); -cc.defineGetterSetter(_proto, "huePercent", _proto.getHuePercentage, _proto.setHuePercentage); -cc.defineGetterSetter(_proto, "background", _proto.getBackground); -cc.defineGetterSetter(_proto, "slider", _proto.getSlider); -cc.defineGetterSetter(_proto, "startPos", _proto.getStartPos); - -_proto = cc.ControlPotentiometer.prototype; -cc.defineGetterSetter(_proto, "enabled", _proto.isEnabled, _proto.setEnabled); -cc.defineGetterSetter(_proto, "value", _proto.getValue, _proto.setValue); -cc.defineGetterSetter(_proto, "minValue", _proto.getMinimumValue, _proto.setMinimumValue); -cc.defineGetterSetter(_proto, "maxValue", _proto.getMaximumValue, _proto.setMaximumValue); -cc.defineGetterSetter(_proto, "progressTimer", _proto.getProgressTimer, _proto.setProgressTimer); -cc.defineGetterSetter(_proto, "thumbSprite", _proto.getThumbSprite, _proto.setThumbSprite); -cc.defineGetterSetter(_proto, "prevLocation", _proto.getPreviousLocation, _proto.setPreviousLocation); - -_proto = cc.ControlSaturationBrightnessPicker.prototype; -cc.defineGetterSetter(_proto, "enabled", _proto.isEnabled, _proto.setEnabled); -cc.defineGetterSetter(_proto, "saturation", _proto.getSaturation); -cc.defineGetterSetter(_proto, "brightness", _proto.getBrightness); -cc.defineGetterSetter(_proto, "background", _proto.getBackground); -cc.defineGetterSetter(_proto, "overlay", _proto.getOverlay); -cc.defineGetterSetter(_proto, "shadow", _proto.getShadow); -cc.defineGetterSetter(_proto, "slider", _proto.getSlider); -cc.defineGetterSetter(_proto, "startPos", _proto.getStartPos); - -_proto = cc.ControlSlider.prototype; -cc.defineGetterSetter(_proto, "enabled", _proto.isEnabled, _proto.setEnabled); -cc.defineGetterSetter(_proto, "value", _proto.getValue, _proto.setValue); -cc.defineGetterSetter(_proto, "minValue", _proto.getMinimumValue, _proto.setMinimumValue); -cc.defineGetterSetter(_proto, "maxValue", _proto.getMaximumValue, _proto.setMaximumValue); -cc.defineGetterSetter(_proto, "minAllowedValue", _proto.getMinimumAllowedValue, _proto.setMinimumAllowedValue); -cc.defineGetterSetter(_proto, "maxAllowedValue", _proto.getMaximumAllowedValue, _proto.setMaximumAllowedValue); -cc.defineGetterSetter(_proto, "thumbSprite", _proto.getThumbSprite); -cc.defineGetterSetter(_proto, "progressSprite", _proto.getProgressSprite); -cc.defineGetterSetter(_proto, "backgroundSprite", _proto.getBackgroundSprite); - -_proto = cc.ControlSwitch.prototype; -cc.defineGetterSetter(_proto, "enabled", _proto.isEnabled, _proto.setEnabled); - -_proto = cc.ScrollView.prototype; -cc.defineGetterSetter(_proto, "width", _proto._getWidth, _proto._setWidth); -cc.defineGetterSetter(_proto, "height", _proto._getHeight, _proto._setHeight); -cc.defineGetterSetter(_proto, "direction", _proto.getDirection, _proto.setDirection); - -_proto = cc.ControlStepper.prototype; -cc.defineGetterSetter(_proto, "wraps", _proto.getWraps, _proto.setWraps); -cc.defineGetterSetter(_proto, "value", _proto.getValue, _proto.setValue); -cc.defineGetterSetter(_proto, "minValue", _proto.getMinimumValue, _proto.setMinimumValue); -cc.defineGetterSetter(_proto, "maxValue", _proto.getMaximumValue, _proto.setMaximumValue); -cc.defineGetterSetter(_proto, "stepValue", _proto.getStepValue, _proto.setStepValue); -cc.defineGetterSetter(_proto, "continuous", _proto.isContinuous); -cc.defineGetterSetter(_proto, "minusSprite", _proto.getMinusSprite, _proto.setMinusSprite); -cc.defineGetterSetter(_proto, "plusSprite", _proto.getPlusSprite, _proto.setPlusSprite); -cc.defineGetterSetter(_proto, "minusLabel", _proto.getMinusLabel, _proto.setMinusLabel); -cc.defineGetterSetter(_proto, "plusSLabel", _proto.getPlusSLabel, _proto.setPlusSLabel); - -_proto = cc.TableViewCell.prototype; -cc.defineGetterSetter(_proto, "objectId", _proto.getObjectID, _proto.setObjectID); diff --git a/native/cocos/scripting/js-bindings/script/jsb.js b/native/cocos/scripting/js-bindings/script/jsb.js index 61dacdc64c..6e169aff76 100644 --- a/native/cocos/scripting/js-bindings/script/jsb.js +++ b/native/cocos/scripting/js-bindings/script/jsb.js @@ -25,45 +25,18 @@ // // DO NOT ALTER THE ORDER -require('script/jsb_cocos2d_constants.js'); require('script/jsb_cocos2d.js'); require('script/jsb_common.js'); require('script/jsb_property_impls.js'); require('script/jsb_property_apis.js'); require('script/jsb_create_apis.js'); - -if (window.ccs) { - require('script/studio/jsb_studio_boot.js'); - require('script/studio/jsb_cocos2d_studio.js'); - require('script/studio/jsb_studio_property_apis.js'); - require('script/studio/jsb_studio_create_apis.js'); - - require('script/studio/jsb_studio_load.js'); - require('script/studio/parsers/action-1.x.js'); - require('script/studio/parsers/action-2.x.js'); - require('script/studio/parsers/scene-1.x.js'); - require('script/studio/parsers/timelineParser-1.x.js'); - require('script/studio/parsers/timelineParser-2.x.js'); - require('script/studio/parsers/uiParser-1.x.js'); - require('script/studio/parsers/compatible.js'); -} +require('script/extension/jsb_cocos2d_extension.js'); if (window.ccui) { require('script/ccui/jsb_cocos2d_ui.js'); require('script/ccui/jsb_ccui_property_impls.js'); require('script/ccui/jsb_ccui_property_apis.js'); require('script/ccui/jsb_ccui_create_apis.js'); - require('script/ccui/jsb_ccui_deprecated.js'); -} - -if (cc.ControlButton) { - require('script/extension/jsb_cocos2d_extension.js'); - require('script/extension/jsb_ext_property_apis.js'); - require('script/extension/jsb_ext_create_apis.js'); -} - -if (cc.PhysicsSprite) { - require('script/physicsSprite/jsb_physicsSprite.js'); } if (window.cp) { @@ -75,31 +48,8 @@ if (window.cp) { require('script/jsb_opengl_constants.js'); require('script/jsb_opengl.js'); -if (cc.BuilderAnimationManager) { - require('script/jsb_cocosbuilder.js'); -} - -if (jsb.fileUtils.isFileExist('jsb_pluginx.js') || jsb.fileUtils.isFileExist('jsb_pluginx.jsc')) { - if (cc.sys.os == cc.sys.OS_IOS || cc.sys.os == cc.sys.OS_ANDROID) { - require('jsb_pluginx.js'); - } -} - if (window.sp) { require('script/jsb_spine.js'); } -if (window.dragonBones) { - require('script/jsb_dragonbones.js'); -} - require("script/jsb_audioengine.js"); - -require('script/jsb_loaders.js'); -require('script/jsb_pool.js'); -require('script/jsb_deprecated.js'); - -if (typeof runtime !== 'undefined') { - require('script/runtime/jsb_runtime.js'); - require('script/runtime/jsb_runtime_md5.js'); -} diff --git a/native/cocos/scripting/js-bindings/script/jsb_boot.js b/native/cocos/scripting/js-bindings/script/jsb_boot.js index 609ad8397f..73f8c34893 100755 --- a/native/cocos/scripting/js-bindings/script/jsb_boot.js +++ b/native/cocos/scripting/js-bindings/script/jsb_boot.js @@ -24,719 +24,7 @@ // cocos2d boot // -//+++++++++++++++++++++++++something about async begin+++++++++++++++++++++++++++++++ -/** - * Async Pool class, a helper of cc.async - * @param {Object|Array} srcObj - * @param {Number} limit the limit of parallel number - * @param {function} iterator - * @param {function} onEnd - * @param {object} target - * @constructor - */ -cc.AsyncPool = function(srcObj, limit, iterator, onEnd, target){ - var self = this; - self._srcObj = srcObj; - self._limit = limit; - self._pool = []; - self._iterator = iterator; - self._iteratorTarget = target; - self._onEnd = onEnd; - self._onEndTarget = target; - self._results = srcObj instanceof Array ? [] : {}; - self._isErr = false; - - cc.each(srcObj, function(value, index){ - self._pool.push({index : index, value : value}); - }); - - self.size = self._pool.length; - self.finishedSize = 0; - self._workingSize = 0; - - self._limit = self._limit || self.size; - - self.onIterator = function(iterator, target){ - self._iterator = iterator; - self._iteratorTarget = target; - }; - - self.onEnd = function(endCb, endCbTarget){ - self._onEnd = endCb; - self._onEndTarget = endCbTarget; - }; - - self._handleItem = function(){ - var self = this; - if(self._pool.length == 0) - return; //return directly if the array's length = 0 - if(self._workingSize >= self._limit) - return; //return directly if the working size great equal limit number - var item = self._pool.shift(); - var value = item.value, index = item.index; - self._workingSize++; - self._iterator.call(self._iteratorTarget, value, index, function(err){ - if(self._isErr) - return; - - self.finishedSize++; - self._workingSize--; - if(err) { - self._isErr = true; - if(self._onEnd) - self._onEnd.call(self._onEndTarget, err); - return - } - - var arr = Array.prototype.slice.call(arguments, 1); - self._results[this.index] = arr[0]; - if (self.finishedSize === self.size) { - if (self._onEnd) - self._onEnd.call(self._onEndTarget, null, self._results); - return; - } - self._handleItem(); - }.bind(item), self); - }; - - self.flow = function(){ - var self = this; - if(self._pool.length === 0) { - if(self._onEnd) - self._onEnd.call(self._onEndTarget, null, []); - return; - } - for(var i = 0; i < self._limit; i++) - self._handleItem(); - }; -}; - -/** - * @class - */ -cc.async = /** @lends cc.async# */{ - /** - * Do tasks series. - * @param {Array|Object} tasks - * @param {function} [cb] callback - * @param {Object} [target] - * @return {cc.AsyncPool} - */ - series : function(tasks, cb, target){ - var asyncPool = new cc.AsyncPool(tasks, 1, function(func, index, cb1){ - func.call(target, cb1); - }, cb, target); - asyncPool.flow(); - return asyncPool; - }, - - /** - * Do tasks parallel. - * @param {Array|Object} tasks - * @param {function} cb callback - * @param {Object} [target] - * @return {cc.AsyncPool} - */ - parallel : function(tasks, cb, target){ - var asyncPool = new cc.AsyncPool(tasks, 0, function(func, index, cb1){ - func.call(target, cb1); - }, cb, target); - asyncPool.flow(); - return asyncPool; - }, - - /** - * Do tasks waterfall. - * @param {Array|Object} tasks - * @param {function} cb callback - * @param {Object} [target] - * @return {cc.AsyncPool} - */ - waterfall : function(tasks, cb, target){ - var args = []; - var lastResults = [null];//the array to store the last results - var asyncPool = new cc.AsyncPool(tasks, 1, - function (func, index, cb1) { - args.push(function (err) { - args = Array.prototype.slice.call(arguments, 1); - if(tasks.length - 1 === index) lastResults = lastResults.concat(args);//while the last task - cb1.apply(null, arguments); - }); - func.apply(target, args); - }, function (err) { - if (!cb) - return; - if (err) - return cb.call(target, err); - cb.apply(target, lastResults); - }); - asyncPool.flow(); - return asyncPool; - }, - - /** - * Do tasks by iterator. - * @param {Array|Object} tasks - * @param {function|Object} iterator - * @param {function} [callback] - * @param {Object} [target] - * @return {cc.AsyncPool} - */ - map : function(tasks, iterator, callback, target){ - var locIterator = iterator; - if(typeof(iterator) === "object"){ - callback = iterator.cb; - target = iterator.iteratorTarget; - locIterator = iterator.iterator; - } - var asyncPool = new cc.AsyncPool(tasks, 0, locIterator, callback, target); - asyncPool.flow(); - return asyncPool; - }, - - /** - * Do tasks by iterator limit. - * @param {Array|Object} tasks - * @param {Number} limit - * @param {function} iterator - * @param {function} cb callback - * @param {Object} [target] - */ - mapLimit : function(tasks, limit, iterator, cb, target){ - var asyncPool = new cc.AsyncPool(tasks, limit, iterator, cb, target); - asyncPool.flow(); - return asyncPool; - } -}; -//+++++++++++++++++++++++++something about async end+++++++++++++++++++++++++++++++++ - -//+++++++++++++++++++++++++something about path begin++++++++++++++++++++++++++++++++ -/** - * @class - */ -cc.path = /** @lends cc.path# */{ - normalizeRE: /[^\.\/]+\/\.\.\//, - - /** - * Join strings to be a path. - * @example - cc.path.join("a", "b.png");//-->"a/b.png" - cc.path.join("a", "b", "c.png");//-->"a/b/c.png" - cc.path.join("a", "b");//-->"a/b" - cc.path.join("a", "b", "/");//-->"a/b/" - cc.path.join("a", "b/", "/");//-->"a/b/" - * @returns {string} - */ - join: function () { - var l = arguments.length; - var result = ""; - for (var i = 0; i < l; i++) { - result = (result + (result === "" ? "" : "/") + arguments[i]).replace(/(\/|\\\\)$/, ""); - } - return result; - }, - - /** - * Get the ext name of a path. - * @example - cc.path.extname("a/b.png");//-->".png" - cc.path.extname("a/b.png?a=1&b=2");//-->".png" - cc.path.extname("a/b");//-->null - cc.path.extname("a/b?a=1&b=2");//-->null - * @param {string} pathStr - * @returns {*} - */ - extname: function (pathStr) { - var temp = /(\.[^\.\/\?\\]*)(\?.*)?$/.exec(pathStr); - return temp ? temp[1] : null; - }, - - /** - * Get the main name of a file name - * @param {string} fileName - * @returns {string} - */ - mainFileName: function(fileName){ - if(fileName){ - var idx = fileName.lastIndexOf("."); - if(idx !== -1) - return fileName.substring(0,idx); - } - return fileName; - }, - - /** - * Get the file name of a file path. - * @example - cc.path.basename("a/b.png");//-->"b.png" - cc.path.basename("a/b.png?a=1&b=2");//-->"b.png" - cc.path.basename("a/b.png", ".png");//-->"b" - cc.path.basename("a/b.png?a=1&b=2", ".png");//-->"b" - cc.path.basename("a/b.png", ".txt");//-->"b.png" - * @param {string} pathStr - * @param {string} [extname] - * @returns {*} - */ - basename: function (pathStr, extname) { - var index = pathStr.indexOf("?"); - if (index > 0) pathStr = pathStr.substring(0, index); - var reg = /(\/|\\\\)([^(\/|\\\\)]+)$/g; - var result = reg.exec(pathStr.replace(/(\/|\\\\)$/, "")); - if (!result) return null; - var baseName = result[2]; - if (extname && pathStr.substring(pathStr.length - extname.length).toLowerCase() === extname.toLowerCase()) - return baseName.substring(0, baseName.length - extname.length); - return baseName; - }, - - /** - * Get dirname of a file path. - * @example - * unix - cc.path.driname("a/b/c.png");//-->"a/b" - cc.path.driname("a/b/c.png?a=1&b=2");//-->"a/b" - cc.path.dirname("a/b/");//-->"a/b" - cc.path.dirname("c.png");//-->"" - * windows - cc.path.driname("a\\b\\c.png");//-->"a\b" - cc.path.driname("a\\b\\c.png?a=1&b=2");//-->"a\b" - * @param {string} pathStr - * @returns {*} - */ - dirname: function (pathStr) { - return pathStr.replace(/((.*)(\/|\\|\\\\))?(.*?\..*$)?/, '$2'); - }, - - /** - * Change extname of a file path. - * @example - cc.path.changeExtname("a/b.png", ".plist");//-->"a/b.plist" - cc.path.changeExtname("a/b.png?a=1&b=2", ".plist");//-->"a/b.plist?a=1&b=2" - * @param {string} pathStr - * @param {string} [extname] - * @returns {string} - */ - changeExtname: function (pathStr, extname) { - extname = extname || ""; - var index = pathStr.indexOf("?"); - var tempStr = ""; - if (index > 0) { - tempStr = pathStr.substring(index); - pathStr = pathStr.substring(0, index); - } - index = pathStr.lastIndexOf("."); - if (index < 0) return pathStr + extname + tempStr; - return pathStr.substring(0, index) + extname + tempStr; - }, - /** - * Change file name of a file path. - * @example - cc.path.changeBasename("a/b/c.plist", "b.plist");//-->"a/b/b.plist" - cc.path.changeBasename("a/b/c.plist?a=1&b=2", "b.plist");//-->"a/b/b.plist?a=1&b=2" - cc.path.changeBasename("a/b/c.plist", ".png");//-->"a/b/c.png" - cc.path.changeBasename("a/b/c.plist", "b");//-->"a/b/b" - cc.path.changeBasename("a/b/c.plist", "b", true);//-->"a/b/b.plist" - * @param {String} pathStr - * @param {String} basename - * @param {Boolean} [isSameExt] - * @returns {string} - */ - changeBasename: function (pathStr, basename, isSameExt) { - if (basename.indexOf(".") === 0) return this.changeExtname(pathStr, basename); - var index = pathStr.indexOf("?"); - var tempStr = ""; - var ext = isSameExt ? this.extname(pathStr) : ""; - if (index > 0) { - tempStr = pathStr.substring(index); - pathStr = pathStr.substring(0, index); - } - index = pathStr.lastIndexOf("/"); - index = index <= 0 ? 0 : index + 1; - return pathStr.substring(0, index) + basename + ext + tempStr; - }, - //todo make public after verification - _normalize: function(url){ - var oldUrl = url = String(url); - - //removing all ../ - do { - oldUrl = url; - url = url.replace(this.normalizeRE, ""); - } while(oldUrl.length !== url.length); - return url; - } -}; -//+++++++++++++++++++++++++something about path end++++++++++++++++++++++++++++++++ - -//+++++++++++++++++++++++++something about loader start+++++++++++++++++++++++++++ -cc.loader = { - _resPath : "", - _audioPath : "", - _register : {},//register of loaders - cache : {},//cache for data loaded - _langPathCache : {},//cache for lang path - - /** - * Get XMLHttpRequest. - * @returns {XMLHttpRequest} - */ - getXMLHttpRequest : function () { - return new XMLHttpRequest(); - }, - - - //@MODE_BEGIN DEV - - _jsCache : {},//cache for js - - _getArgs4Js: function (args) { - var a0 = args[0], a1 = args[1], a2 = args[2], results = ["", null, null]; - - if (args.length === 1) { - results[1] = a0 instanceof Array ? a0 : [a0]; - } else if (args.length === 2) { - if (typeof a1 === "function") { - results[1] = a0 instanceof Array ? a0 : [a0]; - results[2] = a1; - } else { - results[0] = a0 || ""; - results[1] = a1 instanceof Array ? a1 : [a1]; - } - } else if (args.length === 3) { - results[0] = a0 || ""; - results[1] = a1 instanceof Array ? a1 : [a1]; - results[2] = a2; - } else throw new Error("arguments error to load js!"); - return results; - }, - /** - * Load js files. - * @param {?string=} baseDir The pre path for jsList. - * @param {array.} jsList List of js path. - * @param {function} cb Callback function - * - * If the arguments.length == 2, then the baseDir turns to be "". - * @returns {*} - */ - loadJs: function (baseDir, jsList, cb) { - var self = this, localJsCache = self._jsCache, - args = self._getArgs4Js(arguments); - baseDir = args[0]; - jsList = args[1]; - cb = args[2]; - var ccPath = cc.path; - for(var i = 0, li = jsList.length; i < li; ++i){ - require(ccPath.join(baseDir, jsList[i])); - } - if(cb) cb(); - }, - /** - * Load js width loading image. - * - * @param {string} [baseDir] - * @param {array} jsList - * @param {function} [cb] - */ - loadJsWithImg : function(baseDir, jsList, cb){ - this.loadJs.apply(this, arguments); - }, - - //@MODE_END DEV - - /** - * Load a single resource as txt. - * @param {!string} url - * @param {function} cb arguments are : err, txt - */ - loadTxt : function(url, cb){ - cb(null, jsb.fileUtils.getStringFromFile(url)); - }, - - loadJson : function(url, cb){ - this.loadTxt(url, function(err, txt){ - try{ - err ? cb(err) : cb(null, JSON.parse(txt)); - }catch(e){ - throw e; - cb("load json [" + url + "] failed : " + e); - } - }); - }, - - /** - * Load a single image. - * @param {!string} url - * @param {object} [option] - * @param {function} cb - * @returns {Image} - */ - loadImg: function (url, option, cb){ - var l = arguments.length; - if(l == 2) cb = option; - - var cachedTex = cc.textureCache.getTextureForKey(url); - if (cachedTex) { - cb && cb(null, cachedTex); - } - else if (url.match(jsb.urlRegExp)) { - jsb.loadRemoteImg(url, function(succeed, tex) { - if (succeed) { - cb && cb(null, tex); - } - else { - cb && cb("Load image failed"); - } - }); - } - else { - cc.textureCache._addImageAsync(url, function (tex){ - if (tex instanceof cc.Texture2D) - cb && cb(null, tex); - else cb && cb("Load image failed"); - }); - } - }, - /** - * Load binary data by url. - * @param {String} url - * @param {Function} cb - */ - loadBinary : function(url, cb){ - cb(null, jsb.fileUtils.getDataFromFile(url)); - }, - loadBinarySync : function(url){ - return jsb.fileUtils.getDataFromFile(url); - }, - - /** - * Iterator function to load res - * @param {object} item - * @param {number} index - * @param {function} [cb] - * @returns {*} - * @private - */ - _loadResIterator: function (item, index, cb) { - var self = this, url = null; - var type = item.type; - if (type) { - type = "." + type.toLowerCase(); - url = item.src ? item.src : item.name + type; - } else { - url = item; - type = cc.path.extname(url); - } - - var obj = self.cache[url]; - if (obj) - return cb(null, obj); - var loader = null; - if (type) { - loader = self._register[type.toLowerCase()]; - } - if (!loader) { - cc.error("loader for [" + type + "] not exists!"); - return cb(); - } - var basePath = loader.getBasePath ? loader.getBasePath() : self.resPath; - var realUrl = self.getUrl(basePath, url); - - loader.load(realUrl, url, item, function (err, data) { - if (err) { - cc.log(err); - self.cache[url] = null; - delete self.cache[url]; - cb(); - } else { - self.cache[url] = data; - cb(null, data); - } - }); - }, - - /** - * Get url with basePath. - * @param {string} basePath - * @param {string} [url] - * @returns {*} - */ - getUrl: function (basePath, url) { - var self = this, langPathCache = self._langPathCache, path = cc.path; - if (basePath !== undefined && url === undefined) { - url = basePath; - var type = path.extname(url); - type = type ? type.toLowerCase() : ""; - var loader = self._register[type]; - if (!loader) - basePath = self.resPath; - else - basePath = loader.getBasePath ? loader.getBasePath() : self.resPath; - } - url = cc.path.join(basePath || "", url); - if (url.match(/[\/(\\\\)]lang[\/(\\\\)]/i)) { - if (langPathCache[url]) - return langPathCache[url]; - var extname = path.extname(url) || ""; - url = langPathCache[url] = url.substring(0, url.length - extname.length) + "_" + cc.sys.language + extname; - } - return url; - }, - - /** - * Load resources then call the callback. - * @param {string} resources - * @param {function} [option] callback or trigger - * @param {function|Object} [loadCallback] - * @return {cc.AsyncPool} - */ - load : function(resources, option, loadCallback){ - var self = this; - var len = arguments.length; - if(len === 0) - throw new Error("arguments error!"); - - if(len === 3){ - if(typeof option === "function"){ - if(typeof loadCallback === "function") - option = {trigger : option, cb : loadCallback }; - else - option = { cb : option, cbTarget : loadCallback}; - } - }else if(len === 2){ - if(typeof option === "function") - option = {cb : option}; - }else if(len === 1){ - option = {}; - } - - if(!(resources instanceof Array)) - resources = [resources]; - var asyncPool = new cc.AsyncPool( - resources, 0, - function (value, index, AsyncPoolCallback, aPool) { - self._loadResIterator(value, index, function (err) { - var arr = Array.prototype.slice.call(arguments, 1); - if (option.trigger) - option.trigger.call(option.triggerTarget, arr[0], aPool.size, aPool.finishedSize); //call trigger - AsyncPoolCallback(err, arr[0]); - }); - }, - option.cb, option.cbTarget); - asyncPool.flow(); - return asyncPool; - }, - - loadAliases : function(url, cb){ - jsb.fileUtils.loadFilenameLookup(url); - if(cb) cb(); - }, - - /** - * Register a resource loader into loader. - * @param {string} extNames - * @param {function} loader - */ - register: function (extNames, loader) { - if (!extNames || !loader) return; - var self = this; - if (typeof extNames === "string") - return this._register[extNames.trim().toLowerCase()] = loader; - for (var i = 0, li = extNames.length; i < li; i++) { - self._register["." + extNames[i].trim().toLowerCase()] = loader; - } - }, - - /** - * Get resource data by url. - * @param url - * @returns {*} - */ - getRes : function(url){ - var cached = this.cache[url]; - if (cached) - return cached; - var type = cc.path.extname(url); - if (!type) return cc.log("cc.loader.getRes: Invalid url"); - var loader = this._register[type.toLowerCase()]; - if (!loader) return cc.log("cc.loader.getRes: loader for [" + type + "] not exists!"); - var basePath = loader.getBasePath ? loader.getBasePath() : this.resPath; - var realUrl = this.getUrl(basePath, url); - return loader.load(realUrl, url); - }, - - /** - * Release the cache of resource by url. - * @param url - */ - release: function (url) { - var cache = this.cache; - delete cache[url]; - }, - - /** - * Resource cache of all resources. - */ - releaseAll: function () { - var locCache = this.cache; - for (var key in locCache) - delete locCache[key]; - } - -}; -cc.defineGetterSetter(cc.loader, "resPath", function(){ - return this._resPath; -}, function(resPath){ - this._resPath = resPath || ""; - jsb.fileUtils.addSearchPath(this._resPath); -}); -cc.defineGetterSetter(cc.loader, "audioPath", function(){ - return this._audioPath; -}, function(audioPath){ - this._audioPath = audioPath || ""; - jsb.fileUtils.addSearchPath(this._audioPath); -}); - -//+++++++++++++++++++++++++something about loader end+++++++++++++++++++++++++++++ - -/** - * A string tool to construct a string with format string. - * for example: - * cc.formatStr("a: %d, b: %b", a, b); - * cc.formatStr(a, b, c); - * @returns {String} - */ -cc.formatStr = function(){ - var args = arguments; - var l = args.length; - if (l < 1) return ''; - var REGEXP_NUM_OR_STR = /(%d)|(%s)/; - - var i = 1; - var str = args[0]; - var hasSubstitution = typeof str === 'string' && REGEXP_NUM_OR_STR.test(str); - if (hasSubstitution) { - var REGEXP_STR = /%s/; - for (; i < l; ++i) { - var arg = args[i]; - var regExpToTest = typeof arg === 'number' ? REGEXP_NUM_OR_STR : REGEXP_STR; - if (regExpToTest.test(str)) - str = str.replace(regExpToTest, arg); - else - str += ' ' + arg; - } - } - else { - if (l > 1) { - for (; i < l; ++i) { - str += ' ' + args[i]; - } - } - else { - str = '' + str; - } - } - return str; -}; +'use strict'; //+++++++++++++++++++++++++Engine initialization function begin+++++++++++++++++++++++++++ @@ -756,7 +44,7 @@ cc.view.convertToLocationInView = function (tx, ty, relatedPos) { cc.view.enableRetina = function(enabled) {}; cc.view.isRetinaEnabled = function() { var sys = cc.sys; - return (sys.os == sys.OS_IOS || sys.os == sys.OS_OSX) ? true : false; + return (sys.os === sys.OS_IOS || sys.os === sys.OS_OSX) ? true : false; }; cc.view.adjustViewPort = function() {}; cc.view.resizeWithBrowserSize = function () {return;}; @@ -781,12 +69,8 @@ cc.view.setContentTranslateLeftTop = function(){return;}; cc.view.getContentTranslateLeftTop = function(){return null;}; cc.view.setFrameZoomFactor = function(){return;}; cc.view.setOrientation = function () {}; -cc.DENSITYDPI_DEVICE = "device-dpi"; -cc.DENSITYDPI_HIGH = "high-dpi"; -cc.DENSITYDPI_MEDIUM = "medium-dpi"; -cc.DENSITYDPI_LOW = "low-dpi"; cc.view.setTargetDensityDPI = function() {}; -cc.view.getTargetDensityDPI = function() {return cc.DENSITYDPI_DEVICE;}; +cc.view.getTargetDensityDPI = function() {return cc.macro.DENSITYDPI_DEVICE;}; cc.eventManager = cc.director.getEventDispatcher(); @@ -806,40 +90,8 @@ cc.audioEngine.features = { }; cc.configuration = cc.Configuration.getInstance(); - cc.textureCache = cc.director.getTextureCache(); -cc.TextureCache.prototype._addImageAsync = cc.TextureCache.prototype.addImageAsync; -cc.TextureCache.prototype.addImageAsync = function(url, cb, target) { - var localTex = null; - cc.loader.loadImg(url, function(err, tex) { - if (err) tex = null; - if (cb) { - cb.call(target, tex); - } - localTex = tex; - }); - return localTex; -}; -// Fix for compatibility with old APIs -cc.TextureCache.prototype._addImage = cc.TextureCache.prototype.addImage; -cc.TextureCache.prototype.addImage = function(url, cb, target) { - if (typeof cb === "function") { - return this.addImageAsync(url, cb, target); - } - else { - if (cb) { - return this._addImage(url, cb); - } - else { - return this._addImage(url); - } - } -}; - cc.shaderCache = cc.ShaderCache.getInstance(); -cc.animationCache = cc.AnimationCache.getInstance(); -cc.spriteFrameCache = cc.SpriteFrameCache.getInstance(); - cc.plistParser = cc.PlistParser.getInstance(); // File utils (Temporary, won't be accessible) @@ -1529,257 +781,11 @@ cc._initDebugSetting = function (mode) { } }; -cc._engineLoaded = false; - -cc.initEngine = function (config, cb) { - require("script/jsb.js"); - cc._renderType = cc.game.RENDER_TYPE_OPENGL; - cc._initDebugSetting(config[cc.game.CONFIG_KEY.debugMode]); - cc._engineLoaded = true; - cc.log(cc.ENGINE_VERSION); - if (cb) cb(); -}; - -//+++++++++++++++++++++++++something about CCGame begin+++++++++++++++++++++++++++ - -/** - * An object to boot the game. - * @class - * @name cc.game - */ -cc.game = { - DEBUG_MODE_NONE: 0, - DEBUG_MODE_INFO: 1, - DEBUG_MODE_WARN: 2, - DEBUG_MODE_ERROR: 3, - DEBUG_MODE_INFO_FOR_WEB_PAGE: 4, - DEBUG_MODE_WARN_FOR_WEB_PAGE: 5, - DEBUG_MODE_ERROR_FOR_WEB_PAGE: 6, - - EVENT_HIDE: "game_on_hide", - EVENT_SHOW: "game_on_show", - EVENT_RESIZE: "game_on_resize", - - RENDER_TYPE_CANVAS: 0, - RENDER_TYPE_WEBGL: 1, - RENDER_TYPE_OPENGL: 2, - - _eventHide: null, - _eventShow: null, - - /** - * Key of config - * @constant - * @type {Object} - */ - CONFIG_KEY: { - width: "width", - height: "height", - engineDir: "engineDir", - modules: "modules", - debugMode: "debugMode", - showFPS: "showFPS", - frameRate: "frameRate", - id: "id", - renderMode: "renderMode", - jsList: "jsList" - }, - - // states - _paused: false,//whether the game is paused - _prepareCalled: false,//whether the prepare function has been called - _prepared: false,//whether the engine has prepared - - _intervalId: null,//interval target of main - - /** - * Config of game - * @type {Object} - */ - config: null, - - /** - * Callback when the scripts of engine have been load. - * @type {Function} - */ - onStart: null, - - /** - * Callback when game exits. - * @type {Function} - */ - onStop: null, - -//@Public Methods - -// @Game play control - /** - * Set frameRate of game. - * @param frameRate - */ - setFrameRate: function (frameRate) { - var self = this, config = self.config, CONFIG_KEY = self.CONFIG_KEY; - config[CONFIG_KEY.frameRate] = frameRate; - cc.director.setAnimationInterval(1.0/frameRate); - }, - - /** - * Run the game frame by frame. - */ - step: function () { - cc.director.mainLoop(); - }, - - /** - * Pause the game. - */ - pause: function () { - this._paused = true; - cc.director.pause(); - }, - - /** - * Resume the game from pause. - */ - resume: function () { - this._paused = false; - cc.director.resume(); - }, - - /** - * Check whether the game is paused. - */ - isPaused: function () { - return this._paused; - }, - - /** - * Restart game. - */ - restart: function () { - __restartVM(); - }, - - /** - * End game, it will close the game window - */ - end: function () { - close(); - }, - -// @Game loading - /** - * Prepare game. - * @param cb - */ - prepare: function (cb) { - var self = this, - config = self.config, - CONFIG_KEY = self.CONFIG_KEY; - - this._loadConfig(); - - // Already prepared - if (this._prepared) { - if (cb) cb(); - return; - } - // Prepare called, but not done yet - if (this._prepareCalled) { - return; - } - // Prepare never called and engine ready - if (cc._engineLoaded) { - this._prepareCalled = true; - - // Load game scripts - var jsList = config[CONFIG_KEY.jsList]; - if (jsList) { - cc.loader.loadJsWithImg(jsList, function (err) { - if (err) throw new Error(err); - self._prepared = true; - if (cb) cb(); - }); - } - else { - if (cb) cb(); - } - - return; - } - - // Engine not loaded yet - cc.initEngine(this.config, function () { - self.prepare(cb); - }); - }, - - /** - * Run game with configuration object and onStart function. - * @param {Object|Function} [config] Pass configuration object or onStart function - * @param {onStart} [onStart] onStart function to be executed after game initialized - */ - run: function (config, onStart) { - if (typeof config === 'function') { - cc.game.onStart = config; - } - else { - if (config) { - cc.game.config = config; - } - if (typeof onStart === 'function') { - cc.game.onStart = onStart; - } - } - - this.prepare(cc.game.onStart && cc.game.onStart.bind(cc.game)); - }, - -//@Private Methods - - _loadConfig: function () { - // Load config - // Already loaded - if (this.config) { - this._initConfig(this.config); - } - // Load from project.json - else { - try { - var txt = jsb.fileUtils.getStringFromFile("project.json"); - var data = JSON.parse(txt); - this._initConfig(data || {}); - } catch (e) { - console.log("Failed to read or parse project.json"); - this._initConfig({}); - } - } - }, - - _initConfig: function (config) { - var CONFIG_KEY = this.CONFIG_KEY; - - // Configs adjustment - config[CONFIG_KEY.showFPS] = typeof config[CONFIG_KEY.showFPS] === 'undefined' ? true : config[CONFIG_KEY.showFPS]; - config[CONFIG_KEY.engineDir] = config[CONFIG_KEY.engineDir] || "frameworks/cocos2d-html5"; - if (config[CONFIG_KEY.debugMode] == null) - config[CONFIG_KEY.debugMode] = 0; - config[CONFIG_KEY.frameRate] = config[CONFIG_KEY.frameRate] || 60; - if (config[CONFIG_KEY.renderMode] == null) - config[CONFIG_KEY.renderMode] = 0; - - this.config = config; - - cc.director.setDisplayStats(this.config[CONFIG_KEY.showFPS]); - cc.director.setAnimationInterval(1.0/this.config[CONFIG_KEY.frameRate]); - } -}; - //+++++++++++++++++++++++++something about CCGame end+++++++++++++++++++++++++++++ // Original bind in Spidermonkey v33 will trigger object life cycle track issue in our memory model and cause crash Function.prototype.bind = function (oThis) { - if (!cc.isFunction(this)) { + if (typeof this !== 'function') { // closest thing possible to the ECMAScript 5 // internal IsCallable function throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); @@ -1802,3 +808,11 @@ Function.prototype.bind = function (oThis) { }; jsb.urlRegExp = new RegExp("^(?:https?|ftp)://\\S*$", "i"); + +cc._engineLoaded = false; + +(function (config) { + require("script/jsb.js"); + cc._engineLoaded = true; + console.log(cc.ENGINE_VERSION); +})(); diff --git a/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js b/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js index 6f0e187552..db87e6cf9b 100644 --- a/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js +++ b/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js @@ -28,28 +28,6 @@ // cc.ENGINE_VERSION = "Cocos2d-JS v3.14"; -cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL = 0; -cc.DIRECTOR_STATS_POSITION = {x: 0, y: 0}; -cc.DIRECTOR_FPS_INTERVAL = 0.5; -cc.COCOSNODE_RENDER_SUBPIXEL = 1; -cc.SPRITEBATCHNODE_RENDER_SUBPIXEL = 1; -cc.OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA = 0; -cc.TEXTURE_ATLAS_USE_TRIANGLE_STRIP = 0; -cc.TEXTURE_ATLAS_USE_VAO = 0; -cc.TEXTURE_NPOT_SUPPORT = 0; -cc.RETINA_DISPLAY_SUPPORT = 1; -cc.RETINA_DISPLAY_FILENAME_SUFFIX = "-hd"; -cc.USE_LA88_LABELS = 1; -cc.SPRITE_DEBUG_DRAW = 0; -cc.SPRITEBATCHNODE_DEBUG_DRAW = 0; -cc.LABELBMFONT_DEBUG_DRAW = 0; -cc.LABELATLAS_DEBUG_DRAW = 0; -cc.IS_RETINA_DISPLAY_SUPPORTED = 1; -cc.DEFAULT_ENGINE = cc.ENGINE_VERSION + "-native"; -cc.ENABLE_STACKABLE_ACTIONS = 1; -cc.ENABLE_GL_STATE_CACHE = 1; - - // Resolution policies cc.ResolutionPolicy = { @@ -76,58 +54,11 @@ cc.ResolutionPolicy = { UNKNOWN:5 }; -cc.LANGUAGE_ENGLISH = 0; -cc.LANGUAGE_CHINESE = 1; -cc.LANGUAGE_FRENCH = 2; -cc.LANGUAGE_ITALIAN = 3; -cc.LANGUAGE_GERMAN = 4; -cc.LANGUAGE_SPANISH = 5; -cc.LANGUAGE_RUSSIAN = 6; -cc.LANGUAGE_KOREAN = 7; -cc.LANGUAGE_JAPANESE = 8; -cc.LANGUAGE_HUNGARIAN = 9; -cc.LANGUAGE_PORTUGUESE = 10; -cc.LANGUAGE_ARABIC = 11; - cc.Director.PROJECTION_2D = 0; cc.Director.PROJECTION_3D = 1; cc.Director.PROJECTION_CUSTOM = 3; cc.Director.PROJECTION_DEFAULT = cc.Director.PROJECTION_3D; -cc.DEVICE_ORIENTATION_PORTRAIT = 0; -cc.DEVICE_ORIENTATION_LANDSCAPE_LEFT = 1; -cc.DEVICE_ORIENTATION_PORTRAIT_UPSIDE_DOWN = 2; -cc.DEVICE_ORIENTATION_LANDSCAPE_RIGHT = 3; -cc.DEVICE_MAX_ORIENTATIONS = 2; - -cc.IMAGE_FORMAT_JPEG = 0; -cc.IMAGE_FORMAT_PNG = 1; -cc.IMAGE_FORMAT_RAWDATA = 9; - -cc.TOUCH_ALL_AT_ONCE = 0; -cc.TOUCH_ONE_BY_ONE = 1; - -cc.TRANSITION_ORIENTATION_LEFT_OVER = 0; -cc.TRANSITION_ORIENTATION_RIGHT_OVER = 1; -cc.TRANSITION_ORIENTATION_UP_OVER = 0; -cc.TRANSITION_ORIENTATION_DOWN_OVER = 1; - -cc.RED = {r:255, g:0, b:0}; -cc.GREEN = {r:0, g:255, b:0}; -cc.BLUE = {r:0, g:0, b:255}; -cc.BLACK = {r:0, g:0, b:0}; -cc.WHITE = {r:255, g:255, b:255}; -cc.YELLOW = {r:255, g:255, b:0}; - -cc.POINT_ZERO = {x:0, y:0}; - -cc.PARTICLE_DEFAULT_CAPACITY = 500; - -cc.MENU_STATE_WAITING = 0; -cc.MENU_STATE_TRACKING_TOUCH = 1; -cc.MENU_HANDLER_PRIORITY = -128; -cc.DEFAULT_PADDING = 5; - cc.Scheduler.PRIORITY_SYSTEM = -2147483648; cc.Scheduler.PRIORITY_NON_SYSTEM = cc.Scheduler.PRIORITY_SYSTEM + 1; @@ -158,80 +89,6 @@ _Class.PIXEL_FORMAT_ATC_INTERPOLATED_ALPHA = 20; _Class.PIXEL_FORMAT_DEFAULT = _Class.PIXEL_FORMAT_AUTO; _Class.defaultPixelFormat = _Class.PIXEL_FORMAT_DEFAULT; -// For blend -cc.ONE = 1; -cc.ZERO = 0; -cc.SRC_ALPHA = 0x0302; -cc.SRC_ALPHA_SATURATE = 0x308; -cc.SRC_COLOR = 0x300; -cc.DST_ALPHA = 0x304; -cc.DST_COLOR = 0x306; -cc.ONE_MINUS_SRC_ALPHA = 0x0303; -cc.ONE_MINUS_SRC_COLOR = 0x301; -cc.ONE_MINUS_DST_ALPHA = 0x305; -cc.ONE_MINUS_DST_COLOR = 0x0307; -cc.ONE_MINUS_CONSTANT_ALPHA = 0x8004; -cc.ONE_MINUS_CONSTANT_COLOR = 0x8002; - -//texture parameters -cc.LINEAR = 0x2601; -cc.REPEAT = 0x2901; -cc.CLAMP_TO_EDGE = 0x812f; -cc.MIRRORED_REPEAT = 0x8370; - -cc.VERTEX_ATTRIB_FLAG_NONE = 0; -cc.VERTEX_ATTRIB_FLAG_POSITION = 1 << 0; -cc.VERTEX_ATTRIB_FLAG_COLOR = 1 << 1; -cc.VERTEX_ATTRIB_FLAG_TEX_COORDS = 1 << 2; -cc.VERTEX_ATTRIB_FLAG_POS_COLOR_TEX = ( cc.VERTEX_ATTRIB_FLAG_POSITION | cc.VERTEX_ATTRIB_FLAG_COLOR | cc.VERTEX_ATTRIB_FLAG_TEX_COORDS ); -cc.GL_ALL = 0; - -cc.VERTEX_ATTRIB_POSITION = 0; -cc.VERTEX_ATTRIB_COLOR = 1; -cc.VERTEX_ATTRIB_TEX_COORDS = 2; -cc.VERTEX_ATTRIB_MAX = 3; - -cc.UNIFORM_PMATRIX = 0; -cc.UNIFORM_MVMATRIX = 1; -cc.UNIFORM_MVPMATRIX = 2; -cc.UNIFORM_TIME = 3; -cc.UNIFORM_SINTIME = 4; -cc.UNIFORM_COSTIME = 5; -cc.UNIFORM_RANDOM01 = 6; -cc.UNIFORM_SAMPLER = 7; -cc.UNIFORM_MAX = 8; - -// Shaders -cc.UNIFORM_TIME_S = "CC_Time"; -cc.UNIFORM_COS_TIME_S = 'CC_CosTime'; -cc.UNIFORM_COSTIME_S = "CC_CosTime"; -cc.UNIFORM_SIN_TIME_S = 'CC_SinTime'; -cc.UNIFORM_SINTIME_S = "CC_SinTime"; -cc.UNIFORM_PMATRIX_S = "CC_PMatrix"; -cc.UNIFORM_MVMATRIX_S = "CC_MVMatrix"; -cc.UNIFORM_MVPMATRIX_S = "CC_MVPMatrix"; -cc.UNIFORM_P_MATRIX_S = 'CC_PMatrix'; -cc.UNIFORM_MV_MATRIX_S = 'CC_MVMatrix'; -cc.UNIFORM_MVP_MATRIX_S = 'CC_MVPMatrix'; -cc.UNIFORM_RANDOM01_S = 'CC_Random01'; -cc.UNIFORM_SAMPLER_S = 'CC_Texture0'; -cc.UNIFORM_ALPHA_TEST_VALUE_S = "CC_AlphaValue"; - -cc.ITEM_SIZE = 32; - -cc.CURRENT_ITEM = 0xc0c05001; -cc.ZOOM_ACTION_TAG = 0xc0c05002; -cc.NORMAL_TAG = 8801; -cc.SELECTED_TAG = 8802; -cc.DISABLE_TAG = 8803; - - -cc.stencilBits = -1; //CCClippingNode.js - -cc.g_NumberOfDraws = 0; //CCDirector.js - -cc.s_globalOrderOfArrival = 1; - cc.Event.TOUCH = 0; //CCEvent.js cc.Event.KEYBOARD = 1; cc.Event.ACCELERATION = 2; @@ -255,903 +112,37 @@ cc.EventMouse.BUTTON_8 = 7; cc.EventTouch.MAX_TOUCHES = 5; cc.EventTouch.EventCode = {BEGAN: 0, MOVED: 1, ENDED: 2, CANCELLED: 3}; -cc.SpriteBatchNode.DEFAULT_CAPACITY = 29; //CCSpriteBatchNode.js - cc.ParticleSystem.SHAPE_MODE = 0; //CCParticleSystem.js cc.ParticleSystem.TEXTURE_MODE = 1; cc.ParticleSystem.STAR_SHAPE = 0; cc.ParticleSystem.BALL_SHAPE = 1; - -cc.ProgressTimer.TEXTURE_COORDS_COUNT = 4; //CCProgressTimer.js -cc.ProgressTimer.TEXTURE_COORDS = 0x4b; - -cc.IMAGE_FORMAT_RAWDATA = 2; //CCRenderTexture.js +cc.ParticleSystem.DURATION_INFINITY = -1; +cc.ParticleSystem.START_SIZE_EQUAL_TO_END_SIZE = -1; +cc.ParticleSystem.START_RADIUS_EQUAL_TO_END_RADIUS = -1; cc.TMXLayerInfo.ATTRIB_NONE = 1 << 0; //CCTMXXMLParser.js cc.TMXLayerInfo.ATTRIB_BASE64 = 1 << 1; cc.TMXLayerInfo.ATTRIB_GZIP = 1 << 2; cc.TMXLayerInfo.ATTRIB_ZLIB = 1 << 3; -cc.TMX_PROPERTY_NONE = 0; -cc.TMX_PROPERTY_MAP = 1; -cc.TMX_PROPERTY_LAYER = 2; -cc.TMX_PROPERTY_OBJECTGROUP = 3; -cc.TMX_PROPERTY_OBJECT = 4; -cc.TMX_PROPERTY_TILE = 5; -cc.SCENE_FADE = 4208917214; //CCTransition.js - -cc.SCENE_RADIAL = 0xc001; //CCTransitionProgress.js - - -// -// CCMacro.js export -// - -/** - * @constant - * @type Number - */ -cc.INVALID_INDEX = -1; - -/** - * PI is the ratio of a circle's circumference to its diameter. - * @constant - * @type Number - */ -cc.PI = Math.PI; - -/** - * @constant - * @type Number - */ -cc.FLT_MAX = parseFloat('3.402823466e+38F'); - -/** - * @constant - * @type Number - */ -cc.RAD = cc.PI / 180; - -/** - * @constant - * @type Number - */ -cc.DEG = 180 / cc.PI; - -/** - * maximum unsigned int value - * @constant - * @type Number - */ -cc.UINT_MAX = 0xffffffff; - -/** - *

- * simple macro that swaps 2 variables
- * modified from c++ macro, you need to pass in the x and y variables names in string,
- * and then a reference to the whole object as third variable - *

- * @param x - * @param y - * @param ref - * @function - * @deprecated - */ -cc.swap = function (x, y, ref) { - if ((typeof ref) == 'object' && (typeof ref.x) != 'undefined' && (typeof ref.y) != 'undefined') { - var tmp = ref[x]; - ref[x] = ref[y]; - ref[y] = tmp; - } else - cc.log("cc.swap is being modified from original macro, please check usage"); -}; - -/** - *

- * Linear interpolation between 2 numbers, the ratio sets how much it is biased to each end - *

- * @param {Number} a number A - * @param {Number} b number B - * @param {Number} r ratio between 0 and 1 - * @function - * @example - * cc.lerp(2,10,0.5)//returns 6
- * cc.lerp(2,10,0.2)//returns 3.6 - */ -cc.lerp = function (a, b, r) { - return a + (b - a) * r; -}; - -/** - * get a random number from 0 to 0xffffff - * @function - * @returns {number} - */ -cc.rand = function () { - return Math.random() * 0xffffff; -}; - -/** - * returns a random float between -1 and 1 - * @return {Number} - * @function - */ -cc.randomMinus1To1 = function () { - return (Math.random() - 0.5) * 2; -}; - -/** - * returns a random float between 0 and 1 - * @return {Number} - * @function - */ -cc.random0To1 = Math.random; - -/** - * converts degrees to radians - * @param {Number} angle - * @return {Number} - * @function - */ -cc.degreesToRadians = function (angle) { - return angle * cc.RAD; -}; - -/** - * converts radians to degrees - * @param {Number} angle - * @return {Number} - * @function - */ -cc.radiansToDegrees = function (angle) { - return angle * cc.DEG; -}; - -/** - * @constant - * @type Number - */ -cc.REPEAT_FOREVER = 0xffffffff; - -/** - * default gl blend src function. Compatible with premultiplied alpha images. - * @constant - * @type Number - */ -cc.BLEND_SRC = cc.OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA ? 1 : 0x0302; - -/** - * default gl blend dst function. Compatible with premultiplied alpha images. - * @constant - * @type Number - */ -cc.BLEND_DST = 0x0303; - -/** - * Helpful macro that setups the GL server state, the correct GL program and sets the Model View Projection matrix - * @param {cc.Node} node setup node - * @function - */ -cc.nodeDrawSetup = function (node) { - //cc.glEnable(node._glServerState); - if (node._shaderProgram) { - //cc._renderContext.useProgram(node._shaderProgram._programObj); - node._shaderProgram.use(); - node._shaderProgram.setUniformForModelViewAndProjectionMatrixWithMat4(); - } -}; - -/** - *

- * GL states that are enabled:
- * - GL_TEXTURE_2D
- * - GL_VERTEX_ARRAY
- * - GL_TEXTURE_COORD_ARRAY
- * - GL_COLOR_ARRAY
- *

- * @function - */ -cc.enableDefaultGLStates = function () { - //TODO OPENGL STUFF - /* - glEnableClientState(GL_VERTEX_ARRAY); - glEnableClientState(GL_COLOR_ARRAY); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - glEnable(GL_TEXTURE_2D);*/ -}; - -/** - *

- * Disable default GL states:
- * - GL_TEXTURE_2D
- * - GL_TEXTURE_COORD_ARRAY
- * - GL_COLOR_ARRAY
- *

- * @function - */ -cc.disableDefaultGLStates = function () { - //TODO OPENGL - /* - glDisable(GL_TEXTURE_2D); - glDisableClientState(GL_COLOR_ARRAY); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - glDisableClientState(GL_VERTEX_ARRAY); - */ -}; - -/** - *

- * Increments the GL Draws counts by one.
- * The number of calls per frame are displayed on the screen when the CCDirector's stats are enabled.
- *

- * @param {Number} addNumber - * @function - */ -cc.incrementGLDraws = function (addNumber) { - cc.g_NumberOfDraws += addNumber; -}; - -/** - * @constant - * @type Number - */ -cc.FLT_EPSILON = 0.0000001192092896; - -/** - *

- * On Mac it returns 1;
- * On iPhone it returns 2 if RetinaDisplay is On. Otherwise it returns 1 - *

- * @function - */ -cc.contentScaleFactor = cc.IS_RETINA_DISPLAY_SUPPORTED ? function () { - return cc.director.getContentScaleFactor(); -} : function () { - return 1; -}; - -/** - * Converts a Point in points to pixels - * @param {cc.Point} points - * @return {cc.Point} - * @function - */ -cc.pointPointsToPixels = function (points) { - var scale = cc.contentScaleFactor(); - return cc.p(points.x * scale, points.y * scale); -}; - -/** - * Converts a Point in pixels to points - * @param {Point} pixels - * @function - */ -cc.pointPixelsToPoints = function (pixels) { - var scale = cc.contentScaleFactor(); - return cc.p(pixels.x / scale, pixels.y / scale); -}; - -cc._pointPixelsToPointsOut = function(pixels, outPoint){ - var scale = cc.contentScaleFactor(); - outPoint.x = pixels.x / scale; - outPoint.y = pixels.y / scale; -}; - -/** - * Converts a Size in points to pixels - * @param {cc.Size} sizeInPoints - * @return {cc.Size} - * @function - */ -cc.sizePointsToPixels = function (sizeInPoints) { - var scale = cc.contentScaleFactor(); - return cc.size(sizeInPoints.width * scale, sizeInPoints.height * scale); -}; - -/** - * Converts a size in pixels to points - * @param {cc.Size} sizeInPixels - * @return {cc.Size} - * @function - */ -cc.sizePixelsToPoints = function (sizeInPixels) { - var scale = cc.contentScaleFactor(); - return cc.size(sizeInPixels.width / scale, sizeInPixels.height / scale); -}; - -cc._sizePixelsToPointsOut = function (sizeInPixels, outSize) { - var scale = cc.contentScaleFactor(); - outSize.width = sizeInPixels.width / scale; - outSize.height = sizeInPixels.height / scale; -}; - -/** - * Converts a rect in pixels to points - * @param {cc.Rect} pixel - * @function - */ -cc.rectPixelsToPoints = cc.IS_RETINA_DISPLAY_SUPPORTED ? function (pixel) { - var scale = cc.contentScaleFactor(); - return cc.rect(pixel.x / scale, pixel.y / scale, - pixel.width / scale, pixel.height / scale); -} : function (p) { - return p; -}; - -/** - * Converts a rect in points to pixels - * @param {cc.Rect} point - * @function - */ -cc.rectPointsToPixels = cc.IS_RETINA_DISPLAY_SUPPORTED ? function (point) { - var scale = cc.contentScaleFactor(); - return cc.rect(point.x * scale, point.y * scale, - point.width * scale, point.height * scale); -} : function (p) { - return p; -}; - -cc.checkGLErrorDebug = function () { - if (cc.renderMode == cc._RENDER_TYPE_WEBGL) { - var _error = cc._renderContext.getError(); - if (_error) { - cc.log(CC._localZOrder.checkGLErrorDebug, _error); - } - } -}; - - -// -// Reusable objects -// -cc._reuse_p = [ {x:0, y:0}, {x:0,y:0}, {x:0,y:0}, {x:0,y:0} ]; -cc._reuse_p_index = 0; -cc._reuse_size = {width:0, height:0}; -cc._reuse_rect = {x:0, y:0, width:0, height:0}; -cc._reuse_color3b = {r:255, g:255, b:255 }; -cc._reuse_color4b = {r:255, g:255, b:255, a:255 }; - - - -// -// Basic structure : Point -// -cc.p = function( x, y ) -{ +// Temporary basic structures, will be overwrite by value-types/ +// Point +cc.p = function (x, y) { + 'use strict'; if (x == undefined) return {x: 0, y: 0}; if (y == undefined) return {x: x.x, y: x.y}; return {x:x, y:y}; }; -cc._p = function( x, y ) -{ - if( cc._reuse_p_index == cc._reuse_p.length ) - cc._reuse_p_index = 0; - - var p = cc._reuse_p[ cc._reuse_p_index]; - cc._reuse_p_index++; - p.x = x; - p.y = y; - return p; -}; - -cc.pointEqualToPoint = function (point1, point2) { - return ((point1.x == point2.x) && (point1.y == point2.y)); -}; - -cc.PointZero = function () { - return cc.p(0, 0); -}; - - -/** - * Unrotates two points. - * @param {cc.Point} v1 - * @param {cc.Point} v2 - * @return {cc.Point} - */ -cc.pUnrotate = function (v1, v2) { - return cc.p(v1.x * v2.x + v1.y * v2.y, v1.y * v2.x - v1.x * v2.y); -}; - -/** - * Converts radians to a normalized vector. - * @param {Number} a - * @return {cc.Point} - */ -cc.pForAngle = function (a) { - return cc.p(Math.cos(a), Math.sin(a)); -}; - -/** - * Converts a vector to radians. - * @param {cc.Point} v - * @return {Number} - */ -cc.pToAngle = function (v) { - return Math.atan2(v.y, v.x); -}; - -/** - * Clamp a value between from and to. - * @param {Number} value - * @param {Number} min_inclusive - * @param {Number} max_inclusive - * @return {Number} - */ -cc.clampf = function (value, min_inclusive, max_inclusive) { - if (min_inclusive > max_inclusive) { - var temp = min_inclusive; - min_inclusive = max_inclusive; - max_inclusive = temp; - } - return value < min_inclusive ? min_inclusive : value < max_inclusive ? value : max_inclusive; -}; - -/** - * Quickly convert cc.Size to a cc.Point - * @param {cc.Size} s - * @return {cc.Point} - */ -cc.pFromSize = function (s) { - return cc.p(s.width, s.height); -}; - -/** - * Run a math operation function on each point component
- * Math.abs, Math.fllor, Math.ceil, Math.round. - * @param {cc.Point} p - * @param {Function} opFunc - * @return {cc.Point} - * @example - * //For example: let's try to take the floor of x,y - * var p = cc.pCompOp(cc.p(10,10),Math.abs); - */ -cc.pCompOp = function (p, opFunc) { - return cc.p(opFunc(p.x), opFunc(p.y)); -}; - -/** - * Linear Interpolation between two points a and b - * alpha == 0 ? a - * alpha == 1 ? b - * otherwise a value between a..b - * @param {cc.Point} a - * @param {cc.Point} b - * @param {Number} alpha - * @return {cc.pAdd} - */ -cc.pLerp = function (a, b, alpha) { - return cc.pAdd(cc.pMult(a, 1 - alpha), cc.pMult(b, alpha)); -}; - -/** - * @param {cc.Point} a - * @param {cc.Point} b - * @param {Number} variance - * @return {Boolean} if points have fuzzy equality which means equal with some degree of variance. - */ -cc.pFuzzyEqual = function (a, b, variance) { - if (a.x - variance <= b.x && b.x <= a.x + variance) { - if (a.y - variance <= b.y && b.y <= a.y + variance) - return true; - } - return false; -}; - -/** - * Multiplies a nd b components, a.x*b.x, a.y*b.y - * @param {cc.Point} a - * @param {cc.Point} b - * @return {cc.Point} - */ -cc.pCompMult = function (a, b) { - return cc.p(a.x * b.x, a.y * b.y); -}; - -/** - * @param {cc.Point} a - * @param {cc.Point} b - * @return {Number} the signed angle in radians between two vector directions - */ -cc.pAngleSigned = function (a, b) { - var a2 = cc.pNormalize(a); - var b2 = cc.pNormalize(b); - var angle = Math.atan2(a2.x * b2.y - a2.y * b2.x, cc.pDot(a2, b2)); - if (Math.abs(angle) < cc.POINT_EPSILON) - return 0.0; - return angle; -}; - -/** - * @param {cc.Point} a - * @param {cc.Point} b - * @return {Number} the angle in radians between two vector directions - */ -cc.pAngle = function (a, b) { - var angle = Math.acos(cc.pDot(cc.pNormalize(a), cc.pNormalize(b))); - if (Math.abs(angle) < cc.POINT_EPSILON) return 0.0; - return angle; -}; - -/** - * Rotates a point counter clockwise by the angle around a pivot - * @param {cc.Point} v v is the point to rotate - * @param {cc.Point} pivot pivot is the pivot, naturally - * @param {Number} angle angle is the angle of rotation cw in radians - * @return {cc.Point} the rotated point - */ -cc.pRotateByAngle = function (v, pivot, angle) { - var r = cc.pSub(v, pivot); - var cosa = Math.cos(angle), sina = Math.sin(angle); - var t = r.x; - r.x = t * cosa - r.y * sina + pivot.x; - r.y = t * sina + r.y * cosa + pivot.y; - return r; -}; - -/** - * Calculates sum of two points. - * @method pAdd - * @param {Vec2} v1 - * @param {Vec2} v2 - * @return {Vec2} - */ -cc.pAdd = function (v1, v2) { - return cc.p(v1.x + v2.x, v1.y + v2.y); -}; - -/** - * Calculates the square distance between two points (not calling sqrt() ). - * @method pDistanceSQ - * @param {Vec2} point1 - * @param {Vec2} point2 - * @return {Number} - */ -cc.pDistanceSQ = function(point1, point2){ - return cc.pLengthSQ(cc.pSub(point1,point2)); -}; - -/** - * Calculates the distance between two points. - * @method pDistance - * @param {Vec2} v1 - * @param {Vec2} v2 - * @return {Number} - */ -cc.pDistance = function (v1, v2) { - return cc.pLength(cc.pSub(v1, v2)); -}; - -/** - * Calculates difference of two points. - * @method pSub - * @param {Vec2} v1 - * @param {Vec2} v2 - * @return {Vec2} - */ -cc.pSub = function (v1, v2) { - return cc.p(v1.x - v2.x, v1.y - v2.y); -}; - -/** - * Returns opposite of Vec2. - * @method pNeg - * @param {Vec2} point - * @return {Vec2} - */ -cc.pNeg = function (point) { - return cc.p(-point.x, -point.y); -}; - -/** - * Returns point multiplied by given factor. - * @method pMult - * @param {Vec2} point - * @param {Number} floatVar - * @return {Vec2} - */ -cc.pMult = function (point, floatVar) { - return cc.p(point.x * floatVar, point.y * floatVar); -}; - -/** - * Calculates midpoint between two points. - * @method pMidpoint - * @param {Vec2} v1 - * @param {Vec2} v2 - * @return {Vec2} - */ -cc.pMidpoint = function (v1, v2) { - return cc.pMult(cc.pAdd(v1, v2), 0.5); -}; - -/** - * Calculates dot product of two points. - * @method pDot - * @param {Vec2} v1 - * @param {Vec2} v2 - * @return {Number} - */ -cc.pDot = function (v1, v2) { - return v1.x * v2.x + v1.y * v2.y; -}; - -/**_ComponentJS - * Calculates cross product of two points. - * @method pCross - * @param {Vec2} v1 - * @param {Vec2} v2 - * @return {Number} - */ -cc.pCross = function (v1, v2) { - return v1.x * v2.y - v1.y * v2.x; -}; - -/** - * Calculates perpendicular of v, - * rotated 90 degrees counter-clockwise -- cross(v, perp(v)) greater than 0. - * @method pPerp - * @param {Vec2} point - * @return {Vec2} - */ -cc.pPerp = function (point) { - return cc.p(-point.y, point.x); -}; - -/** - * Calculates perpendicular of v, - * rotated 90 degrees clockwise -- cross(v, rperp(v)) smaller than 0. - * @method pRPerp - * @param {Vec2} point - * @return {Vec2} - */ -cc.pRPerp = function (point) { - return cc.p(point.y, -point.x); -}; - -/** - * Calculates the projection of v1 over v2. - * @method pProject - * @param {Vec2} v1 - * @param {Vec2} v2 - * @return {Vec2} - */ -cc.pProject = function (v1, v2) { - return cc.pMult(v2, cc.pDot(v1, v2) / cc.pDot(v2, v2)); -}; - -/** - * Returns this vector with a magnitude of 1. - * @method pNormalize - * @param {Vec2} v - * @return {Vec2} - */ -cc.pNormalize = function (v) { - var n = cc.pLength(v); - return n === 0 ? cc.p(v) : cc.pMult(v, 1.0 / n); -}; - -/** - * Clamp a point between from and to. - * @method pClamp - * @param {Vec2} p - * @param {Vec2} min_inclusive - * @param {Vec2} max_inclusive - * @return {Vec2} - */ -cc.pClamp = function (p, min_inclusive, max_inclusive) { - return cc.p(cc.clampf(p.x, min_inclusive.x, max_inclusive.x), cc.clampf(p.y, min_inclusive.y, max_inclusive.y)); -}; - -/** - * Calculates the square length of a cc.Vec2 (not calling sqrt() ). - * @method pLengthSQ - * @param {Vec2} v - * @return {Number} - */ -cc.pLengthSQ = function (v) { - return cc.pDot(v, v); -}; - -/** - * Calculates distance between point an origin. - * @method pLength - * @param {Vec2} v - * @return {Number} - */ -cc.pLength = function (v) { - return Math.sqrt(cc.pLengthSQ(v)); -}; - -/** - * A general line-line intersection test - * @param {cc.Point} A A is the startpoint for the first line P1 = (p1 - p2). - * @param {cc.Point} B B is the endpoint for the first line P1 = (p1 - p2). - * @param {cc.Point} C C is the startpoint for the second line P2 = (p3 - p4). - * @param {cc.Point} D D is the endpoint for the second line P2 = (p3 - p4). - * @param {cc.Point} retP retP.x is the range for a hitpoint in P1 (pa = p1 + s*(p2 - p1)),
- * retP.y is the range for a hitpoint in P3 (pa = p2 + t*(p4 - p3)). - * @return {Boolean} - * indicating successful intersection of a line
- * note that to truly test intersection for segments we have to make
- * sure that s & t lie within [0..1] and for rays, make sure s & t > 0
- * the hit point is p3 + t * (p4 - p3);
- * the hit point also is p1 + s * (p2 - p1); - */ -cc.pLineIntersect = function (A, B, C, D, retP) { - if ((A.x == B.x && A.y == B.y) || (C.x == D.x && C.y == D.y)) { - return false; - } - var BAx = B.x - A.x; - var BAy = B.y - A.y; - var DCx = D.x - C.x; - var DCy = D.y - C.y; - var ACx = A.x - C.x; - var ACy = A.y - C.y; - - var denom = DCy * BAx - DCx * BAy; - - retP.x = DCx * ACy - DCy * ACx; - retP.y = BAx * ACy - BAy * ACx; - - if (denom == 0) { - if (retP.x == 0 || retP.y == 0) { - // Lines incident - return true; - } - // Lines parallel and not incident - return false; - } - - retP.x = retP.x / denom; - retP.y = retP.y / denom; - - return true; -}; - -/** - * ccpSegmentIntersect return YES if Segment A-B intersects with segment C-D. - * @param {cc.Point} A - * @param {cc.Point} B - * @param {cc.Point} C - * @param {cc.Point} D - * @return {Boolean} - */ -cc.pSegmentIntersect = function (A, B, C, D) { - var retP = cc.p(0, 0); - if (cc.pLineIntersect(A, B, C, D, retP)) - if (retP.x >= 0.0 && retP.x <= 1.0 && retP.y >= 0.0 && retP.y <= 1.0) - return true; - return false; -}; - - -/** - * ccpIntersectPoint return the intersection point of line A-B, C-D - * @param {cc.Point} A - * @param {cc.Point} B - * @param {cc.Point} C - * @param {cc.Point} D - * @return {cc.Point} - */ -cc.pIntersectPoint = function (A, B, C, D) { - var retP = cc.p(0, 0); - - if (cc.pLineIntersect(A, B, C, D, retP)) { - // Point of intersection - var P = cc.p(0, 0); - P.x = A.x + retP.x * (B.x - A.x); - P.y = A.y + retP.x * (B.y - A.y); - return P; - } - - return cc.p(0,0); -}; - -/** - * check to see if both points are equal - * @param {cc.Point} A A ccp a - * @param {cc.Point} B B ccp b to be compared - * @return {Boolean} the true if both ccp are same - */ -cc.pSameAs = function (A, B) { - if ((A != null) && (B != null)) { - return (A.x == B.x && A.y == B.y); - } - return false; -}; - -/** - * sets the position of the point to 0 - */ -cc.pZeroIn = function(v) { - v.x = 0; - v.y = 0; -}; - -/** - * copies the position of one point to another - */ -cc.pIn = function(v1, v2) { - v1.x = v2.x; - v1.y = v2.y; -}; - -/** - * multiplies the point with the given factor (inplace) - */ -cc.pMultIn = function(point, floatVar) { - point.x *= floatVar; - point.y *= floatVar; -}; - -/** - * subtracts one point from another (inplace) - */ -cc.pSubIn = function(v1, v2) { - v1.x -= v2.x; - v1.y -= v2.y; -}; - -/** - * adds one point to another (inplace) - */ -cc.pAddIn = function(v1, v2) { - v1.x += v2.x; - v1.y += v2.y; -}; - -/** - * normalizes the point (inplace) - */ -cc.pNormalizeIn = function(v) { - cc.pMultIn(v, 1.0 / Math.sqrt(v.x * v.x + v.y * v.y)); -}; - -// -// Grid -// -cc._g = function( x, y ) -{ - cc._reuse_grid.x = x; - cc._reuse_grid.y = y; - return cc._reuse_grid; -}; - -// -// Basic structure : Size -// -cc.size = function(w,h) -{ +// Size +cc.size = function (w, h) { + 'use strict'; return {width:w, height:h}; }; -cc._size = function(w,h) -{ - cc._reuse_size.width = w; - cc._reuse_size.height = h; - return cc._reuse_size; -}; -cc.sizeEqualToSize = function (size1, size2) -{ - return ((size1.width == size2.width) && (size1.height == size2.height)); -}; - -cc.SizeZero = function () { - return cc.size(0, 0); -}; - -/** - * create a cc.rect object - * @param {Number|cc.point|cc.rect} [x] a Number value as x or a cc.point object as origin or a cc.rect clone object - * @param {Number|cc.size} [y] x1 a Number value as y or a cc.size object as size - * @param {Number} [w] - * @param {Number} [h] - * @return {Object} a cc.rect object - */ -cc.rect = function(x,y,w,h) -{ +// Rect +cc.rect = function (x, y, w, h) { + 'use strict'; var argLen = arguments.length; if (argLen === 0) return { x: 0, y: 0, width: 0, height: 0 }; @@ -1167,131 +158,9 @@ cc.rect = function(x,y,w,h) throw "unknown argument type"; }; -cc._rect = function(x,y,w,h) -{ - cc._reuse_rect.x = x; - cc._reuse_rect.y = y; - cc._reuse_rect.width = w; - cc._reuse_rect.height = h; - return cc._reuse_rect; -}; -cc.rectEqualToRect = function (rect1, rect2) { - return ( rect1.x==rect2.x && rect1.y==rect2.y && rect1.width==rect2.width && rect1.height==rect2.height); -}; - -cc.rectContainsRect = function (rect1, rect2) { - if ((rect1.x >= rect2.x) || (rect1.y >= rect2.y) || - ( rect1.x + rect1.width <= rect2.x + rect2.width) || - ( rect1.y + rect1.height <= rect2.y + rect2.height)) - return false; - return true; -}; - -cc.rectGetMaxX = function (rect) { - return (rect.x + rect.width); -}; - -cc.rectGetMidX = function (rect) { - return (rect.x + rect.width / 2.0); -}; - -cc.rectGetMinX = function (rect) { - return rect.x; -}; - -cc.rectGetMaxY = function (rect) { - return(rect.y + rect.height); -}; - -cc.rectGetMidY = function (rect) { - return rect.y + rect.height / 2.0; -}; - -cc.rectGetMinY = function (rect) { - return rect.y; -}; - -cc.rectContainsPoint = function (rect, point) { - var ret = false; - if (point.x >= rect.x && point.x <= rect.x + rect.width && - point.y >= rect.y && point.y <= rect.y + rect.height) { - ret = true; - } - return ret; -}; - -cc.rectIntersectsRect = function( rectA, rectB ) -{ - var bool = ! ( rectA.x > rectB.x + rectB.width || - rectA.x + rectA.width < rectB.x || - rectA.y > rectB.y +rectB.height || - rectA.y + rectA.height < rectB.y ); - - return bool; -}; - -cc.rectOverlapsRect = function (rectA, rectB) -{ - return !((rectA.x + rectA.width < rectB.x) || - (rectB.x + rectB.width < rectA.x) || - (rectA.y + rectA.height < rectB.y) || - (rectB.y + rectB.height < rectA.y)); -}; - -cc.rectUnion = function (rectA, rectB) { - var rect = cc.rect(0, 0, 0, 0); - rect.x = Math.min(rectA.x, rectB.x); - rect.y = Math.min(rectA.y, rectB.y); - rect.width = Math.max(rectA.x + rectA.width, rectB.x + rectB.width) - rect.x; - rect.height = Math.max(rectA.y + rectA.height, rectB.y + rectB.height) - rect.y; - return rect; -}; - -cc.rectIntersection = function (rectA, rectB) { - var intersection = cc.rect( - Math.max(rectA.x, rectB.x), - Math.max(rectA.y, rectB.y), - 0, 0); - - intersection.width = Math.min(rectA.x+rectA.width, rectB.x+rectB.width) - intersection.x; - intersection.height = Math.min(rectA.y+rectA.height, rectB.y+rectB.height) - intersection.y; - return intersection; -}; - -cc.RectZero = function () { - return cc.rect(0, 0, 0, 0); -}; - -// Basic structure : Color -cc.Color = function (r, g, b, a) { - this.r = r || 0; - this.g = g || 0; - this.b = b || 0; - this.a = (a === undefined) ? 255 : a; -}; - -/** - * Generate a color object based on multiple forms of parameters - * @example - * - * // 1. All channels separately as parameters - * var color1 = cc.color(255, 255, 255, 255); - * - * // 2. Convert a hex string to a color - * var color2 = cc.color("#000000"); - * - * // 3. An color object as parameter - * var color3 = cc.color({r: 255, g: 255, b: 255, a: 255}); - * - * Alpha channel is optional. Default value is 255 - * - * @param {Number|String|cc.Color} r - * @param {Number} g - * @param {Number} b - * @param {Number} [a=255] - * @returns {cc.Color} - */ +// Color cc.color = function (r, g, b, a) { + 'use strict'; if (r === undefined) return {r: 0, g: 0, b: 0, a: 255}; if (typeof r === "string") @@ -1301,188 +170,8 @@ cc.color = function (r, g, b, a) { return {r: r, g: g, b: b, a: (a === undefined ? 255 : a)}; }; -/** - * returns true if both ccColor3B are equal. Otherwise it returns false. - * @param {cc.Color} color1 - * @param {cc.Color} color2 - * @return {Boolean} true if both ccColor3B are equal. Otherwise it returns false. - */ -cc.colorEqual = function(color1, color2){ - return color1.r === color2.r && color1.g === color2.g && color1.b === color2.b; -}; - -/** - * convert a string of color for style to Color. - * e.g. "#ff06ff" to : cc.color(255,6,255) - * @param {String} hex - * @return {cc.Color} - */ -cc.hexToColor = function (hex) { - hex = hex.replace(/^#?/, "0x"); - var c = parseInt(hex); - var r = c >> 16; - var g = (c >> 8) % 256; - var b = c % 256; - return cc.color(r, g, b); -}; - -/** - * convert Color to a string of color for style. - * e.g. cc.color(255,6,255) to : "#ff06ff" - * @param {cc.Color} color - * @return {String} - */ -cc.colorToHex = function (color) { - var hR = color.r.toString(16); - var hG = color.g.toString(16); - var hB = color.b.toString(16); - var hex = "#" + (color.r < 16 ? ("0" + hR) : hR) + (color.g < 16 ? ("0" + hG) : hG) + (color.b < 16 ? ("0" + hB) : hB); - return hex; -}; - -/** - * White color (255, 255, 255, 255) - * @returns {cc.Color} - * @private - */ -cc.color._getWhite = function(){ - return cc.color(255, 255, 255, 255); -}; - -/** - * Yellow color (255, 255, 0, 255) - * @returns {cc.Color} - * @private - */ -cc.color._getYellow = function () { - return cc.color(255, 255, 0, 255); -}; - -/** - * Blue color (0, 0, 255, 255) - * @type {cc.Color} - * @private - */ -cc.color._getBlue = function () { - return cc.color(0, 0, 255, 255); -}; - -/** - * Green Color (0, 255, 0, 255) - * @type {cc.Color} - * @private - */ -cc.color._getGreen = function () { - return cc.color(0, 255, 0, 255); -}; - -/** - * Red Color (255, 0, 0, 255) - * @type {cc.Color} - * @private - */ -cc.color._getRed = function () { - return cc.color(255, 0, 0, 255); -}; - -/** - * Magenta Color (255, 0, 255, 255) - * @type {cc.Color} - * @private - */ -cc.color._getMagenta = function () { - return cc.color(255, 0, 255, 255); -}; - -/** - * Black Color (0, 0, 0, 255) - * @type {cc.Color} - * @private - */ -cc.color._getBlack = function () { - return cc.color(0, 0, 0, 255); -}; - -/** - * Orange Color (255, 127, 0, 255) - * @type {cc.Color} - * @private - */ -cc.color._getOrange = function () { - return cc.color(255, 127, 0, 255); -}; - -/** - * Gray Color (166, 166, 166, 255) - * @type {cc.Color} - * @private - */ -cc.color._getGray = function () { - return cc.color(166, 166, 166, 255); -}; -var _proto = cc.color; -/** @expose */ -_proto.WHITE; -cc.defineGetterSetter(_proto, "WHITE", _proto._getWhite); -/** @expose */ -_proto.YELLOW; -cc.defineGetterSetter(_proto, "YELLOW", _proto._getYellow); -/** @expose */ -_proto.BLUE; -cc.defineGetterSetter(_proto, "BLUE", _proto._getBlue); -/** @expose */ -_proto.GREEN; -cc.defineGetterSetter(_proto, "GREEN", _proto._getGreen); -/** @expose */ -_proto.RED; -cc.defineGetterSetter(_proto, "RED", _proto._getRed); -/** @expose */ -_proto.MAGENTA; -cc.defineGetterSetter(_proto, "MAGENTA", _proto._getMagenta); -/** @expose */ -_proto.BLACK; -cc.defineGetterSetter(_proto, "BLACK", _proto._getBlack); -/** @expose */ -_proto.ORANGE; -cc.defineGetterSetter(_proto, "ORANGE", _proto._getOrange); -/** @expose */ -_proto.GRAY; -cc.defineGetterSetter(_proto, "GRAY", _proto._getGray); - -// Cocos2d-html5 supports multi scene resources preloading. -// This is a compatible function for JSB. -cc.Loader = cc.Class.extend({ - initWith:function (resources, selector, target) { - if (selector) { - this._selector = selector; - this._target = target; - } - this._selector.call(this._target); - } -}); - -cc.Loader.preload = function (resources, selector, target) { - if (!this._instance) { - this._instance = new cc.Loader(); - } - this._instance.initWith(resources, selector, target); - return this._instance; -}; - -cc.LoaderScene = cc.Loader; - -var ConfigType = { - NONE: 0, - COCOSTUDIO: 1 -}; - -var __onParseConfig = function(type, str) { - if (type === ConfigType.COCOSTUDIO) { - ccs.triggerManager.parse(JSON.parse(str)); - } -}; - +// setTimeout & setInterval var _windowTimeIntervalId = 0; var _windowTimeFunHash = {}; var WindowTimeFun = cc.Class.extend({ @@ -1570,7 +259,7 @@ cc.EventListener.create = function(argObj){ throw "Invalid parameter."; } var listenerType = argObj.event; - delete argObj.event; + argObj.event = undefined; var listener = null; if(listenerType === cc.EventListener.TOUCH_ONE_BY_ONE) { @@ -1585,13 +274,13 @@ cc.EventListener.create = function(argObj){ listener = cc.EventListenerMouse.create(); else if(listenerType === cc.EventListener.CUSTOM){ listener = cc.EventListenerCustom.create(argObj.eventName, argObj.callback); - delete argObj.eventName; - delete argObj.callback; + argObj.eventName = undefined; + argObj.callback = undefined; } else if(listenerType === cc.EventListener.KEYBOARD) listener = cc.EventListenerKeyboard.create(); else if(listenerType === cc.EventListener.ACCELERATION){ listener = cc.EventListenerAcceleration.create(argObj.callback); - delete argObj.callback; + argObj.callback = undefined; }else if(listenerType === cc.EventListener.FOCUS){ listener = cc.EventListenerFocus.create(); } @@ -1600,7 +289,7 @@ cc.EventListener.create = function(argObj){ cc.log("Error: Invalid listener type."); } - for(var key in argObj) { + for (var key in argObj) { // Temporary fix for EventMouse to support getDelta functions (doesn't exist in Cocos2d-x) if (key == "onMouseDown" || key == "onMouseMove") listener["_" + key] = argObj[key]; @@ -1761,15 +450,6 @@ cc.Touch.prototype.getLocationY = function(){ return this.getLocation().y; }; -cc.Director.EVENT_PROJECTION_CHANGED = "director_projection_changed"; -cc.Director.EVENT_AFTER_DRAW = "director_after_draw"; -cc.Director.EVENT_AFTER_VISIT = "director_after_visit"; -cc.Director.EVENT_BEFORE_UPDATE = "director_before_update"; -cc.Director.EVENT_AFTER_UPDATE = "director_after_update"; -cc.Director.EVENT_BEFORE_SCENE_LAUNCH = "director_before_scene_launch"; - -cc.Director.prototype.runScene = cc.Director.prototype.replaceScene; - cc.visibleRect = { topLeft:cc.p(0,0), topRight:cc.p(0,0), @@ -1846,81 +526,6 @@ cc.FontDefinition = function () { }; -// Array utils - -/** - * Verify Array's Type - * @param {Array} arr - * @param {function} type - * @return {Boolean} - * @function - */ -cc.arrayVerifyType = function (arr, type) { - if (arr && arr.length > 0) { - for (var i = 0; i < arr.length; i++) { - if (!(arr[i] instanceof type)) { - cc.log("element type is wrong!"); - return false; - } - } - } - return true; -}; - -/** - * Searches for the first occurrence of object and removes it. If object is not found the function has no effect. - * @function - * @param {Array} arr Source Array - * @param {*} delObj remove object - */ -cc.arrayRemoveObject = function (arr, delObj) { - for (var i = 0, l = arr.length; i < l; i++) { - if (arr[i] == delObj) { - arr.splice(i, 1); - break; - } - } -}; - -/** - * Removes from arr all values in minusArr. For each Value in minusArr, the first matching instance in arr will be removed. - * @function - * @param {Array} arr Source Array - * @param {Array} minusArr minus Array - */ -cc.arrayRemoveArray = function (arr, minusArr) { - for (var i = 0, l = minusArr.length; i < l; i++) { - cc.arrayRemoveObject(arr, minusArr[i]); - } -}; - -/** - * Inserts some objects at index - * @function - * @param {Array} arr - * @param {Array} addObjs - * @param {Number} index - * @return {Array} - */ -cc.arrayAppendObjectsToIndex = function(arr, addObjs,index){ - arr.splice.apply(arr, [index, 0].concat(addObjs)); - return arr; -}; - -/** - * Copy an array's item to a new array (its performance is better than Array.slice) - * @param {Array} arr - * @returns {Array} - */ -cc.copyArray = function(arr){ - var i, len = arr.length, arr_clone = new Array(len); - for (i = 0; i < len; i += 1) - arr_clone[i] = arr[i]; - return arr_clone; -}; - - - // // DrawNode JS API Wrapper // @@ -2133,192 +738,7 @@ cc.TMXLayer.prototype.getPositonAt = function(x, y){ return this._getPositionAt(pos); }; -//LabelTTF -cc.LabelTTF.prototype.initWithString = function(text, fontName, fontSize, dimensions, hAlignment, vAlignment) { - var fontDef = new cc.FontDefinition(); - if(typeof fontName === 'string') fontDef.fontName = fontName; - if(typeof fontSize === 'number') fontDef.fontSize = fontSize; - if(dimensions) { - fontDef.boundingWidth = dimensions.width; - fontDef.boundingHeight = dimensions.height; - } - if(typeof hAlignment === 'number') fontDef.textAlign = hAlignment; - if(typeof vAlignment === 'number') fontDef.verticalAlign = vAlignment; - - this._renderLabel.setFontDefinition(fontDef); - this._renderLabel.setString(text); - this.setContentSize(this._renderLabel.getContentSize()); -}; -cc.LabelTTF.prototype.initWithStringAndTextDefinition = function(text, textDefinition) { - this._renderLabel.setFontDefinition(textDefinition); - this._renderLabel.setString(text); - this.setContentSize(this._renderLabel.getContentSize()); -}; -cc.LabelTTF.prototype.setDimensions = function (arg1, arg2) { - if(arguments.length == 2) { - this._renderLabel.setDimensions(arg1, arg2); - } - else{ - this._renderLabel.setDimensions(arg1.width, arg1.height); - } - this.setContentSize(this._renderLabel.getContentSize()); -}; -cc.LabelTTF.prototype.getDimensions = function() { - return this._renderLabel.getDimensions(); -}; -cc.LabelTTF.prototype.setTextDefinition = function( textDefinition ) { - this._renderLabel.setFontDefinition(textDefinition); - this.setContentSize(this._renderLabel.getContentSize()); -}; -cc.LabelTTF.prototype.getTextDefinition = function() { - return this._renderLabel.getFontDefinition(); -}; -cc.LabelTTF.prototype.enableShadow = function( shadowOffset, shadowOpacity, shadowBlur ) { - this._renderLabel.enableShadow(cc.color(0, 0, 0, 255 * shadowOpacity), shadowOffset); - this.setContentSize(this._renderLabel.getContentSize()); -}; -cc.LabelTTF.prototype.disableShadow = function() { - if (this._renderLabel) { - this._renderLabel.disableEffect(2); - this.setContentSize(this._renderLabel.getContentSize()); - } -}; -cc.LabelTTF.prototype.enableStroke = function( strokeColor, strokeSize ) { - this._renderLabel.enableOutline(cc.color(strokeColor.r, strokeColor.g, strokeColor.b, 255), strokeSize); - this.setContentSize(this._renderLabel.getContentSize()); -}; -cc.LabelTTF.prototype.disableStroke = function() { - if (this._renderLabel) { - this._renderLabel.disableEffect(1); - this.setContentSize(this._renderLabel.getContentSize()); - } -}; -cc.LabelTTF.prototype.setFontFillColor = function( textColor ) { - this._renderLabel.setTextColor(cc.color(textColor.r, textColor.g, textColor.b, 255)); - this.setContentSize(this._renderLabel.getContentSize()); -}; -cc.LabelTTF.prototype.getFontSize = function() { - return this._renderLabel.getSystemFontSize(); -}; -cc.LabelTTF.prototype.setFontSize = function( fontSize ) { - this._renderLabel.setSystemFontSize( fontSize ); - this.setContentSize(this._renderLabel.getContentSize()); -}; -cc.LabelTTF.prototype.getFontName = function() { - return this._renderLabel.getSystemFontName(); -}; -cc.LabelTTF.prototype.setFontName = function( fontName ) { - this._renderLabel.setSystemFontName( fontName ); - this.setContentSize(this._renderLabel.getContentSize()); -}; -cc.LabelTTF.prototype.getString = function() { - return this._renderLabel.getString(); -}; -cc.LabelTTF.prototype.setString = function( text ) { - this._renderLabel.setString( text ); - this.setContentSize(this._renderLabel.getContentSize()); -}; -cc.LabelTTF.prototype.setDrawMode = function() { -}; -cc.LabelTTF.prototype.setFlippedX = function(flippedX) { - if (this._flippedX !== flippedX) { - this._flippedX = flippedX; - if (flippedX) { - this._renderLabel.setScaleX(-1); - } - else { - this._renderLabel.setScaleX(1); - } - } -}; -cc.LabelTTF.prototype.setFlippedY = function(flippedY) { - if (this._flippedY !== flippedY) { - this._flippedY = flippedY; - if (flippedY) { - this._renderLabel.setScaleY(-1); - } - else { - this._renderLabel.setScaleY(1); - } - } -}; -cc.LabelTTF.prototype.getHorizontalAlignment = function() { - return this._renderLabel.getHorizontalAlignment(); -}; -cc.LabelTTF.prototype.setHorizontalAlignment = function(hAlignment) { - this._renderLabel.setHorizontalAlignment(hAlignment); -}; -cc.LabelTTF.prototype.getVerticalAlignment = function() { - return this._renderLabel.getVerticalAlignment(); -}; -cc.LabelTTF.prototype.setVerticalAlignment = function(vAlignment) { - this._renderLabel.setVerticalAlignment(vAlignment); -}; - -cc.LabelTTF.create = function (text, fontName, fontSize, dimensions, hAlignment, vAlignment) { - if(arguments.length == 0) { - return new cc.LabelTTF(); - } - else { - return cc.LabelTTF.createWithFontDefinition(text, fontName, fontSize, dimensions, hAlignment, vAlignment); - } -}; - -cc.LabelTTF.createWithFontDefinition = function (text, fontName, fontSize, dimensions, hAlignment, vAlignment) { - var ret = new cc.LabelTTF(); - - ret.initWithString(text, fontName, fontSize, dimensions, hAlignment, vAlignment); - - return ret; -}; - -//LabelBMFont -cc.LabelBMFont = cc.Label.extend({ - initWithString: function (text, fntFile, width, hAlignment, imageOffset) { - if (imageOffset) { - this.setBMFontFilePath(fntFile, imageOffset); - } - else { - this.setBMFontFilePath(fntFile); - } - if (width && width > 0) - this.setMaxLineWidth(width); - if(hAlignment) - this.setAlignment(hAlignment); - - this.setString(text); - }, - setWidth: function(maxWidth) { - this.setMaxLineWidth(maxWidth); - }, - setFntFile: function (fntFile, imageOffset) { - if (imageOffset) { - this.setBMFontFilePath(fntFile, imageOffset); - } - else { - this.setBMFontFilePath(fntFile); - } - }, - getFntFile: function () { - return this.getBMFontFilePath(); - }, - getChildByTag: function (letterIndex) { - return this.getLetter(letterIndex); - } -}); - -cc.LabelBMFont.create = function (text, fntFile, width, hAlignment, imageOffset) { - if(arguments.length > 0) { - var ret = new cc.LabelBMFont(); - ret.initWithString(text, fntFile, width, hAlignment, imageOffset); - - return ret; - } - else { - return new cc.LabelBMFont(); - } -}; - +cc.TMXLayer.prototype.tileFlagsAt = cc.TMXLayer.prototype.getTileFlagsAt; // // setBlendFunc JS API Wrapper @@ -2328,7 +748,6 @@ var protoHasBlend = [cc.AtlasNode.prototype, cc.DrawNode.prototype, cc.LabelTTF.prototype, cc.SpriteBatchNode.prototype, - cc.LabelBMFont.prototype, cc.LayerColor.prototype, cc.MotionStreak.prototype, cc.Sprite.prototype, @@ -2588,263 +1007,6 @@ cc.Speed.prototype.getSpeed = cc.ActionInterval.prototype.getSpeed = function() } }; -// -//AffineTransform API -// - -/** - * @memberOf cc - * @function - * @param {Number} a - * @param {Number} b - * @param {Number} c - * @param {Number} d - * @param {Number} tx - * @param {Number} ty - */ -cc.AffineTransform = function (a, b, c, d, tx, ty) { - this.a = a; - this.b = b; - this.c = c; - this.d = d; - this.tx = tx; - this.ty = ty; -}; - -/** - * @memberOf cc - * @function - * @param {Number} a - * @param {Number} b - * @param {Number} c - * @param {Number} d - * @param {Number} tx - * @param {Number} ty - * @return {cc.AffineTransform} - * Constructor - */ -cc.affineTransformMake = function (a, b, c, d, tx, ty) { - return {a: a, b: b, c: c, d: d, tx: tx, ty: ty}; -}; - -/** - * @memberOf cc - * @function - * @param {cc.Point} point - * @param {cc.AffineTransform} t - * @return {cc.Point} - * Constructor - */ -cc.pointApplyAffineTransform = function (point, t) { - return {x: t.a * point.x + t.c * point.y + t.tx, y: t.b * point.x + t.d * point.y + t.ty}; -}; - -cc._pointApplyAffineTransform = function (x, y, t) { - return {x: t.a * x + t.c * y + t.tx, - y: t.b * x + t.d * y + t.ty}; -}; - -/** - * @memberOf cc - * @function - * @param {cc.Size} size - * @param {cc.AffineTransform} t - * @return {cc.Size} - * Constructor - */ -cc.sizeApplyAffineTransform = function (size, t) { - return {width: t.a * size.width + t.c * size.height, height: t.b * size.width + t.d * size.height}; -}; - -/** - * @memberOf cc - * @function - * @return {cc.AffineTransform} - * Constructor - */ -cc.affineTransformMakeIdentity = function () { - return {a: 1.0, b: 0.0, c: 0.0, d: 1.0, tx: 0.0, ty: 0.0}; -}; - -/** - * @memberOf cc - * @function - * @return {cc.AffineTransform} - * Constructor - */ -cc.affineTransformIdentity = function () { - return {a: 1.0, b: 0.0, c: 0.0, d: 1.0, tx: 0.0, ty: 0.0}; -}; - -/** - * @memberOf cc - * @function - * @param {cc.Rect} rect - * @param {cc.AffineTransform} anAffineTransform - * @return {cc.Rect} - * Constructor - */ -cc.rectApplyAffineTransform = function (rect, anAffineTransform) { - var top = cc.rectGetMinY(rect); - var left = cc.rectGetMinX(rect); - var right = cc.rectGetMaxX(rect); - var bottom = cc.rectGetMaxY(rect); - - var topLeft = cc._pointApplyAffineTransform(left, top, anAffineTransform); - var topRight = cc._pointApplyAffineTransform(right, top, anAffineTransform); - var bottomLeft = cc._pointApplyAffineTransform(left, bottom, anAffineTransform); - var bottomRight = cc._pointApplyAffineTransform(right, bottom, anAffineTransform); - - var minX = Math.min(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x); - var maxX = Math.max(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x); - var minY = Math.min(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y); - var maxY = Math.max(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y); - - return cc.rect(minX, minY, (maxX - minX), (maxY - minY)); -}; - -cc._rectApplyAffineTransformIn = function(rect, anAffineTransform){ - var top = cc.rectGetMinY(rect); - var left = cc.rectGetMinX(rect); - var right = cc.rectGetMaxX(rect); - var bottom = cc.rectGetMaxY(rect); - - var topLeft = cc._pointApplyAffineTransform(left, top, anAffineTransform); - var topRight = cc._pointApplyAffineTransform(right, top, anAffineTransform); - var bottomLeft = cc._pointApplyAffineTransform(left, bottom, anAffineTransform); - var bottomRight = cc._pointApplyAffineTransform(right, bottom, anAffineTransform); - - var minX = Math.min(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x); - var maxX = Math.max(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x); - var minY = Math.min(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y); - var maxY = Math.max(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y); - - rect.x = minX; - rect.y = minY; - rect.width = maxX - minX; - rect.height = maxY - minY; - return rect; -}; - -/** - * @memberOf cc - * @function - * @param {cc.AffineTransform} t - * @param {Number} tx - * @param {Number}ty - * @return {cc.AffineTransform} - * Constructor - */ -cc.affineTransformTranslate = function (t, tx, ty) { - return { - a: t.a, - b: t.b, - c: t.c, - d: t.d, - tx: t.tx + t.a * tx + t.c * ty, - ty: t.ty + t.b * tx + t.d * ty - }; -}; - -/** - * @memberOf cc - * @function - * @param {cc.AffineTransform} t - * @param {Number} sx - * @param {Number} sy - * @return {cc.AffineTransform} - * Constructor - */ -cc.affineTransformScale = function (t, sx, sy) { - return {a: t.a * sx, b: t.b * sx, c: t.c * sy, d: t.d * sy, tx: t.tx, ty: t.ty}; -}; - -/** - * @memberOf cc - * @function - * @param {cc.AffineTransform} aTransform - * @param {Number} anAngle - * @return {cc.AffineTransform} - * Constructor - */ -cc.affineTransformRotate = function (aTransform, anAngle) { - var fSin = Math.sin(anAngle); - var fCos = Math.cos(anAngle); - - return {a: aTransform.a * fCos + aTransform.c * fSin, - b: aTransform.b * fCos + aTransform.d * fSin, - c: aTransform.c * fCos - aTransform.a * fSin, - d: aTransform.d * fCos - aTransform.b * fSin, - tx: aTransform.tx, - ty: aTransform.ty}; -}; - -/** - * Concatenate `t2' to `t1' and return the result:
- * t' = t1 * t2 - * @memberOf cc - * @function - * @param {cc.AffineTransform} t1 - * @param {cc.AffineTransform} t2 - * @return {cc.AffineTransform} - * Constructor - */ -cc.affineTransformConcat = function (t1, t2) { - return {a: t1.a * t2.a + t1.b * t2.c, //a - b: t1.a * t2.b + t1.b * t2.d, //b - c: t1.c * t2.a + t1.d * t2.c, //c - d: t1.c * t2.b + t1.d * t2.d, //d - tx: t1.tx * t2.a + t1.ty * t2.c + t2.tx, //tx - ty: t1.tx * t2.b + t1.ty * t2.d + t2.ty}; //ty -}; - -/** - * Concatenate a transform matrix to another
- * The results are reflected in the first matrix.
- * t' = t1 * t2 - * @function - * @param {cc.AffineTransform} t1 The first transform object - * @param {cc.AffineTransform} t2 The transform object to concatenate - * @return {cc.AffineTransform} The result of concatenation - */ -cc.affineTransformConcatIn = function (t1, t2) { - var a = t1.a, b = t1.b, c = t1.c, d = t1.d, tx = t1.tx, ty = t1.ty; - t1.a = a * t2.a + b * t2.c; - t1.b = a * t2.b + b * t2.d; - t1.c = c * t2.a + d * t2.c; - t1.d = c * t2.b + d * t2.d; - t1.tx = tx * t2.a + ty * t2.c + t2.tx; - t1.ty = tx * t2.b + ty * t2.d + t2.ty; - return t1; -}; - -/** - * Return true if `t1' and `t2' are equal, false otherwise. - * @memberOf cc - * @function - * @param {cc.AffineTransform} t1 - * @param {cc.AffineTransform} t2 - * @return {Boolean} - * Constructor - */ -cc.affineTransformEqualToTransform = function (t1, t2) { - return ((t1.a === t2.a) && (t1.b === t2.b) && (t1.c === t2.c) && (t1.d === t2.d) && (t1.tx === t2.tx) && (t1.ty === t2.ty)); -}; - -/** - * Get the invert value of an AffineTransform object - * @memberOf cc - * @function - * @param {cc.AffineTransform} t - * @return {cc.AffineTransform} - * Constructor - */ -cc.affineTransformInvert = function (t) { - var determinant = 1 / (t.a * t.d - t.b * t.c); - return {a: determinant * t.d, b: -determinant * t.b, c: -determinant * t.c, d: determinant * t.a, - tx: determinant * (t.c * t.ty - t.d * t.tx), ty: determinant * (t.b * t.tx - t.a * t.ty)}; -}; - // // Node API @@ -2858,6 +1020,8 @@ cc.Node.prototype.getUserData = function () { }; //for compatibility with html5 +cc.Node.prototype.ignoreAnchorPointForPosition = cc.Node.prototype.setIgnoreAnchorPointForPosition; + cc.Node.prototype._setNormalizedPosition = cc.Node.prototype.setNormalizedPosition; cc.Node.prototype.setNormalizedPosition = function(pos, y){ if(y === undefined) @@ -2954,59 +1118,6 @@ cc.Texture2D.prototype.setTexParameters = function (texParams, magFilter, wrapS, cc.Texture2D.prototype.handleLoadedTexture = function (premultiplied) {}; -// -// MenuItem setCallback support target -// -cc.MenuItem.prototype._setCallback = cc.MenuItem.prototype.setCallback; -cc.MenuItem.prototype.setCallback = function (callback, target) { - this._setCallback(callback.bind(target)); -}; - -// -// MenuItemImage support sprite frame name as parameter -// -var _p = cc.MenuItemImage.prototype; -_p._setNormalSpriteFrame = _p.setNormalSpriteFrame; -_p._setSelectedSpriteFrame = _p.setSelectedSpriteFrame; -_p._setDisabledSpriteFrame = _p.setDisabledSpriteFrame; -_p.setNormalSpriteFrame = function(frame) { - if (frame[0] == "#") - frame = cc.spriteFrameCache.getSpriteFrame(frame.substr(1)); - this._setNormalSpriteFrame(frame); -}; -_p.setSelectedSpriteFrame = function(frame) { - if (frame[0] == "#") - frame = cc.spriteFrameCache.getSpriteFrame(frame.substr(1)); - this._setSelectedSpriteFrame(frame); -}; -_p.setDisabledSpriteFrame = function(frame) { - if (frame[0] == "#") - frame = cc.spriteFrameCache.getSpriteFrame(frame.substr(1)); - this._setDisabledSpriteFrame(frame); -}; - -cc.MenuItemToggle.prototype.selectedItem = cc.MenuItemToggle.prototype.getSelectedItem; - -// playMusic searchPaths -if (cc.sys.os === cc.sys.OS_ANDROID && cc.audioEngine) { - cc.audioEngine._playMusic = cc.audioEngine.playMusic; - cc.audioEngine.playMusic = function () { - var args = arguments; - var searchPaths = jsb.fileUtils.getSearchPaths(); - var path = args[0]; - searchPaths.some(function (item) { - var temp = item + '/' + path; - var exists = jsb.fileUtils.isFileExist(temp); - if (exists) { - path = temp; - return true; - } - }); - args[0] = path; - cc.audioEngine._playMusic.apply(cc.audioEngine, args); - }; -} - // // Label overflow // @@ -3063,31 +1174,6 @@ _p.schedule = function (callback, target, interval, repeat, delay, paused, key) this._schedule(callback, target, interval, repeat, delay, paused, key); }; - -cc._NodeGrid = cc.NodeGrid; -cc.NodeGrid = function(rect){ - if (!(this instanceof cc.NodeGrid)){ - cc.error("NodeGrid's constructor can not be called as a function, please use 'new cc.NodeGrid()'"); - return; - } - - if (rect) { - return cc._NodeGrid.create(rect); - } - else { - return cc._NodeGrid.create(); - } -} - -cc.NodeGrid.create = function(rect){ - if (rect) { - return cc._NodeGrid.create(rect); - } - else { - return cc._NodeGrid.create(); - } -} - // // cc.BlendFunc // @@ -3146,3 +1232,22 @@ cc.GLProgram.prototype.setUniformLocationWithMatrix4fv = function(){ this.setUniformLocationWithMatrixfvUnion.apply(this, tempArray); }; +// +// LocalStorage +// +sys.localStorage._setItem = sys.localStorage.setItem; +sys.localStorage.setItem = function(itemKey,itemValue) { + if (typeof itemKey === 'string') { + if(itemValue !== undefined && itemValue !== null) + { + if (typeof itemValue !== 'string') { + cc.log("sys.localStorage.setItem Warning: itemValue[" + itemValue + "] is not string!"); + itemValue = '' + itemValue; + } + sys.localStorage._setItem(itemKey, itemValue); + } + } + else + cc.log("sys.localStorage.setItem Warning: itemKey[" + itemKey + "] is not string!"); +} + diff --git a/native/cocos/scripting/js-bindings/script/jsb_cocos2d_constants.js b/native/cocos/scripting/js-bindings/script/jsb_cocos2d_constants.js deleted file mode 100644 index 42bff9663e..0000000000 --- a/native/cocos/scripting/js-bindings/script/jsb_cocos2d_constants.js +++ /dev/null @@ -1,141 +0,0 @@ -/* -* AUTOGENERATED FILE. DO NOT EDIT IT -* Generated by "generate_jsb.py -c cocos2d_jsb.ini" on 2013-03-10 -* Script version: v0.6 -*/ - -var cc = cc || {}; -cc.Sprite.INDEX_NOT_INITIALIZED = -1; -cc.TMX_ORIENTATION_HEX = 0x1; -cc.TMX_ORIENTATION_ISO = 0x2; -cc.TMX_ORIENTATION_ORTHO = 0x0; -cc.Z_COMPRESSION_BZIP2 = 0x1; -cc.Z_COMPRESSION_GZIP = 0x2; -cc.Z_COMPRESSION_NONE = 0x3; -cc.Z_COMPRESSION_ZLIB = 0x0; -cc.BLEND_DST = 0x303; -cc.BLEND_SRC = 0x1; -cc.DIRECTOR_IOS_USE_BACKGROUND_THREAD = 0x0; -cc.DIRECTOR_MAC_THREAD = 0x0; -cc.DIRECTOR_STATS_INTERVAL = 0.1; -cc.ENABLE_BOX2_D_INTEGRATION = 0x0; -cc.ENABLE_DEPRECATED = 0x1; -cc.ENABLE_GL_STATE_CACHE = 0x1; -cc.ENABLE_PROFILERS = 0x0; -cc.ENABLE_STACKABLE_ACTIONS = 0x1; -cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL = 0x0; -cc.GL_ALL = 0x0; -cc.LABELATLAS_DEBUG_DRAW = 0x0; -cc.LABELBMFONT_DEBUG_DRAW = 0x0; -cc.MAC_USE_DISPLAY_LINK_THREAD = 0x0; -cc.MAC_USE_MAIN_THREAD = 0x2; -cc.MAC_USE_OWN_THREAD = 0x1; -cc.NODE_RENDER_SUBPIXEL = 0x1; -cc.PVRMIPMAP_MAX = 0x10; -cc.SPRITEBATCHNODE_RENDER_SUBPIXEL = 0x1; -cc.SPRITE_DEBUG_DRAW = 0x0; -cc.TEXTURE_ATLAS_USE_TRIANGLE_STRIP = 0x0; -cc.TEXTURE_ATLAS_USE_VAO = 0x1; -cc.USE_L_A88_LABELS = 0x1; -cc.ACTION_TAG_INVALID = -1; -cc.DEVICE_MAC = 0x6; -cc.DEVICE_MAC_RETINA_DISPLAY = 0x7; -cc.DEVICEI_PAD = 0x4; -cc.DEVICEI_PAD_RETINA_DISPLAY = 0x5; -cc.DEVICEI_PHONE = 0x0; -cc.DEVICEI_PHONE5 = 0x2; -cc.DEVICEI_PHONE5_RETINA_DISPLAY = 0x3; -cc.DEVICEI_PHONE_RETINA_DISPLAY = 0x1; -cc.FILE_UTILS_SEARCH_DIRECTORY_MODE = 0x1; -cc.FILE_UTILS_SEARCH_SUFFIX_MODE = 0x0; -cc.FLIPED_ALL = 0xe0000000; -cc.FLIPPED_MASK = 0x1fffffff; -cc.IMAGE_FORMAT_JPEG = 0x0; -cc.IMAGE_FORMAT_PNG = 0x1; -cc.ITEM_SIZE = 0x20; -cc.LABEL_AUTOMATIC_WIDTH = -1; -cc.LINE_BREAK_MODE_CHARACTER_WRAP = 0x1; -cc.LINE_BREAK_MODE_CLIP = 0x2; -cc.LINE_BREAK_MODE_HEAD_TRUNCATION = 0x3; -cc.LINE_BREAK_MODE_MIDDLE_TRUNCATION = 0x5; -cc.LINE_BREAK_MODE_TAIL_TRUNCATION = 0x4; -cc.LINE_BREAK_MODE_WORD_WRAP = 0x0; -cc.MAC_VERSION_10_6 = 0xa060000; -cc.MAC_VERSION_10_7 = 0xa070000; -cc.MAC_VERSION_10_8 = 0xa080000; -cc.MENU_HANDLER_PRIORITY = -128; -cc.MENU_STATE_TRACKING_TOUCH = 0x1; -cc.MENU_STATE_WAITING = 0x0; -cc.NODE_TAG_INVALID = -1; - -cc.ParticleSystem.TYPE_FREE = 0; -cc.ParticleSystem.TYPE_RELATIVE = 1; -cc.ParticleSystem.TYPE_GROUPED = 2; -cc.ParticleSystem.DURATION_INFINITY = -1; -cc.ParticleSystem.MODE_GRAVITY = 0; -cc.ParticleSystem.MODE_RADIUS = 1; -cc.ParticleSystem.START_SIZE_EQUAL_TO_END_SIZE = -1; -cc.ParticleSystem.START_RADIUS_EQUAL_TO_END_RADIUS = -1; - -cc.PRIORITY_NON_SYSTEM_MIN = -2147483647; -cc.ProgressTimer.TYPE_BAR = 0x1; -cc.ProgressTimer.TYPE_RADIAL = 0x0; -cc.RESOLUTION_MAC = 0x1; -cc.RESOLUTION_MAC_RETINA_DISPLAY = 0x2; -cc.RESOLUTION_UNKNOWN = 0x0; -cc.TMX_TILE_DIAGONAL_FLAG = 0x20000000; -cc.TMX_TILE_HORIZONTAL_FLAG = 0x80000000; -cc.TMX_TILE_VERTICAL_FLAG = 0x40000000; - -cc.TEXT_ALIGNMENT_CENTER = 1; -cc.TEXT_ALIGNMENT_RIGHT = 2; -cc.TEXT_ALIGNMENT_LEFT = 0; - -cc.VERTICAL_TEXT_ALIGNMENT_TOP = 0; -cc.VERTICAL_TEXT_ALIGNMENT_CENTER = 1; -cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM = 2; - -cc.TOUCHES_ALL_AT_ONCE = 0x0; -cc.TOUCHES_ONE_BY_ONE = 0x1; -cc.TRANSITION_ORIENTATION_DOWN_OVER = 0x1; -cc.TRANSITION_ORIENTATION_LEFT_OVER = 0x0; -cc.TRANSITION_ORIENTATION_RIGHT_OVER = 0x1; -cc.TRANSITION_ORIENTATION_UP_OVER = 0x0; -cc.UNIFORM_COS_TIME = 0x5; -cc.UNIFORM_MV_MATRIX = 0x1; -cc.UNIFORM_MVP_MATRIX = 0x2; -cc.UNIFORM_P_MATRIX = 0x0; -cc.UNIFORM_RANDOM01 = 0x6; -cc.UNIFORM_SAMPLER = 0x7; -cc.UNIFORM_SIN_TIME = 0x4; -cc.UNIFORM_TIME = 0x3; -cc.UNIFORM_MAX = 0x8; -cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM = 0x2; -cc.VERTICAL_TEXT_ALIGNMENT_CENTER = 0x1; -cc.VERTICAL_TEXT_ALIGNMENT_TOP = 0x0; -cc.OS_VERSION_4_0 = 0x4000000; -cc.OS_VERSION_4_0_1 = 0x4000100; -cc.OS_VERSION_4_1 = 0x4010000; -cc.OS_VERSION_4_2 = 0x4020000; -cc.OS_VERSION_4_2_1 = 0x4020100; -cc.OS_VERSION_4_3 = 0x4030000; -cc.OS_VERSION_4_3_1 = 0x4030100; -cc.OS_VERSION_4_3_2 = 0x4030200; -cc.OS_VERSION_4_3_3 = 0x4030300; -cc.OS_VERSION_4_3_4 = 0x4030400; -cc.OS_VERSION_4_3_5 = 0x4030500; -cc.OS_VERSION_5_0 = 0x5000000; -cc.OS_VERSION_5_0_1 = 0x5000100; -cc.OS_VERSION_5_1_0 = 0x5010000; -cc.OS_VERSION_6_0_0 = 0x6000000; -cc.ANIMATION_FRAME_DISPLAYED_NOTIFICATION = 'CCAnimationFrameDisplayedNotification'; -cc.CHIPMUNK_IMPORT = 'chipmunk.h'; -cc.ATTRIBUTE_NAME_COLOR = 'a_color'; -cc.ATTRIBUTE_NAME_POSITION = 'a_position'; -cc.ATTRIBUTE_NAME_TEX_COORD = 'a_texCoord'; -cc.ATTRIBUTE_NAME_TEX_COORD1 = "a_texCoord1"; -cc.ATTRIBUTE_NAME_TEX_COORD2 = "a_texCoord2"; -cc.ATTRIBUTE_NAME_TEX_COORD3 = "a_texCoord3"; -cc.ATTRIBUTE_NAME_NORMAL = "a_normal"; -cc.ATTRIBUTE_NAME_BLEND_WEIGHT = "a_blendWeight"; -cc.ATTRIBUTE_NAME_BLEND_INDEX = "a_blendIndex"; diff --git a/native/cocos/scripting/js-bindings/script/jsb_cocosbuilder.js b/native/cocos/scripting/js-bindings/script/jsb_cocosbuilder.js deleted file mode 100644 index 07fd31e06d..0000000000 --- a/native/cocos/scripting/js-bindings/script/jsb_cocosbuilder.js +++ /dev/null @@ -1,208 +0,0 @@ -/* - * Copyright (c) 2013-2016 Chukong Technologies Inc. - * - * 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. - */ - -// -// CocosBuilder definitions -// - -cc.BuilderReader = cc.BuilderReader || {}; -cc.BuilderReader._resourcePath = ""; - -cc.BuilderReader._controllerClassCache = {}; -cc.BuilderReader.registerController = function(controllerName, controller){ - cc.BuilderReader._controllerClassCache[controllerName] = cc.Class.extend(controller); -}; - -cc.BuilderReader.setResourcePath = function (rootPath) { - cc.BuilderReader._resourcePath = rootPath; -}; - -cc.BuilderReader.load = function(file, owner, parentSize) -{ - // Load the node graph using the correct function - var reader = cc._Reader.create(); - reader.setCCBRootPath(cc.BuilderReader._resourcePath); - - var node; - - if (parentSize) - { - node = reader.load(file, null, parentSize); - } - else - { - node = reader.load(file); - } - - // Assign owner callbacks & member variables - if (owner) - { - // Callbacks - var ownerCallbackNames = reader.getOwnerCallbackNames(); - var ownerCallbackNodes = reader.getOwnerCallbackNodes(); - - for (var i = 0; i < ownerCallbackNames.length; i++) - { - var callbackName = ownerCallbackNames[i]; - var callbackNode = ownerCallbackNodes[i]; - - if (owner[callbackName] === undefined) - { - cc.log("Warning: " + "owner." + callbackName + " is undefined."); - } - else - { - if(callbackNode instanceof cc.ControlButton) - { - var ownerCallbackControlEvents = reader.getOwnerCallbackControlEvents(); - callbackNode.addTargetWithActionForControlEvents(owner, owner[callbackName], ownerCallbackControlEvents[i]); - } - else - { - callbackNode.setCallback(owner[callbackName], owner); - } - } - } - - // Variables - var ownerOutletNames = reader.getOwnerOutletNames(); - var ownerOutletNodes = reader.getOwnerOutletNodes(); - - for (var i = 0; i < ownerOutletNames.length; i++) - { - var outletName = ownerOutletNames[i]; - var outletNode = ownerOutletNodes[i]; - - owner[outletName] = outletNode; - } - } - - var nodesWithAnimationManagers = reader.getNodesWithAnimationManagers(); - node._nodesWithAnimationManagers = nodesWithAnimationManagers; - var animationManagersForNodes = reader.getAnimationManagersForNodes(); - - var controllerClassCache = cc.BuilderReader._controllerClassCache; - // Attach animation managers to nodes and assign root node callbacks and member variables - for (var i = 0; i < nodesWithAnimationManagers.length; i++) - { - var innerNode = nodesWithAnimationManagers[i]; - var animationManager = animationManagersForNodes[i]; - - innerNode.animationManager = animationManager; - - var controllerName = animationManager.getDocumentControllerName(); - if (!controllerName) continue; - - // Create a controller - var controllerClass = controllerClassCache[controllerName]; - if(!controllerClass) throw "Can not find controller : " + controllerName; - var controller = new controllerClass(); - controller.controllerName = controllerName; - - innerNode.controller = controller; - controller.rootNode = innerNode; - - // Callbacks - var documentCallbackNames = animationManager.getDocumentCallbackNames(); - var documentCallbackNodes = animationManager.getDocumentCallbackNodes(); - innerNode._documentCallbackNodes = documentCallbackNodes; - - for (var j = 0; j < documentCallbackNames.length; j++) - { - var callbackName = documentCallbackNames[j]; - var callbackNode = documentCallbackNodes[j]; - - if (controller[callbackName] === undefined) - { - cc.log("Warning: " + controllerName + "." + callbackName + " is undefined."); - } - else - { - if(callbackNode instanceof cc.ControlButton) - { - var documentCallbackControlEvents = animationManager.getDocumentCallbackControlEvents(); - callbackNode.addTargetWithActionForControlEvents(controller, controller[callbackName], documentCallbackControlEvents[j]); - } - else - { - callbackNode.setCallback(controller[callbackName], controller); - } - } - } - - - // Variables - var documentOutletNames = animationManager.getDocumentOutletNames(); - var documentOutletNodes = animationManager.getDocumentOutletNodes(); - - for (var j = 0; j < documentOutletNames.length; j++) - { - var outletName = documentOutletNames[j]; - var outletNode = documentOutletNodes[j]; - - controller[outletName] = outletNode; - } - - if (typeof(controller.onDidLoadFromCCB) == "function") - { - controller.onDidLoadFromCCB(); - } - - // Setup timeline callbacks - var keyframeCallbacks = animationManager.getKeyframeCallbacks(); - for (var j = 0; j < keyframeCallbacks.length; j++) - { - var callbackSplit = keyframeCallbacks[j].split(":"); - var callbackType = callbackSplit[0]; - var callbackName = callbackSplit[1]; - - if (callbackType == 1) // Document callback - { - var callfunc = cc.CallFunc.create(controller[callbackName], controller); - animationManager.setCallFunc(callfunc, keyframeCallbacks[j]); - } - else if (callbackType == 2 && owner) // Owner callback - { - var callfunc = cc.CallFunc.create(owner[callbackName], owner); - animationManager.setCallFunc(callfunc, keyframeCallbacks[j]); - } - } - - // Start animation - var autoPlaySeqId = animationManager.getAutoPlaySequenceId(); - if (autoPlaySeqId != -1) - { - animationManager.runAnimationsForSequenceIdTweenDuration(autoPlaySeqId, 0); - } - } - - return node; -}; - -cc.BuilderReader.loadAsScene = function(file, owner, parentSize) -{ - var node = cc.BuilderReader.load(file, owner, parentSize); - var scene = cc.Scene.create(); - scene.addChild( node ); - - return scene; -}; diff --git a/native/cocos/scripting/js-bindings/script/jsb_create_apis.js b/native/cocos/scripting/js-bindings/script/jsb_create_apis.js index 5acacbbada..7acfed9bff 100644 --- a/native/cocos/scripting/js-bindings/script/jsb_create_apis.js +++ b/native/cocos/scripting/js-bindings/script/jsb_create_apis.js @@ -20,6 +20,8 @@ * THE SOFTWARE. */ +'use strict'; + /************************************************************ * * Constructors with built in init function @@ -64,19 +66,6 @@ _p._ctor = function(start, end, v, colorStops) { }; -_p = cc.LayerMultiplex.prototype; -_p._ctor = function(layers) { - if(layers !== undefined){ - if (layers instanceof Array) - cc.LayerMultiplex.prototype.initWithArray.call(this, layers); - else - cc.LayerMultiplex.prototype.initWithArray.call(this, Array.prototype.slice.call(arguments)); - }else{ - cc.LayerMultiplex.prototype.init.call(this); - } -}; - - /************************ Sprite *************************/ _p = cc.Sprite.prototype; @@ -108,15 +97,6 @@ _p._ctor = function(fileName, rect) { } }; -_p = cc.SpriteBatchNode.prototype; -_p._ctor = function(fileImage, capacity) { - capacity = capacity || cc.SpriteBatchNode.DEFAULT_CAPACITY; - if (typeof(fileImage) == 'string') - this.initWithFile(fileImage, capacity); - else - this.initWithTexture(fileImage, capacity); -}; - _p = cc.SpriteFrame.prototype; _p._ctor = function(filename, rect, rotated, offset, originalSize){ if(originalSize !== undefined){ @@ -132,168 +112,6 @@ _p._ctor = function(filename, rect, rotated, offset, originalSize){ } }; -/***************************** effect *******************************/ -_p = cc.GridBase.prototype; -_p._ctor = function(gridSize, texture, flipped){ - if(gridSize !== undefined) - this.initWithSize(gridSize, texture, flipped); -}; - -_p = cc.Grid3D.prototype; -_p._ctor = function(gridSize, texture, flipped){ - if(gridSize !== undefined) - this.initWithSize(gridSize, texture, flipped); -}; - -_p = cc.TiledGrid3D.prototype; -_p._ctor = function(gridSize, texture, flipped){ - if(gridSize !== undefined) - this.initWithSize(gridSize, texture, flipped); -}; -/************************ Menu and menu items *************************/ - -_p = cc.Menu.prototype; -_p._ctor = function(menuItems) { - if((arguments.length > 0) && (arguments[arguments.length-1] == null)) - cc.log('parameters should not be ending with null in Javascript'); - - var argc = arguments.length, - items = []; - if (argc == 1) { - if (menuItems instanceof Array) { - items = menuItems; - } - else{ - items.push(arguments[0]); - } - } - else if (argc > 1) { - for (var i = 0; i < argc; i++) { - if (arguments[i]) - items.push(arguments[i]); - } - } - - if(items && items.length > 0) - this.initWithArray(items); - else - this.init(); -}; - - -_p = cc.MenuItem.prototype; -_p._ctor = function(callback, target) { - callback && this.initWithCallback(callback.bind(target)); -}; - -_p = cc.MenuItemLabel.prototype; -_p._ctor = function(label, callback, target) { - callback = callback ? callback.bind(target) : null; - label && this.initWithLabel(label, callback); -}; - -_p = cc.MenuItemAtlasFont.prototype; -_p._ctor = function(value, charMapFile, itemWidth, itemHeight, startCharMap, callback, target) { - callback = callback ? callback.bind(target) : null; - value !== undefined && this.initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, callback); -}; - -_p = cc.MenuItemFont.prototype; -_p._ctor = function(value, callback, target) { - callback = callback ? callback.bind(target) : null; - value !== undefined && this.initWithString(value, callback); -}; - -_p = cc.MenuItemSprite.prototype; -_p._ctor = function(normalSprite, selectedSprite, three, four, five) { - if (normalSprite) { - normalSprite = normalSprite; - selectedSprite = selectedSprite || null; - var disabledSprite, target, callback; - if (five) { - disabledSprite = three; - callback = four; - target = five; - } else if (four && typeof four === 'function') { - disabledSprite = three; - callback = four; - } else if (four && typeof three === 'function') { - target = four; - callback = three; - disabledSprite = normalSprite; - } else if (three === undefined) { - disabledSprite = normalSprite; - } - callback = callback ? callback.bind(target) : null; - this.initWithNormalSprite(normalSprite, selectedSprite, disabledSprite, callback); - } -}; - -_p = cc.MenuItemImage.prototype; -_p._ctor = function(normalImage, selectedImage, three, four, five) { - var disabledImage = null, - callback = null, - target = null; - - if (normalImage === undefined) { - cc.MenuItemImage.prototype.init.call(this); - } - else { - if (four === undefined) { - callback = three; - } - else if (five === undefined) { - if (typeof three === 'function') { - callback = three; - target = four; - } - else { - disabledImage = three; - callback = four; - } - } - else if (five) { - disabledImage = three; - callback = four; - target = five; - } - callback = callback ? callback.bind(target) : null; - var normalSprite = new cc.Sprite(normalImage); - var selectedSprite = new cc.Sprite(selectedImage); - var disabledSprite = disabledImage ? new cc.Sprite(disabledImage) : new cc.Sprite(normalImage); - this.initWithNormalSprite(normalSprite, selectedSprite, disabledSprite, callback); - } -}; - -_p = cc.MenuItemToggle.prototype; -_p._ctor = function() { - var argc = arguments.length, callback, target; - // passing callback. - if (typeof arguments[argc-2] === 'function') { - callback = arguments[argc-2]; - target = arguments[argc-1]; - argc = argc - 2; - } else if(typeof arguments[argc-1] === 'function'){ - callback = arguments[argc-1]; - argc = argc - 1; - } - - if(argc > 0) { - this.initWithItem(arguments[0]); - - for (var i = 1; i < argc; i++) { - if (arguments[i]) - this.addSubItem(arguments[i]); - } - if (callback) - target ? this.setCallback(callback, target) : this.setCallback(callback); - } - else { - callback = callback ? callback.bind(target) : null; - this.initWithCallback(callback); - } -}; - /************************ motion-streak *************************/ _p = cc.MotionStreak.prototype; _p._ctor = function(fade, minSeg, stroke, color, texture){ @@ -336,31 +154,6 @@ cc.ParticleSmoke.prototype._ctor = dummyCtor; cc.ParticleRain.prototype._ctor = dummyCtor; cc.ParticleSnow.prototype._ctor = dummyCtor; - - -/************************ ProgressTimer *************************/ -_p = cc.ProgressTimer.prototype; -_p._ctor = function(sprite){ - sprite !== undefined && this.initWithSprite(sprite); -}; - -/************************ TextFieldTTF *************************/ -_p = cc.TextFieldTTF.prototype; -_p._ctor = function(placeholder, dimensions, alignment, fontName, fontSize){ - if(fontSize !== undefined){ - this.initWithPlaceHolder('', dimensions, alignment, fontName, fontSize); - if(placeholder) - this._placeHolder = placeholder; - } - else if(fontName === undefined && alignment !== undefined){ - fontName = arguments[1]; - fontSize = arguments[2]; - this.initWithString('', fontName, fontSize); - if(placeholder) - this._placeHolder = placeholder; - } -}; - /************************ RenderTexture *************************/ _p = cc.RenderTexture.prototype; _p._ctor = function(width, height, format, depthStencilFormat){ @@ -402,23 +195,6 @@ _p._ctor = function(tmxFile, resourcePath){ } }; -/************************ TransitionScene *************************/ -_p = cc.TransitionScene.prototype; -_p._ctor = function(t, scene){ - if(t !== undefined && scene !== undefined) - this.initWithDuration(t, scene); -}; - -_p = cc.TransitionSceneOriented.prototype; -_p._ctor = function(t, scene, orientation){ - orientation != undefined && this.initWithDuration(t, scene, orientation); -}; - -_p = cc.TransitionPageTurn.prototype; -_p._ctor = function(t, scene, backwards){ - backwards != undefined && this.initWithDuration(t, scene, backwards); -}; - /************************ Actions *************************/ cc.Speed.prototype._ctor = function(action, speed) { @@ -760,10 +536,6 @@ cc.AnimationFrame.prototype._ctor = function(spriteFrame, delayUnits, userInfo) /************************ Nodes *************************/ -cc.AtlasNode.prototype._ctor = function(tile, tileWidth, tileHeight, itemsToRender) { - itemsToRender !== undefined && this.initWithTileFile(tile, tileWidth, tileHeight, itemsToRender); -}; - cc.ClippingNode.prototype._ctor = function(stencil) { if(stencil != undefined) cc.ClippingNode.prototype.init.call(this, stencil); @@ -775,16 +547,6 @@ cc.DrawNode.prototype._ctor = function() { cc.DrawNode.prototype.init.call(this); }; -cc.LabelBMFont.prototype._ctor = function(str, fntFile, width, alignment, imageOffset) { - if( fntFile ) { - str = str || ''; - width = width || 0; - alignment = alignment === undefined ? cc.TEXT_ALIGNMENT_LEFT : alignment; - imageOffset = imageOffset || cc.p(0, 0); - cc.LabelBMFont.prototype.initWithString.call(this, str, fntFile, width, alignment, imageOffset); - } -}; - cc.LabelTTF.prototype._ctor = function(text, fontName, fontSize, dimensions, hAlignment, vAlignment) { this._flippedX = false; this._flippedY = false; @@ -807,7 +569,6 @@ cc.LabelTTF.prototype._ctor = function(text, fontName, fontSize, dimensions, hAl } }; - /************************ Other classes *************************/ cc.EventTouch.prototype._ctor = function(touches) { @@ -824,299 +585,3 @@ cc.GLProgram.prototype._ctor = function(vShaderFileName, fShaderFileName) { cc.GLProgram.prototype.updateUniforms.call(this); } }; - -/************************************************************ - * - * Unified create function - * - ************************************************************/ - -/** - * Create a sprite with image path or frame name or texture or spriteFrame. - * @constructs - * @param {String|cc.Texture2D|cc.SpriteFrame} fileName The string which indicates a path to image file, e.g., 'scene1/monster.png'. - * @param {cc.Rect} rect Only the contents inside rect of pszFileName's texture will be applied for this sprite. - * @return {cc.Sprite} A valid sprite object - * @example - * - * 1.Create a sprite with image path and rect - * var sprite1 = cc.Sprite.create('res/HelloHTML5World.png'); - * var sprite2 = cc.Sprite.create('res/HelloHTML5World.png',cc.rect(0,0,480,320)); - * - * 2.Create a sprite with a sprite frame name. Must add '#' before frame name. - * var sprite = cc.Sprite.create('#grossini_dance_01.png'); - * - * 3.Create a sprite with a sprite frame - * var spriteFrame = cc.spriteFrameCache.getSpriteFrame('grossini_dance_01.png'); - * var sprite = cc.Sprite.create(spriteFrame); - * - * 4.Create a sprite with an existing texture contained in a CCTexture2D object - * After creation, the rect will be the size of the texture, and the offset will be (0,0). - * var texture = cc.textureCache.addImage('HelloHTML5World.png'); - * var sprite1 = cc.Sprite.create(texture); - * var sprite2 = cc.Sprite.create(texture, cc.rect(0,0,480,320)); - * - */ -cc.Sprite.create = function (fileName, rect) { - return new cc.Sprite(fileName, rect); -}; - -cc.SpriteBatchNode._create = cc.SpriteBatchNode.create; -/** - *

- * creates a cc.SpriteBatchNodeCanvas with a file image (.png, .jpg etc) with a default capacity of 29 children.
- * The capacity will be increased in 33% in runtime if it run out of space.
- * The file will be loaded using the TextureMgr.
- *

- * @param {String|cc.Texture2D} fileImage - * @param {Number} capacity - * @return {cc.SpriteBatchNode} - * @example - * 1. - * //create a SpriteBatchNode with image path - * var spriteBatchNode = cc.SpriteBatchNode.create('res/animations/grossini.png', 50); - * 2. - * //create a SpriteBatchNode with texture - * var texture = cc.textureCache.addImage('res/animations/grossini.png'); - * var spriteBatchNode = cc.SpriteBatchNode.create(texture,50); - */ -cc.SpriteBatchNode.create = function(fileName, capacity){ - return new cc.SpriteBatchNode(fileName, capacity); -}; - - -/** - *

- * Create a cc.SpriteFrame with a texture filename, rect, rotated, offset and originalSize in pixels.
- * The originalSize is the size in pixels of the frame before being trimmed. - *

- * @param {String|cc.Texture2D} filename - * @param {cc.Rect} rect if parameters' length equal 2, rect in points, else rect in pixels - * @param {Boolean} rotated - * @param {cc.Point} offset - * @param {cc.Size} originalSize - * @return {cc.SpriteFrame} - * @example - * 1. - * //Create a cc.SpriteFrame with image path - * var frame1 = cc.SpriteFrame.create('res/grossini_dance.png',cc.rect(0,0,90,128)); - * var frame2 = cc.SpriteFrame.create('res/grossini_dance.png',cc.rect(0,0,90,128),false,0,cc.size(90,128)); - * - * 2. - * //Create a cc.SpriteFrame with a texture, rect, rotated, offset and originalSize in pixels. - * var texture = cc.textureCache.addImage('res/grossini_dance.png'); - * var frame1 = cc.SpriteFrame.create(texture, cc.rect(0,0,90,128)); - * var frame2 = cc.SpriteFrame.create(texture, cc.rect(0,0,90,128),false,0,cc.size(90,128)); - */ -cc.SpriteFrame.create = function(fileName, rect, rotated, offset, originalSize){ - return new cc.SpriteFrame(fileName, rect, rotated, offset, originalSize); -}; - - -cc.ParticleSystem._create = cc.ParticleSystem.create; -/** - *

return the string found by key in dict.
- * This plist files can be create manually or with Particle Designer:
- * http://particledesigner.71squared.com/
- *

- * @param {String|Number} plistFile - * @return {cc.ParticleSystem} - */ -cc.ParticleSystem.create = function(plistFile){ - return new cc.ParticleSystem(plistFile); -}; - - -/** - * initializes the particle system with the name of a file on disk (for a list of supported formats look at the cc.Texture2D class), a capacity of particles - * @param {String|cc.Texture2D} fileImage - * @param {Number} capacity - * @return {cc.ParticleBatchNode} - * @example - * 1. - * //Create a cc.ParticleBatchNode with image path and capacity - * var particleBatchNode = cc.ParticleBatchNode.create('res/grossini_dance.png',30); - * - * 2. - * //Create a cc.ParticleBatchNode with a texture and capacity - * var texture = cc.TextureCache.getInstance().addImage('res/grossini_dance.png'); - * var particleBatchNode = cc.ParticleBatchNode.create(texture, 30); - */ -cc.ParticleBatchNode.create = function(fileImage, capacity){ - return new cc.ParticleBatchNode(fileImage, capacity); -}; - - -/** - * Creates a TMX Tiled Map with a TMX file or content string. - * Implementation cc.TMXTiledMap - * @param {String} tmxFile tmxFile fileName or content string - * @param {String} resourcePath If tmxFile is a file name ,it is not required.If tmxFile is content string ,it is must required. - * @return {cc.TMXTiledMap|undefined} - * @example - * //example - * 1. - * //create a TMXTiledMap with file name - * var tmxTiledMap = cc.TMXTiledMap.create('res/orthogonal-test1.tmx'); - * 2. - * //create a TMXTiledMap with content string and resource path - * var resources = 'res/TileMaps'; - * var filePath = 'res/TileMaps/orthogonal-test1.tmx'; - * var xmlStr = cc.loader.getRes(filePath); - * var tmxTiledMap = cc.TMXTiledMap.create(xmlStr, resources); - */ -cc.TMXTiledMap.create = function (tmxFile, resourcePath) { - return new cc.TMXTiledMap(tmxFile, resourcePath); -}; - - -// MenuItems -cc.MenuItem.create = function (callback, target) { - return new cc.MenuItem(callback, target); -}; -cc.MenuItemLabel.create = function (label, selector, target) { - return new cc.MenuItemLabel(label, selector, target); -}; -cc.MenuItemAtlasFont.create = function (value, charMapFile, itemWidth, itemHeight, startCharMap, callback, target) { - return new cc.MenuItemAtlasFont(value, charMapFile, itemWidth, itemHeight, startCharMap, callback, target); -}; -cc.MenuItemFont.create = function (value, callback, target) { - return new cc.MenuItemFont(value, callback, target); -}; -cc.MenuItemSprite.create = function (normalSprite, selectedSprite, three, four, five) { - return new cc.MenuItemSprite(normalSprite, selectedSprite, three, four, five || undefined); -}; -cc.MenuItemImage.create = function(normalImage, selectedImage, three, four, five) { - return new cc.MenuItemImage(normalImage, selectedImage, three, four, five); -}; -cc.MenuItemToggle.create = function(/* var args */) { - var n = arguments.length; - - if (typeof arguments[n-2] === 'function' || typeof arguments[n-1] === 'function') { - var args = Array.prototype.slice.call(arguments); - var obj = null; - if( typeof arguments[n-2] === 'function' ) - obj = args.pop(); - - var func = args.pop(); - - // create it with arguments, - var item = cc.MenuItemToggle._create.apply(this, args); - - // then set the callback - if( obj !== null ) - item.setCallback(func, obj); - else - item.setCallback(func); - return item; - } else { - return cc.MenuItemToggle._create.apply(this, arguments); - } -}; - - -// LayerMultiplex -cc.LayerMultiplex.create = cc.LayerMultiplex.createWithArray = function (layers) { - var result = new cc.LayerMultiplex(); - if(layers !== undefined){ - if (layers instanceof Array) - cc.LayerMultiplex.prototype.initWithArray.call(result, layers); - else - cc.LayerMultiplex.prototype.initWithArray.call(result, Array.prototype.slice.call(arguments)); - }else{ - cc.LayerMultiplex.prototype.init.call(result); - } - return result; -}; - -/** - * Creates an animation. - * @param {Array} frames - * @param {Number} delay - * @param {Number} [loops=1] - * @return {cc.Animation} - * @example - * - * 1.Creates an empty animation - * var animation1 = cc.Animation.create(); - * - * 2.Create an animation with sprite frames , delay and loops. - * var spriteFrames = []; - * var frame = cache.getSpriteFrame('grossini_dance_01.png'); - * spriteFrames.push(frame); - * var animation1 = cc.Animation.create(spriteFrames); - * var animation2 = cc.Animation.create(spriteFrames, 0.2); - * var animation2 = cc.Animation.create(spriteFrames, 0.2, 2); - * - * 3.Create an animation with animation frames , delay and loops. - * var animationFrames = []; - * var frame = new cc.AnimationFrame(); - * animationFrames.push(frame); - * var animation1 = cc.Animation.create(animationFrames); - * var animation2 = cc.Animation.create(animationFrames, 0.2); - * var animation3 = cc.Animation.create(animationFrames, 0.2, 2); - */ -cc.Animation.create = function (frames, delay, loops) { - if(frames === undefined){ - return cc.Animation.createWithAnimationFrames(); - } - else if(frames[0] && frames[0] instanceof cc.AnimationFrame){ - return cc.Animation.createWithAnimationFrames.apply(this, arguments); - } - else if(frames[0] && frames[0] instanceof cc.SpriteFrame){ - delay = delay || 0; - return cc.Animation.createWithSpriteFrames.apply(this, arguments); - } -}; - -cc.Menu.create = function(menuItems) { - if((arguments.length > 0) && (arguments[arguments.length-1] == null)) - cc.log('parameters should not be ending with null in Javascript'); - - var argc = arguments.length, - items = []; - if (argc == 1) { - if (menuItems instanceof Array) { - items = menuItems; - } - else{ - items.push(arguments[0]); - } - } - else if (argc > 1) { - for (var i = 0; i < argc; i++) { - if (arguments[i]) - items.push(arguments[i]); - } - } - return cc.Menu._create.apply(null, items); -}; - -cc.GLProgram.create = function (vShaderFileName, fShaderFileName) { - return new cc.GLProgram(vShaderFileName, fShaderFileName); -}; - -cc.GLProgram.createWithString = function (vShader, fShader) { - var program = new cc.GLProgram(); - program.initWithByteArrays(vShader, fShader); - return program; -}; - -cc.TMXLayer.prototype.tileFlagsAt = cc.TMXLayer.prototype.getTileFlagsAt; - -sys.localStorage._setItem = sys.localStorage.setItem; -sys.localStorage.setItem = function(itemKey,itemValue) { - if (typeof itemKey === 'string') { - if(itemValue !== undefined && itemValue !== null) - { - if (typeof itemValue !== 'string') { - cc.log("sys.localStorage.setItem Warning: itemValue[" + itemValue + "] is not string!"); - itemValue = '' + itemValue; - } - sys.localStorage._setItem(itemKey, itemValue); - } - } - else - cc.log("sys.localStorage.setItem Warning: itemKey[" + itemKey + "] is not string!"); -} - diff --git a/native/cocos/scripting/js-bindings/script/jsb_deprecated.js b/native/cocos/scripting/js-bindings/script/jsb_deprecated.js deleted file mode 100644 index 7372c8c28f..0000000000 --- a/native/cocos/scripting/js-bindings/script/jsb_deprecated.js +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (c) 2013-2016 Chukong Technologies Inc. - * - * 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. - */ - -// Deprecated functions - -var cc = cc || {}; - -(function() { - - var logW = function(old_name, new_name) { - cc.log("\n********** \n"+old_name +" was deprecated, please use "+ new_name +" instead.\n**********"); - }; - - // Deprecated static functions - cc.AnimationCache.purgeSharedAnimationCache = function() { - logW("cc.AnimationCache.purgeSharedAnimationCache", "cc.AnimationCache.destroyInstance"); - cc.AnimationCache.destroyInstance(); - }; - - cc.TextureCache.getInstance = function() { - return cc.Director.getInstance().getTextureCache(); - }; - - // Deprecated member functions - cc.Action.prototype.copy = function() { - logW("cc.Action.copy", "cc.Action.clone"); - return cc.Action.prototype.clone.apply(this, arguments); - }; - - cc.Animation.prototype.copy = function() { - logW("cc.Animation.copy", "cc.Animation.clone"); - return cc.Animation.prototype.clone.apply(this, arguments); - }; - - cc.Node.prototype.nodeToWorldTransform = function() { - logW("cc.Node.nodeToWorldTransform", "cc.Node.getNodeToWorldTransform"); - return cc.Node.prototype.getNodeToWorldTransform.apply(this, arguments); - }; - - cc.Node.prototype.getZOrder = function() { - logW("cc.Node.getZOrder", "cc.Node.getLocalZOrder"); - return cc.Node.prototype.getLocalZOrder.apply(this, arguments); - }; - - cc.Node.prototype.setZOrder = function() { - logW("cc.Node.setZOrder", "cc.Node.setLocalZOrder"); - cc.Node.prototype.setLocalZOrder.apply(this, arguments); - }; - - // Not deprecated in the web engine yet, so no need to log - cc.Node.prototype.ignoreAnchorPointForPosition = cc.Node.prototype.setIgnoreAnchorPointForPosition; - - cc.Node.prototype.nodeToParentTransform = function() { - logW("cc.Node.nodeToParentTransform", "cc.Node.getNodeToParentTransform"); - return cc.Node.prototype.getNodeToParentTransform.apply(this, arguments); - }; - - cc.Node.prototype.worldToNodeTransform = function() { - logW("cc.Node.worldToNodeTransform", "cc.Node.getWorldToNodeTransform"); - return cc.Node.prototype.getWorldToNodeTransform.apply(this, arguments); - }; - - cc.Node.prototype.parentToNodeTransform = function() { - logW("cc.Node.parentToNodeTransform", "cc.Node.getParentToNodeTransform"); - return cc.Node.prototype.getParentToNodeTransform.apply(this, arguments); - }; - - cc.Node.prototype.numberOfRunningActions = function() { - logW("cc.Node.numberOfRunningActions", "cc.Node.getNumberOfRunningActions"); - return cc.Node.prototype.getNumberOfRunningActions.apply(this, arguments); - }; - - cc.Node.prototype.numberOfRunningActionsInTarget = function() { - logW("cc.Node.numberOfRunningActionsInTarget", "cc.Node.getNumberOfRunningActionsInTarget"); - return cc.Node.prototype.getNumberOfRunningActionsInTarget.apply(this, arguments); - }; - - cc.Menu.prototype.setHandlerPriority = function() { - cc.log("cc.Menu.setHandlerPriority was deprecated, 3.0 uses new event dispatcher to dispatch touch event based on draw order, so setHandlerPriority is not needed now."); - }; - - cc.Layer.prototype.setKeypadEnabled = function() { - logW("cc.Layer.setKeypadEnabled", "cc.Layer.setKeyboardEnabled"); - return cc.Layer.prototype.setKeyboardEnabled.apply(this, arguments); - }; - - cc.Layer.prototype.isKeypadEnabled = function() { - logW("cc.Layer.isKeypadEnabled", "cc.Layer.isKeyboardEnabled"); - return cc.Layer.prototype.isKeyboardEnabled.apply(this, arguments); - }; - - cc.registerTargettedDelegate = function() { - logW("cc.registerTargettedDelegate", "cc.registerTargetedDelegate"); - return cc.registerTargetedDelegate.apply(this, arguments); - }; - - cc.Touch.prototype.getId = function(){ - logW("cc.Touch.getId", "cc.Touch.getID"); - return this.getID(); - }; - -})(); diff --git a/native/cocos/scripting/js-bindings/script/jsb_dragonbones.js b/native/cocos/scripting/js-bindings/script/jsb_dragonbones.js deleted file mode 100644 index b85b277fac..0000000000 --- a/native/cocos/scripting/js-bindings/script/jsb_dragonbones.js +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2016 Chukong Technologies Inc. - * - * 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. - */ - -var _proto = dragonBones.CCArmatureDisplay.prototype; -_proto.animation = _proto.getAnimation; - -var slotProto = dragonBones.Slot.prototype; -cc.defineGetterSetter(slotProto, 'childArmature', slotProto.getChildArmature, slotProto.setChildArmature); - -var armatureProto = dragonBones.Armature.prototype; -cc.defineGetterSetter(armatureProto, 'animation', armatureProto.getAnimation, null); -cc.defineGetterSetter(armatureProto, 'display', armatureProto.getDisplay, null); -cc.defineGetterSetter(armatureProto, 'name', armatureProto.getName, null); - -var animationStateProto = dragonBones.AnimationState.prototype; -cc.defineGetterSetter(animationStateProto, 'name', animationStateProto.getName); - -var slotProto = dragonBones.Slot.prototype; -cc.defineGetterSetter(slotProto, 'display', slotProto.getDisplay); - -dragonBones.EventObject.START = "start"; -dragonBones.EventObject.LOOP_COMPLETE = "loopComplete"; -dragonBones.EventObject.COMPLETE = "complete"; -dragonBones.EventObject.FADE_IN = "fadeIn"; -dragonBones.EventObject.FADE_IN_COMPLETE = "fadeInComplete"; -dragonBones.EventObject.FADE_OUT = "fadeOut"; -dragonBones.EventObject.FADE_OUT_COMPLETE = "fadeOutComplete"; -dragonBones.EventObject.FRAME_EVENT = "frameEvent"; -dragonBones.EventObject.SOUND_EVENT = "soundEvent"; - -dragonBones.DragonBones = { - ANGLE_TO_RADIAN : Math.PI / 180, - RADIAN_TO_ANGLE : 180 / Math.PI -}; diff --git a/native/cocos/scripting/js-bindings/script/jsb_loaders.js b/native/cocos/scripting/js-bindings/script/jsb_loaders.js deleted file mode 100644 index 2618872b21..0000000000 --- a/native/cocos/scripting/js-bindings/script/jsb_loaders.js +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Copyright (c) 2014-2016 Chukong Technologies Inc. - * - * 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. - */ - -// -// cocos2d loader plugins. -// -// This helper file should be required after jsb_cocos2d.js -// - -cc._emptyLoader = { - load : function(realUrl, url, res, cb){ - cb && cb(null, null); - return null; - } -}; - -cc.loader.register([ - "mp3", "ogg", "wav", "mp4", "m4a", - "font", "eot", "ttf", "woff", "svg", "gaf" - ], - cc._emptyLoader); - -cc._txtLoader = { - load : function(realUrl, url, res, cb){ - var result = jsb.fileUtils.getStringFromFile(realUrl); - cb && cb(null, result); - return result; - } -}; -cc.loader.register(["txt", "xml", "vsh", "fsh", "tmx", "tsx"], cc._txtLoader); - -cc._jsonLoader = { - load : function(realUrl, url, res, cb){ - var data = jsb.fileUtils.getStringFromFile(realUrl), result; - try{ - result = JSON.parse(data); - }catch(e){ - cc.error(e); - result = null; - } - cb && cb(null, result); - return result; - } -}; -cc.loader.register(["json", "ExportJson"], cc._jsonLoader); - -cc._imgLoader = { - load : function(realUrl, url, res, cb){ - cc.loader.loadImg(realUrl, function(err, img){ - if(err) { - cb && cb(err); - return; - } - cc.loader.cache[url] = img; - cb && cb(null, img); - }); - } -}; -cc.loader.register(["png", "jpg", "bmp","jpeg","gif", "webp"], cc._imgLoader); - -cc._plistLoader = { - load : function(realUrl, url, res, cb){ - var content = jsb.fileUtils.getStringFromFile(realUrl); - var result = cc.plistParser.parse(content); - cb && cb(null, result); - return result; - } -}; -cc.loader.register(["plist"], cc._plistLoader); - -cc._binaryLoader = { - load : function(realUrl, url, res, cb){ - var result = cc.loader.loadBinarySync(realUrl); - cb && cb(null, result); - return result; - } -}; -cc.loader.register(["ccbi"], cc._binaryLoader); - - -cc._fntLoader = { - INFO_EXP : /info [^\n]*(\n|$)/gi, - COMMON_EXP : /common [^\n]*(\n|$)/gi, - PAGE_EXP : /page [^\n]*(\n|$)/gi, - CHAR_EXP : /char [^\n]*(\n|$)/gi, - KERNING_EXP : /kerning [^\n]*(\n|$)/gi, - ITEM_EXP : /\w+=[^ \r\n]+/gi, - INT_EXP : /^[\-]?\d+$/, - - _parseStrToObj : function(str){ - var arr = str.match(this.ITEM_EXP); - var obj = {}; - if(arr){ - for(var i = 0, li = arr.length; i < li; i++){ - var tempStr = arr[i]; - var index = tempStr.indexOf("="); - var key = tempStr.substring(0, index); - var value = tempStr.substring(index + 1); - if(value.match(this.INT_EXP)) value = parseInt(value); - else if(value[0] == '"') value = value.substring(1, value.length - 1); - obj[key] = value; - } - } - return obj; - }, - parseFnt : function(fntStr, url){ - var self = this, fnt = {}; - //padding - var infoObj = self._parseStrToObj(fntStr.match(self.INFO_EXP)[0]); - var paddingArr = infoObj["padding"].split(","); - var padding = { - left : parseInt(paddingArr[0]), - top : parseInt(paddingArr[1]), - right : parseInt(paddingArr[2]), - bottom : parseInt(paddingArr[3]) - }; - - //common - var commonObj = self._parseStrToObj(fntStr.match(self.COMMON_EXP)[0]); - fnt.commonHeight = commonObj["lineHeight"]; - if (cc._renderType === cc._RENDER_TYPE_WEBGL) { - var texSize = cc.configuration.getMaxTextureSize(); - if(commonObj["scaleW"] > texSize.width || commonObj["scaleH"] > texSize.height) - cc.log("cc.LabelBMFont._parseCommonArguments(): page can't be larger than supported"); - } - if(commonObj["pages"] !== 1) cc.log("cc.LabelBMFont._parseCommonArguments(): only supports 1 page"); - - //page - var pageObj = self._parseStrToObj(fntStr.match(self.PAGE_EXP)[0]); - if(pageObj["id"] !== 0) cc.log("cc.LabelBMFont._parseImageFileName() : file could not be found"); - fnt.atlasName = cc.path.changeBasename(url, pageObj["file"]); - - //char - var charLines = fntStr.match(self.CHAR_EXP); - var fontDefDictionary = fnt.fontDefDictionary = {}; - for(var i = 0, li = charLines.length; i < li; i++){ - var charObj = self._parseStrToObj(charLines[i]); - var charId = charObj["id"]; - fontDefDictionary[charId] = { - rect : {x : charObj["x"], y : charObj["y"], width : charObj["width"], height : charObj["height"]}, - xOffset : charObj["xoffset"], - yOffset : charObj["yoffset"], - xAdvance : charObj["xadvance"] - }; - } - - //kerning - var kerningDict = fnt.kerningDict = {}; - var kerningLines = fntStr.match(self.KERNING_EXP); - if(kerningLines){ - for(var i = 0, li = kerningLines.length; i < li; i++){ - var kerningObj = self._parseStrToObj(kerningLines[i]); - kerningDict[(kerningObj["first"] << 16) | (kerningObj["second"] & 0xffff)] = kerningObj["amount"]; - } - } - return fnt; - }, - - load : function(realUrl, url, res, cb){ - var data = jsb.fileUtils.getStringFromFile(realUrl), result = null; - if (data) - result = this.parseFnt(data, url); - cb && cb(null, result); - return result; - } -}; -cc.loader.register(["fnt"], cc._fntLoader); diff --git a/native/cocos/scripting/js-bindings/script/jsb_opengl_constants.js b/native/cocos/scripting/js-bindings/script/jsb_opengl_constants.js index 1a2b892da5..fd51b674bb 100644 --- a/native/cocos/scripting/js-bindings/script/jsb_opengl_constants.js +++ b/native/cocos/scripting/js-bindings/script/jsb_opengl_constants.js @@ -828,45 +828,3 @@ gl.WRITEONLY_RENDERING_QCOM = 0x8823; gl.WRITE_ONLY_OES = 0x88b9; gl.Z400_BINARY_AMD = 0x8740; gl.ZERO = 0x0; - -//------------Shader Name--------------- -/** - * @constant - * @type {String} - */ -cc.SHADER_POSITION_TEXTURECOLOR = "ShaderPositionTextureColor"; -/** - * @constant - * @type {String} - */ -cc.SHADER_POSITION_TEXTURECOLORALPHATEST = "ShaderPositionTextureColorAlphaTest"; -/** - * @constant - * @type {String} - */ -cc.SHADER_POSITION_COLOR = "ShaderPositionColor"; -/** - * @constant - * @type {String} - */ -cc.SHADER_POSITION_TEXTURE = "ShaderPositionTexture"; -/** - * @constant - * @type {String} - */ -cc.SHADER_POSITION_TEXTURE_UCOLOR = "ShaderPositionTexture_uColor"; -/** - * @constant - * @type {String} - */ -cc.SHADER_POSITION_TEXTUREA8COLOR = "ShaderPositionTextureA8Color"; -/** - * @constant - * @type {String} - */ -cc.SHADER_POSITION_UCOLOR = "ShaderPosition_uColor"; -/** - * @constant - * @type {String} - */ -cc.SHADER_POSITION_LENGTHTEXTURECOLOR = "ShaderPositionLengthTextureColor"; diff --git a/native/cocos/scripting/js-bindings/script/jsb_prepare.js b/native/cocos/scripting/js-bindings/script/jsb_prepare.js index b4d807ea7e..3cdabd32e6 100644 --- a/native/cocos/scripting/js-bindings/script/jsb_prepare.js +++ b/native/cocos/scripting/js-bindings/script/jsb_prepare.js @@ -30,12 +30,6 @@ var cc = cc || {}; */ var jsb = jsb || {}; -/** - * The element contains the game canvas - * @type {HTMLDivElement} - */ -cc.container = null; - /** * Iterate over an object or an array, executing a function for each matched element. * @param {object|array} obj @@ -77,69 +71,6 @@ cc.extend = function(target) { return target; }; -/** - * Check the obj whether is function or not - * @param {*} obj - * @returns {boolean} - */ -cc.isFunction = function(obj) { - return typeof obj == 'function'; -}; - -/** - * Check the obj whether is number or not - * @param {*} obj - * @returns {boolean} - */ -cc.isNumber = function(obj) { - return typeof obj == 'number' || Object.prototype.toString.call(obj) == '[object Number]'; -}; - -/** - * Check the obj whether is string or not - * @param {*} obj - * @returns {boolean} - */ -cc.isString = function(obj) { - return typeof obj == 'string' || Object.prototype.toString.call(obj) == '[object String]'; -}; - -/** - * Check the obj whether is array or not - * @param {*} obj - * @returns {boolean} - */ -cc.isArray = function(obj) { - return Array.isArray(obj) || - (typeof obj === 'object' && Object.prototype.toString.call(obj) === '[object Array]'); -}; - -/** - * Check the obj whether is undefined or not - * @param {*} obj - * @returns {boolean} - */ -cc.isUndefined = function(obj) { - return typeof obj === 'undefined'; -}; -/** - * Check the obj whether is object or not - * @param {*} obj - * @returns {boolean} - */ -cc.isObject = function(obj) { - return ( obj !== null && typeof obj === "object" ); -}; - -/** - * Check the url whether cross origin - * @param {String} url - * @returns {boolean} - */ -cc.isCrossOrigin = function (url) { - return false; -}; - /** * Common getter setter configuration function * @function @@ -155,14 +86,6 @@ cc.defineGetterSetter = function (proto, prop, getter, setter){ Object.defineProperty(proto, prop, desc); }; -/** - * Associates a base class with a native superclass - * @function - * @param {object} jsobj subclass - * @param {object} klass superclass - */ -cc.associateWithNative = function( jsobj, superclass_or_instance ) {}; - // // JSB supports 2 official ways to create subclasses // diff --git a/native/cocos/scripting/js-bindings/script/jsb_property_apis.js b/native/cocos/scripting/js-bindings/script/jsb_property_apis.js index bf5d721a58..a129544884 100644 --- a/native/cocos/scripting/js-bindings/script/jsb_property_apis.js +++ b/native/cocos/scripting/js-bindings/script/jsb_property_apis.js @@ -38,11 +38,6 @@ var _proto = cc.Action.prototype; cc.defineGetterSetter(_proto, "tag", _proto.getTag, _proto.setTag); // Overrides -_proto = cc.AtlasNode.prototype; -cc.defineGetterSetter(_proto, "opacity", _proto.getOpacity, _proto.setOpacity); -cc.defineGetterSetter(_proto, "opacityModifyRGB", _proto.isOpacityModifyRGB, _proto.setOpacityModifyRGB); -cc.defineGetterSetter(_proto, "color", _proto.getColor, _proto.setColor); - _proto = cc.Label.prototype; cc.defineGetterSetter(_proto, "size", _proto.getContentSize, _proto.setContentSize); cc.defineGetterSetter(_proto, "width", _proto._getWidth, _proto._setWidth); @@ -70,32 +65,6 @@ cc.defineGetterSetter(_proto, "height", _proto._getHeight, _proto._setHeight); _proto = cc.Sprite.prototype; cc.defineGetterSetter(_proto, "ignoreAnchor", _proto.isIgnoreAnchorPointForPosition, _proto.ignoreAnchorPointForPosition); -_proto = cc.LabelBMFont.prototype; -cc.defineGetterSetter(_proto, "anchorX", _proto._getAnchorX, _proto._setAnchorX); -cc.defineGetterSetter(_proto, "anchorY", _proto._getAnchorY, _proto._setAnchorY); -cc.defineGetterSetter(_proto, "scale", _proto.getScale, _proto.setScale); -cc.defineGetterSetter(_proto, "scaleX", _proto.getScaleX, _proto.setScaleX); -cc.defineGetterSetter(_proto, "scaleY", _proto.getScaleY, _proto.setScaleY); -cc.defineGetterSetter(_proto, "opacityModifyRGB", _proto.isOpacityModifyRGB, _proto.setOpacityModifyRGB); -cc.defineGetterSetter(_proto, "opacity", _proto.getOpacity, _proto.setOpacity); -cc.defineGetterSetter(_proto, "cascadeOpacity", _proto.isCascadeOpacityEnabled, _proto.setCascadeOpacityEnabled); -cc.defineGetterSetter(_proto, "color", _proto.getColor, _proto.setColor); -cc.defineGetterSetter(_proto, "cascadeColor", _proto.isCascadeColorEnabled, _proto.setCascadeColorEnabled); - -_proto = cc.Menu.prototype; -cc.defineGetterSetter(_proto, "opacityModifyRGB", _proto.isOpacityModifyRGB, _proto.setOpacityModifyRGB); -cc.defineGetterSetter(_proto, "opacity", _proto.getOpacity, _proto.setOpacity); -cc.defineGetterSetter(_proto, "cascadeOpacity", _proto.isCascadeOpacityEnabled, _proto.setCascadeOpacityEnabled); -cc.defineGetterSetter(_proto, "color", _proto.getColor, _proto.setColor); -cc.defineGetterSetter(_proto, "cascadeColor", _proto.isCascadeColorEnabled, _proto.setCascadeColorEnabled); - -_proto = cc.MenuItem.prototype; -cc.defineGetterSetter(_proto, "opacityModifyRGB", _proto.isOpacityModifyRGB, _proto.setOpacityModifyRGB); -cc.defineGetterSetter(_proto, "opacity", _proto.getOpacity, _proto.setOpacity); -cc.defineGetterSetter(_proto, "cascadeOpacity", _proto.isCascadeOpacityEnabled, _proto.setCascadeOpacityEnabled); -cc.defineGetterSetter(_proto, "color", _proto.getColor, _proto.setColor); -cc.defineGetterSetter(_proto, "cascadeColor", _proto.isCascadeColorEnabled, _proto.setCascadeColorEnabled); - _proto = cc.MotionStreak.prototype; cc.defineGetterSetter(_proto, "x", _proto.getPositionX, _proto.setPositionX); cc.defineGetterSetter(_proto, "y", _proto.getPositionY, _proto.setPositionY); @@ -111,25 +80,12 @@ cc.defineGetterSetter(_proto, "scale", _proto.getScale, _proto.setScale); cc.defineGetterSetter(_proto, "scaleX", _proto.getScaleX, _proto.setScaleX); cc.defineGetterSetter(_proto, "scaleY", _proto.getScaleY, _proto.setScaleY); -_proto = cc.ProgressTimer.prototype; -cc.defineGetterSetter(_proto, "opacity", _proto.getOpacity, _proto.setOpacity); -cc.defineGetterSetter(_proto, "opacityModifyRGB", _proto.isOpacityModifyRGB, _proto.setOpacityModifyRGB); -cc.defineGetterSetter(_proto, "color", _proto.getColor, _proto.setColor); - -_proto = cc.TextFieldTTF.prototype; -cc.defineGetterSetter(_proto, "string", _proto.getString, _proto.setString); - // Extends var _proto = cc.ClippingNode.prototype; cc.defineGetterSetter(_proto, "alphaThreshold", _proto.getAlphaThreshold, _proto.setAlphaThreshold); cc.defineGetterSetter(_proto, "inverted", _proto.getInverted, _proto.setInverted); cc.defineGetterSetter(_proto, "stencil", _proto.getStencil, _proto.setStencil); -_proto = cc.AtlasNode.prototype; -cc.defineGetterSetter(_proto, "texture", _proto.getTexture, _proto.setTexture); -cc.defineGetterSetter(_proto, "textureAtlas", _proto.getTextureAtlas, _proto.setTextureAtlas); -cc.defineGetterSetter(_proto, "quadsToDraw", _proto.getQuadsToDraw, _proto.setQuadsToDraw); - _proto = cc.Node.prototype; cc.defineGetterSetter(_proto, "x", _proto.getPositionX, _proto.setPositionX); cc.defineGetterSetter(_proto, "y", _proto.getPositionY, _proto.setPositionY); @@ -228,11 +184,6 @@ cc.defineGetterSetter(_proto, "cascadeOpacity", _proto.isCascadeOpacityEnabled, cc.defineGetterSetter(_proto, "color", _proto.getColor, _proto.setColor); cc.defineGetterSetter(_proto, "cascadeColor", _proto.isCascadeColorEnabled, _proto.setCascadeColorEnabled); -_proto = cc.SpriteBatchNode.prototype; -cc.defineGetterSetter(_proto, "textureAtlas", _proto.getTextureAtlas, _proto.setTextureAtlas); -cc.defineGetterSetter(_proto, "descendants", _proto.getDescendants); -cc.defineGetterSetter(_proto, "texture", _proto.getTexture, _proto.setTexture); - _proto = cc.Texture2D.prototype; cc.defineGetterSetter(_proto, "name", _proto.getName); cc.defineGetterSetter(_proto, "pixelFormat", _proto.getPixelFormat); @@ -245,32 +196,6 @@ cc.defineGetterSetter(_proto, "maxS", _proto.getMaxS, _proto.setMaxS); cc.defineGetterSetter(_proto, "maxT", _proto.getMaxT, _proto.setMaxT); cc.defineGetterSetter(cc.Texture2D, "defaultPixelFormat", cc.Texture2D.getDefaultAlphaPixelFormat, cc.Texture2D.setDefaultAlphaPixelFormat); -_proto = cc.LabelBMFont.prototype; -cc.defineGetterSetter(_proto, "string", _proto.getString, _proto.setString); -cc.defineGetterSetter(_proto, "textAlign", _proto._getAlignment, _proto.setAlignment); -cc.defineGetterSetter(_proto, "boundingWidth", _proto._getBoundingWidth, _proto.setBoundingWidth); -cc.defineGetterSetter(_proto, "boundingHeight", _proto._getBoundingHeight, _proto.setBoundingHeight); - -_proto = cc.Menu.prototype; -cc.defineGetterSetter(_proto, "enabled", _proto.getEnabled, _proto.setEnabled); - -_proto = cc.MenuItem.prototype; -cc.defineGetterSetter(_proto, "enabled", _proto.isEnabled, _proto.setEnabled); - -_proto = cc.MenuItemLabel.prototype; -cc.defineGetterSetter(_proto, "string", _proto.getString, _proto.setString); -cc.defineGetterSetter(_proto, "label", _proto.getLabel, _proto.setLabel); -cc.defineGetterSetter(_proto, "disabledColor", _proto.getDisabledColor, _proto.setDisabledColor); - -_proto = cc.MenuItemFont.prototype; -cc.defineGetterSetter(_proto, "fontSize", _proto.fontSize, _proto.setFontSize); -cc.defineGetterSetter(_proto, "fontName", _proto.fontName, _proto.setFontName); - -_proto = cc.MenuItemSprite.prototype; -cc.defineGetterSetter(_proto, "normalImage", _proto.getNormalImage, _proto.setNormalImage); -cc.defineGetterSetter(_proto, "selectedImage", _proto.getSelectedImage, _proto.setSelectedImage); -cc.defineGetterSetter(_proto, "disabledImage", _proto.getDisabledImage, _proto.setDisabledImage); - _proto = cc.ParticleBatchNode.prototype; cc.defineGetterSetter(_proto, "textureAtlas", _proto.getTextureAtlas, _proto.setTextureAtlas); cc.defineGetterSetter(_proto, "texture", _proto.getTexture, _proto.setTexture); @@ -322,14 +247,6 @@ cc.defineGetterSetter(_proto, "totalParticles", _proto.getTotalParticles, _proto cc.defineGetterSetter(_proto, "autoRemoveOnFinish", _proto.getAutoRemoveOnFinish, _proto.setAutoRemoveOnFinish); cc.defineGetterSetter(_proto, "texture", _proto.getTexture, _proto.setTexture); -_proto = cc.ProgressTimer.prototype; -cc.defineGetterSetter(_proto, "midPoint", _proto.getMidpoint, _proto.setMidpoint); -cc.defineGetterSetter(_proto, "barChangeRate", _proto.getBarChangeRate, _proto.setBarChangeRate); -cc.defineGetterSetter(_proto, "type", _proto.getType, _proto.setType); -cc.defineGetterSetter(_proto, "percentage", _proto.getPercentage, _proto.setPercentage); -cc.defineGetterSetter(_proto, "sprite", _proto.getSprite, _proto.setSprite); -cc.defineGetterSetter(_proto, "reverseDir", _proto.isReverseDirection, _proto.setReverseDirection); - _proto = cc.RenderTexture.prototype; cc.defineGetterSetter(_proto, "sprite", _proto.getSprite, _proto.setSprite); cc.defineGetterSetter(_proto, "clearFlags", _proto.getClearFlags, _proto.setClearFlags); @@ -338,10 +255,6 @@ cc.defineGetterSetter(_proto, "clearStencilVal", _proto.getClearStencilVal, _pro cc.defineGetterSetter(_proto, "clearColorVal", _proto.getClearColor, _proto.setClearColor); cc.defineGetterSetter(_proto, "autoDraw", _proto.getAutoDraw, _proto.setAutoDraw); -_proto = cc.NodeGrid.prototype; -cc.defineGetterSetter(_proto, "grid", _proto.getGrid, _proto.setGrid); -cc.defineGetterSetter(_proto, "target", null, _proto.setTarget); - _proto = cc.TMXLayer.prototype; cc.defineGetterSetter(_proto, "tiles", _proto.getTiles, _proto.setTiles); cc.defineGetterSetter(_proto, "tileset", _proto.getTileset, _proto.setTileset); diff --git a/native/cocos/scripting/js-bindings/script/jsb_property_impls.js b/native/cocos/scripting/js-bindings/script/jsb_property_impls.js index d0d8716c22..e1a41292c8 100644 --- a/native/cocos/scripting/js-bindings/script/jsb_property_impls.js +++ b/native/cocos/scripting/js-bindings/script/jsb_property_impls.js @@ -20,6 +20,8 @@ * THE SOFTWARE. */ +'use strict'; + function _safeExtend(obj, list) { for (var key in list) if(!obj[key]) @@ -35,7 +37,7 @@ function _customUndefined(message) { cc.log("Not implemented yet in JSB"); message && cc.log(message); return undefined; - } + }; } var _undefined = { @@ -45,7 +47,7 @@ var _undefined = { }, _shadowUndefined: _customUndefined("Please use enableShadow function"), _strokeUndefined: _customUndefined("Please use enableStroke function") -} +}; _safeExtend(cc.Node.prototype, { _getWidth: function() { @@ -134,14 +136,6 @@ _safeExtend(cc.Sprite.prototype, { } }); -_safeExtend(cc.LabelBMFont.prototype, { - _getAlignment: _undefined._jsbUndefined, - _getBoundingWidth: _undefined._jsbUndefined, - setBoundingWidth: function (width) { - this.setWidth(width); - } -}); - _safeExtend(cc.TMXLayer.prototype, { _getLayerWidth: function() { return this.getLayerSize().width; @@ -210,8 +204,6 @@ _safeExtend(cc.TMXTiledMap.prototype, { } }); - - _safeExtend(cc.Texture2D.prototype, { _getWidth : function(){ return this.getContentSize().width; diff --git a/native/cocos/scripting/js-bindings/script/physicsSprite/jsb_physicsSprite.js b/native/cocos/scripting/js-bindings/script/physicsSprite/jsb_physicsSprite.js deleted file mode 100644 index 3673ef54b4..0000000000 --- a/native/cocos/scripting/js-bindings/script/physicsSprite/jsb_physicsSprite.js +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright (c) 2013-2016 Chukong Technologies Inc. - * - * 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. - */ - -// move from extension -// start -//PhysicsDebugNode -cc.PhysicsDebugNode.create = function( space ) { - var s = space; - if( space.handle !== undefined ) - s = space.handle; - return cc.PhysicsDebugNode._create( s ); -}; - -cc.PhysicsDebugNode.prototype._ctor = function(space){ - this.init(); - var s = space; - if( space.handle !== undefined ) - s = space.handle; - this.setSpace(s); -}; - -cc.PhysicsDebugNode.prototype.setSpace = function( space ) { - var s = space; - if( space.handle !== undefined ) - s = space.handle; - return this._setSpace( s ); -}; - -// physicsSprite -cc.PhysicsSprite.prototype.setBody = function( body ) { - var b = body; - if( body.handle !== undefined ) - b = body.handle; - return this._setCPBody( b ); -}; - -cc.PhysicsSprite.prototype.getBody = function() { - return this.getCPBody(); -}; -// end - -// move from property_impls -// start -_safeExtend(cc.PhysicsSprite.prototype, { - setPositionX: function(x) { - this.setPosition( cc.p(x, this.getPositionY()) ); - }, - setPositionY: function(y) { - this.setPosition( cc.p(this.getPositionX(), y) ); - } -}); -// end - -// move from property_apis -// start -var _proto = cc.PhysicsSprite.prototype; -cc.defineGetterSetter(_proto, "body", _proto.getBody, _proto.setBody); -cc.defineGetterSetter(_proto, "x", _proto.getPositionX, _proto.setPositionX); -cc.defineGetterSetter(_proto, "y", _proto.getPositionY, _proto.setPositionY); -cc.defineGetterSetter(_proto, "rotation", _proto.getRotation, _proto.setRotation); -cc.defineGetterSetter(_proto, "dirty", _proto.isDirty, _proto.setDirty); -// end - -// move from create_apis -// start -/************************ PhysicsSprite *************************/ -var _p = cc.PhysicsSprite.prototype; -_p._ctor = function(fileName, rect){ - if (fileName === undefined) { - cc.PhysicsSprite.prototype.init.call(this); - }else if (typeof(fileName) === "string") { - if (fileName[0] === "#") { - //init with a sprite frame name - var frameName = fileName.substr(1, fileName.length - 1); - var spriteFrame = cc.spriteFrameCache.getSpriteFrame(frameName); - this.initWithSpriteFrame(spriteFrame); - } else { - //init with filename and rect - if(rect) - this.initWithFile(fileName, rect); - else - this.initWithFile(fileName); - } - }else if (typeof(fileName) === "object") { - if (fileName instanceof cc.Texture2D) { - //init with texture and rect - this.initWithTexture(fileName, rect); - } else if (fileName instanceof cc.SpriteFrame) { - //init with a sprite frame - this.initWithSpriteFrame(fileName); - } - } -}; - -cc.PhysicsSprite._create = cc.PhysicsSprite.create; -cc.PhysicsSprite.create = function (fileName, rect) { - var sprite; - - if (arguments.length == 0) { - sprite = cc.PhysicsSprite._create(); - return sprite; - } - - if (typeof(fileName) === "string") { - if (fileName[0] === "#") { - //init with a sprite frame name - var frameName = fileName.substr(1, fileName.length - 1); - var spriteFrame = cc.spriteFrameCache.getSpriteFrame(frameName); - sprite = cc.PhysicsSprite.createWithSpriteFrame(spriteFrame); - } else { - // Create with filename and rect - sprite = rect ? cc.PhysicsSprite._create(fileName, rect) : cc.PhysicsSprite._create(fileName); - } - if (sprite) - return sprite; - else return null; - } - - if (typeof(fileName) === "object") { - if (fileName instanceof cc.Texture2D) { - //init with texture and rect - sprite = rect ? cc.PhysicsSprite.createWithTexture(fileName, rect) : cc.PhysicsSprite.createWithTexture(fileName); - } else if (fileName instanceof cc.SpriteFrame) { - //init with a sprite frame - sprite = cc.PhysicsSprite.createWithSpriteFrame(fileName) - } - if (sprite) - return sprite; - else return null; - } - - return null; -}; -// end - diff --git a/native/cocos/scripting/js-bindings/script/runtime/jsb_runtime.js b/native/cocos/scripting/js-bindings/script/runtime/jsb_runtime.js deleted file mode 100644 index db66d79c8a..0000000000 --- a/native/cocos/scripting/js-bindings/script/runtime/jsb_runtime.js +++ /dev/null @@ -1,1202 +0,0 @@ -cc.INT_MAX = 2147483647; - -//================================================================================================== -var __RTPreloadCallbackMap = {}; -var __RTPreloadIndex = 0; - -runtime.onPreload = function(cbIndex, resultJson) { - if (cbIndex in __RTPreloadCallbackMap) { - var cb = __RTPreloadCallbackMap[cbIndex]; - if (cb) { - var status = JSON.parse(resultJson); - cb(status); - } - } -}; - -runtime.onPreloadDone = function(cbIndex, resultJson) { - if (cbIndex in __RTPreloadCallbackMap) { - var cb = __RTPreloadCallbackMap[cbIndex]; - if (cb) { - var status = JSON.parse(resultJson); - cb(status); - } - - delete __RTPreloadCallbackMap[cbIndex]; - } -}; - -runtime.preload = function(gameRes, preload_cb, target) { - __RTPreloadIndex++; - if (target == null) { - __RTPreloadCallbackMap[__RTPreloadIndex] = preload_cb; - } - else { - __RTPreloadCallbackMap[__RTPreloadIndex] = preload_cb.bind(target); - } - - runtime.__preload(gameRes, __RTPreloadIndex); -}; -//================================================================================================== -cc.loader.loadImg = function(url, option, cb){ - if (this._imageArray == undefined) { - this._imageArray = []; - } - - var l = arguments.length; - if (l == 2) cb = option; - if (url.match(jsb.urlRegExp)) { - var picName; - var picSuffix = [".png", ".jpg", ".jpeg", ".gif", ".bmp"]; - var hasSuffix = false; - var suffix; - - for (var i = 0; i < picSuffix.length; i++) { - var item = picSuffix[i]; - if (url.indexOf(item) != -1) { - hasSuffix = true; - suffix = item; - break; - } - } - var conf = l == 2 ? null : option; - if (conf) { - picName = cc.md5Encode(url + "cocos" + conf.width + "_" + conf.height); - } else { - cc.log("download default image"); - picName = cc.md5Encode(url); - } - cc.log("picName is " + picName); - var imageConfig = conf; - var cachedTex = cc.textureCache._addImage(picName); - if (cachedTex instanceof cc.Texture2D) { - cc.log("loadImg find texture from cache"); - cb && cb(null, cachedTex); - } else { - var listItem = this._getDownloadItem(picName); - if (listItem) { - cc.log("the same picture is downloading"); - listItem.cb.push(cb); - return; - } else { - listItem = this._addDownloadList(url, picName, suffix, imageConfig, cb); - } - var self = this; - jsb.loadRemoteImg(JSON.stringify(listItem.info), function (configJsonText) { - var config = JSON.parse(configJsonText); - cc.log("callback from loadRemoteImg config is " + configJsonText); - var item = self._getDownloadItem(config.picName); - if (!item && cb) { - cb("Load image failed", null); - return; - } - if (item.cb) { - for (var i = 0; i < item.cb.length; i++) { - cc.log("in callback list now i is " + i); - var texture = null; - var error = null; - if (config.isSuccess) { - cc.log("begin load texture picName is " + item.info.picName); - texture = cc.textureCache._addImage(item.info.picName); - if(!texture instanceof cc.Texture2D){ - texture = null; - error = "add image fail"; - } - } else { - error = "download image fail"; - } - var cbItem = item.cb[i]; - if (cbItem) { - cbItem(error, texture); - } else { - cc.log("ERROR:callback is null"); - } - } - } - self._delDownloadList(item); - }); - } - } else { - var tex = cc.textureCache._addImage(url); - if (tex instanceof cc.Texture2D) - cb && cb(null, tex); - else cb && cb("Load image failed"); - } -}; - -cc.loader._addDownloadList = function (url,picName,suffix,option,cb) { - var item = { - info: { - url: url, - suffix:suffix, - picName:picName, - option: option - }, - cb: [cb] - }; - this._imageArray.push(item); - return item; -}; - -cc.loader._getDownloadItem = function (picName) { - var imgArray = this._imageArray; - for (var i = 0, l = imgArray.length; i < l; i++) { - var item = imgArray[i]; - if (item.info.picName == picName) { - return item; - } - } - return null; -}; - -cc.loader._delDownloadList = function (picName) { - var imgArray = this._imageArray; - for (var i = 0, l = imgArray.length; i < l; i++) { - var item = imgArray[i]; - if (item.info.picName == picName) { - this._imageArray.splice(i,1); - break; - } - } -}; - -//================================================================================================== -cc.network = cc.network||{}; -cc.network.type = { - NO_NETWORK:-1, - MOBILE:0, - WIFI:1 -}; - -cc.network.preloadstatus = { - DOWNLOAD:1, - UNZIP:2 -}; - -cc.network.getNetworkType = function () { - return runtime.getNetworkType(); -}; - -cc.LoaderLayer = cc.Layer.extend({ - _backgroundSprite: null, - _progressBackgroundSprite: null, - _progressBarSprite: null, - _logoSprite: null, - _titleSprite: null, - _groupname: null, - _callback: null, - _selector: null, - _preloadCount: 0, - _isPreloadFromFailed: false, - _progressOriginalWidth: 0, - _isDefaultProgress: true, - _isLandScape: false, - _scaleFactor: null, - - ctor: function (config) { - this._super(); - this._setConfig(config); - }, - _setConfig: function (config) { - if (config) { - cc.LoaderLayer._userConfig = config; - } - }, - ignoreTouch: function(touch, event) { - - }, - onEnter: function () { - this._super(); - this.initData(); - this.initView(); - var config = this._finalConfig; - if (config.onEnter) { - config.onEnter(this); - } - cc.eventManager.addListener({ - event: cc.EventListener.TOUCH_ONE_BY_ONE, - swallowTouches: true, - onTouchBegan: function(touch, event){ - return true; - }, - onTouchMoved: this.ignoreTouch, - onTouchEnded: this.ignoreTouch, - onTouchCancelled: this.ignoreTouch - }, this); - }, - onExit: function () { - this._super(); - var config = this._finalConfig; - if (config.logo.action) { - config.logo.action.release(); - } - if(config.title.action){ - config.title.action.release(); - } - if (config.onExit) { - config.onExit(this); - } - }, - initData: function () { - this._finalConfig = cc.cloneObject(cc.LoaderLayer._config); - var config = this._finalConfig; - if (cc.LoaderLayer._userConfig != null) { - var uConfig = cc.LoaderLayer._userConfig; - if (uConfig.background && uConfig.background.res) { - config.background.res = uConfig.background.res; - } - if (uConfig.title) { - var uTitle = uConfig.title; - var title = config.title; - title.show = typeof uTitle.show != "undefined" ? uTitle.show : title.show; - title.res = uTitle.res ? uTitle.res : title.res; - title.position = uTitle.position ? uTitle.position : title.position; - title.action = uTitle.action ? uTitle.action : title.action; - if (title.action) { - title.action = uTitle.action; - title.action.retain(); - } - } - if (uConfig.logo) { - var uLogo = uConfig.logo; - var logo = config.logo; - logo.show = typeof uLogo.show != "undefined" ? uLogo.show : logo.show; - logo.res = uLogo.res ? uLogo.res : logo.res; - logo.position = uLogo.position ? uLogo.position : logo.position; - if (typeof uLogo.action != "undefined") { - logo.action = uLogo.action; - if (logo.action) { - logo.action.retain(); - } - } - } - if (uConfig.progressBar) { - var uProgress = uConfig.progressBar; - var progress = config.progressBar; - progress.show = typeof uProgress.show != "undefined" ? uProgress.show : progress.show; - if (uProgress.res) { - progress.res = uProgress.res; - this._isDefaultProgress = false; - } - progress.offset = uProgress.offset ? uProgress.offset : progress.offset; - progress.position = uProgress.position ? uProgress.position : progress.position; - progress.barBackgroundRes = uProgress.barBackgroundRes ? uProgress.barBackgroundRes : progress.barBackgroundRes; - } - if (uConfig.tips) { - var uTips = uConfig.tips; - var tips = config.tips; - tips.show = typeof uTips.show != "undefined" ? uTips.show : tips.show; - tips.res = uTips.res ? uTips.res : tips.res; - tips.offset = uTips.offset ? uTips.offset : tips.offset; - tips.fontSize = uTips.fontSize ? uTips.fontSize : tips.fontSize; - tips.position = uTips.position ? uTips.position : tips.position; - tips.color = uTips.color ? uTips.color : tips.color; - if (uConfig.tips.tipsProgress && typeof uConfig.tips.tipsProgress == "function") { - tips.tipsProgress = uConfig.tips.tipsProgress; - } - } - if (typeof uConfig.onEnter == "function") { - config.onEnter = uConfig.onEnter; - } - if (typeof uConfig.onExit == "function") { - config.onExit = uConfig.onExit; - } - } - - if (typeof config.logo.action == "undefined" && cc.LoaderLayer._useDefaultSource) { - config.logo.action = cc.sequence( - cc.spawn(cc.moveBy(0.4, cc.p(0, 40)).easing(cc.easeIn(0.5)), cc.scaleTo(0.4, 0.95, 1.05).easing(cc.easeIn(0.5))), - cc.delayTime(0.08), - cc.spawn(cc.moveBy(0.4, cc.p(0, -40)).easing(cc.easeOut(0.5)), cc.scaleTo(0.4, 1.05, 0.95).easing(cc.easeOut(0.5))) - ).repeatForever(); - config.logo.action.retain(); - } - if (!config.tips.color) { - config.tips.color = cc.color(255, 255, 255); - } - }, - initView: function () { - var config = this._finalConfig; - this._contentLayer = new cc.Layer(); - this._isLandScape = cc.winSize.width > cc.winSize.height; - this._scaleFactor = !cc.LoaderLayer._useDefaultSource ? 1 : cc.winSize.width > cc.winSize.height ? cc.winSize.width / 720 : cc.winSize.width / 480; - - //background - this.backgroundSprite = new cc.Sprite(config.background.res); - this.addChild(this.backgroundSprite); - this.backgroundSprite.x = 0, this.backgroundSprite.y = 0, this.backgroundSprite.anchorX = 0, this.backgroundSprite.anchorY = 0; - if (cc.LoaderLayer._useDefaultSource) { - this.backgroundSprite.scaleX = cc.winSize.width / this.backgroundSprite.width; - this.backgroundSprite.scaleY = cc.winSize.height / this.backgroundSprite.height; - } - - //title - if (config.title.show) { - this.titleSprite = new cc.Sprite(config.title.res); - var defaultTitlePosition = cc.pAdd(cc.visibleRect.center, cc.p(0, this._scaleFactor < 1 ? 0 : this._isLandScape ? -80 : 30)); - this.titleSprite.setPosition(config.title.position ? config.title.position : defaultTitlePosition); - this._contentLayer.addChild(this.titleSprite); - if (config.title.action) { - this.titleSprite.runAction(config.title.action); - } - } - - //logo - if (config.logo.show) { - this.logoSprite = new cc.Sprite(config.logo.res); - var defaultLogoPosition = cc.pAdd(cc.visibleRect.top, cc.p(0, this._scaleFactor < 1 ? 0 : -this.logoSprite.height / 2 - (this._isLandScape ? 56 : 76))); - this.logoSprite.setPosition(config.logo.position ? config.logo.position : defaultLogoPosition); - this._contentLayer.addChild(this.logoSprite); - if (config.logo.action) { - this.logoSprite.runAction(config.logo.action); - } - } - - //progressbar - if (config.progressBar.show) { - this.progressBarSprite = new cc.Sprite(config.progressBar.res); - this._progressOriginalWidth = this.progressBarSprite.width; - this.progressBackgroundSprite = new cc.Sprite(config.progressBar.barBackgroundRes); - this.progressBarSprite.anchorX = 0; - this.progressBarSprite.anchorY = 0; - if (this._isDefaultProgress) { - this._barPoint = new cc.Sprite(config.progressBar.barPoint); - this.progressBarSprite.addChild(this._barPoint); - } - if (config.progressBar.barBackgroundRes == null) { - this.progressBackgroundSprite.setTextureRect(cc.rect(0, 0, this.progressBarSprite.width, this.progressBarSprite.height)); - } - if (config.progressBar.offset == null) { - var deltaProgressWithX = (this.progressBackgroundSprite.width - this.progressBarSprite.width) / 2; - var deltaProgressWithY = (this.progressBackgroundSprite.height - this.progressBarSprite.height) / 2; - config.progressBar.offset = cc.p(deltaProgressWithX, deltaProgressWithY); - } - this.progressBarSprite.setPosition(config.progressBar.offset); - this.progressBackgroundSprite.addChild(this.progressBarSprite); - var defaultProgressPosition = cc.pAdd(cc.visibleRect.bottom, cc.p(0, this.progressBarSprite.height / 2 + this._isLandScape ? 60 : 80)); - this.progressBackgroundSprite.setPosition(config.progressBar.position ? config.progressBar.position : defaultProgressPosition); - this._contentLayer.addChild(this.progressBackgroundSprite); - this._setProgress(0); - } - - //tips - if (config.tips.show) { - this.tipsLabel = new cc.LabelTTF("100%", "Arial", config.tips.fontSize); - this.tipsLabel.setColor(config.tips.color ? config.tips.color : cc.color(255, 255, 255)); - this.tipsLabel.setPosition(config.tips.position ? config.tips.position : this.progressBackgroundSprite ? cc.p(this.progressBackgroundSprite.x, this.progressBackgroundSprite.y + this.progressBackgroundSprite.height / 2 + 20) : cc.pAdd(cc.visibleRect.bottom, cc.p(0, 100))); - this._contentLayer.addChild(this.tipsLabel); - } - this.addChild(this._contentLayer); - if (this._scaleFactor < 1) { - this._contentLayer.setScale(this._scaleFactor); - this._contentLayer.setPosition(cc.pAdd(this._contentLayer.getPosition(), cc.p(0, -50))); - } - - }, - _setProgress: function (percent) { - if (this.progressBarSprite) { - percent = percent < 1 ? percent : 1; - var width = percent * this._progressOriginalWidth; - this.progressBarSprite.setTextureRect(cc.rect(0, 0, width, this.progressBarSprite.height)); - if (this._isDefaultProgress) { - this._barPoint.setPosition(cc.p(this.progressBarSprite.width, this.progressBarSprite.height / 2)); - } - } - }, - setTipsString: function (str) { - if (this.tipsLabel != null) { - this.tipsLabel.setString(str); - } - }, - getProgressBar: function () { - return this.progressBarSprite; - }, - getTipsLabel: function () { - return this.tipsLabel; - }, - getLogoSprite: function () { - return this.logoSprite; - }, - getTitleSprite: function () { - return this.titleSprite; - }, - updateGroup: function (groupname, callback, target) { - this._groupname = groupname; - this._callback = callback; - this._selector = target; - }, - _resetLoadingLabel: function () { - this.setTipsString(""); - this._setProgress(0); - }, - _preloadSource: function () { - cc.log("_preloadSource: " + this._groupname); - this._resetLoadingLabel(); - if (cc.sys.isNative) { - runtime.preload(this._groupname, this._preload_native, this); - } else { - this._preload_html5(); - } - }, - _preload_html5: function () { - var res = ""; - var groupIndex = []; - var config = this._finalConfig; - if (cc.isString(this._groupname)) { - if (this._groupname.indexOf(".") != -1) { - res = [this._groupname]; - } else { - res = window[this._groupname]; - } - } else if (cc.isArray(this._groupname)) { - res = []; - for (var i = 0; i < this._groupname.length; i++) { - var group = window[this._groupname[i]]; - var preCount = i > 0 ? groupIndex[i - 1] : 0; - groupIndex.push(preCount + group.length); - res = res.concat(group); - } - } - var self = this; - //var progressFunction = self.config.progressCallback ? self.config.progressCallback : null; - cc.loader.load(res, function (result, count, loadedCount) { - var checkGroupName = function (loadedCount) { - for (var i = 0; i < groupIndex.length; i++) { - if (groupIndex[i] >= loadedCount) { - return self._groupname[i]; - } - } - return ""; - }; - var groupName = checkGroupName(loadedCount); - var status = { - groupName: groupName, - isCompleted: false, - percent: (loadedCount / count * 100) | 0,//(float), - stage: 1, //(1č”Øē¤ŗę­£åœØäø‹č½½ļ¼Œ2 č”Øē¤ŗę­£åœØč§£åŽ‹) - isFailed: false - }; - if (status.percent != 0) { - self._setProgress(status.percent / 100); - } - config.tips.tipsProgress(status, self); - }, function () { - self.removeFromParent(); - self._preloadCount--; - if (self._callback) { - if (self._selector) { - self._callback(self._selector, true); - } else { - self._callback(true); - } - } - self._callback.call(this._target, !status.isFailed); - }); - }, - _preload_native: function (status) { - var config = this._finalConfig; - if (status.percent) { - this._setProgress(status.percent / 100); - } - if (config.tips.tipsProgress) { - config.tips.tipsProgress(status, this); - } - if (status.isCompleted || status.isFailed) { - this._preloadCount--; - - if (status.isCompleted) { - cc.log("preload finish!"); - this._isPreloadFromFailed = false; - } - if (status.isFailed) { - cc.log("preload failed!"); - this._isPreloadFromFailed = true; - } - - // Remove loading layer from scene after loading was done. - if (this._preloadCount == 0 && !this._isPreloadFromFailed) { - this.removeFromParent(); - if (cc.LoaderLayer._useDefaultSource) { - var _config = cc.runtime.config.design_resolution || {width: 480, height: 720, policy: "SHOW_ALL"}; - cc.view.setDesignResolutionSize(_config.width, _config.height, cc.ResolutionPolicy[_config.policy]); - } - } - - // Callback must be invoked after removeFromParent. - this._callback.call(this._target, status); - } - }, - _addToScene: function () { - if (this._preloadCount == 0 && !this._isPreloadFromFailed) { - if (cc.sys.isNative && cc.LoaderLayer._useDefaultSource) { - var config = cc.runtime.config.design_resolution; - var isLandscape = false; - var isLargeThanResource = false; - if (config) { - var orientation = cc.runtime.config.orientation; - cc.log("_addToScene orientation is " + orientation); - if (orientation == "landscape") { - isLandscape = true; - isLargeThanResource = config.width > 720 || config.height > 480; - } else { - isLargeThanResource = config.width > 480 || config.height > 720; - } - } - cc.log("isLargeThanResource is " + isLargeThanResource); - cc.view.setDesignResolutionSize(isLargeThanResource ? config.width : isLandscape ? 720 : 480, isLargeThanResource ? config.height : isLandscape ? 480 : 720, cc.ResolutionPolicy["FIXED_HEIGHT"]); - } - cc.director.getRunningScene().addChild(this, cc.INT_MAX - 1);// -1 是防止dialogå…ˆå¼¹å‡ŗę„ęŠŠloaderlayer遮住 - } - this._preloadCount++; - } -}); - -cc.LoaderLayer._config = {//é»˜č®¤ēš„č®¾ē½® - background: { - res: "res_engine/preload_bg.jpg" - }, - title: { - show: true, - res: "res_engine/preload_title.png", - position: null, - action: null - }, - logo: { - res: "res_engine/preload_logo.png", - show: true, - position: null - }, - progressBar: { - show: true, - res: "res_engine/progress_bar.png",//progressBar 图片 - offset: null,//loadingbaråē§»loadingbarčƒŒę™Æēš„offset - position: null,//loadbaråœØę•“äøŖlayeräø­ēš„ä½ē½® - barBackgroundRes: "res_engine/progress_bg.png",//progressBar čƒŒę™Æå›¾ē‰‡ - barPoint: "res_engine/progress_light.png", - barShadow: "res_engine/shadow.png" - }, - tips: { - show: true, - fontSize: 22, - position: null, - color: null, - tipsProgress: function (status, loaderlayer) { - if (loaderlayer.getTipsLabel()) { - var statusStr = "正在"; - if (status.stage == cc.network.preloadstatus.DOWNLOAD) { - statusStr += "äø‹č½½"; - } else if (status.stage == cc.network.preloadstatus.UNZIP) { - statusStr += "č§£åŽ‹"; - } - if (status.groupName) { - statusStr += status.groupName; - } - statusStr += "进度:" + status.percent.toFixed(2) + "%"; - loaderlayer.getTipsLabel().setString(statusStr); - } - } - }, - progressCallback: function (progress) {//čæ›åŗ¦ę›“ę–°å›žč°ƒ - - }, - onEnter: function (layer) { - cc.log("LoaderLayer onEnter"); - }, - onExit: function (layer) { - cc.log("LoaderLayer onExit"); - } -}; - -cc.LoaderLayer.preload = function (groupname, callback, target) { - var loaderLayer = new cc.LoaderLayer(); - var preloadCb = function (status) { - if (status.isFailed) { - var tips, conirmfunc, cancelfunc; - switch (status.errorCode) { - case "err_no_space": - { - tips = "ē©ŗé—“äøč¶³ļ¼ŒčÆ·ęø…ē†ē£ē›˜ē©ŗé—“"; - conirmfunc = function () { - callPreload(); - }; - cancelfunc = function () { - cc.director.end(); - }; - break; - } - case "err_verify": - { - tips = "ę ”éŖŒå¤±č“„ļ¼Œę˜Æå¦é‡ę–°äø‹č½½ļ¼Ÿ"; - conirmfunc = function () { - callPreload(); - }; - cancelfunc = function () { - cc.director.end(); - }; - break; - } - case "err_network": - { - tips = "ē½‘ē»œå¼‚åøøę˜Æå¦é‡ę–°äø‹č½½"; - conirmfunc = function () { - callPreload(); - }; - cancelfunc = function () { - cc.director.end(); - }; - break; - } - default : - { - conirmfunc = cancelfunc = function () { - - }; - } - } - cc._NetworkErrorDialog._show(status.errorCode, tips, conirmfunc, cancelfunc); - } else { - if (callback) { - if (target) { - callback.call(target, !status.isFailed); - } else { - callback(!status.isFailed); - } - } - } - }; - - var callPreload = function () { - if (cc.director.getRunningScene()) { - loaderLayer.updateGroup(groupname, preloadCb, target); - loaderLayer._addToScene(); - loaderLayer._preloadSource(); - } else { - cc.log("Current scene is null we can't start preload"); - } - }; - callPreload(); -}; - -cc.LoaderLayer._useDefaultSource = true; -cc.LoaderLayer.setUseDefaultSource = function (status) { - cc.LoaderLayer._useDefaultSource = status; -}; - -cc.LoaderLayer._userConfig = null; -cc.LoaderLayer.setConfig = function (config) { - if(config.title && config.title.action){ - config.title.action.retain(); - } - if(config.logo && config.logo.action){ - config.logo.action.retain(); - } - cc.LoaderLayer._userConfig = config; -}; - -cc.Dialog = cc.Layer.extend({ - _userConfig: null, - _finalConfig: null, - _defaultConfig: null, - backgroundSprite: null, - _menuItemConfirm: null, - _menuItemCancel: null, - _messageLabel: null, - _eventListener: null, - _scaleFactor: null, - - ctor: function (config) { - this._super(); - this.setConfig(config); - }, - setConfig: function (config) { - if (config) { - this._userConfig = config; - } - this.removeAllChildren(); - this.initData(); - }, - initData: function () { - this._finalConfig = cc.cloneObject(cc.Dialog._defaultConfig); - var config = this._finalConfig; - if (this._userConfig != null) { - var uConfig = this._userConfig; - if (uConfig.position) { - config.position = uConfig.position; - } - if (uConfig.action) { - config.action = uConfig.action; - } - if (uConfig.background && uConfig.background.res) { - config.background = uConfig.background; - } - if (uConfig.confirmBtn) { - var uConfirmBtn = uConfig.confirmBtn; - var confirmBtn = config.confirmBtn; - confirmBtn.normalRes = uConfirmBtn.normalRes ? uConfirmBtn.normalRes : confirmBtn.normalRes; - confirmBtn.pressRes = uConfirmBtn.pressRes ? uConfirmBtn.pressRes : confirmBtn.pressRes; - confirmBtn.text = typeof uConfirmBtn.text != "undefined" ? uConfirmBtn.text : confirmBtn.text; - confirmBtn.textColor = uConfirmBtn.textColor ? uConfirmBtn.textColor : confirmBtn.textColor; - confirmBtn.fontSize = uConfirmBtn.fontSize ? uConfirmBtn.fontSize : confirmBtn.fontSize; - confirmBtn.position = uConfirmBtn.position ? uConfirmBtn.position : confirmBtn.position; - confirmBtn.callback = uConfirmBtn.callback ? uConfirmBtn.callback : confirmBtn.callback; - } - if (uConfig.cancelBtn) { - var uCancelBtn = uConfig.cancelBtn; - var cancelBtn = config.cancelBtn; - cancelBtn.normalRes = uCancelBtn.normalRes ? uCancelBtn.normalRes : cancelBtn.normalRes; - cancelBtn.pressRes = uCancelBtn.pressRes ? uCancelBtn.pressRes : cancelBtn.pressRes; - cancelBtn.text = typeof uCancelBtn.text != "undefined" ? uCancelBtn.text : cancelBtn.text; - cancelBtn.textColor = uCancelBtn.textColor ? uCancelBtn.textColor : cancelBtn.textColor; - cancelBtn.fontSize = uCancelBtn.fontSize ? uCancelBtn.fontSize : cancelBtn.fontSize; - cancelBtn.position = uCancelBtn.position ? uCancelBtn.position : cancelBtn.position; - cancelBtn.callback = uCancelBtn.callback ? uCancelBtn.callback : cancelBtn.callback; - } - if (uConfig.messageLabel) { - var uMessageLabel = uConfig.messageLabel; - var messageLabel = config.messageLabel; - messageLabel.text = typeof uMessageLabel.text != "undefined" ? uMessageLabel.text : messageLabel.text; - messageLabel.color = uMessageLabel.color ? uMessageLabel.color : messageLabel.color; - messageLabel.fontSize = uMessageLabel.fontSize ? uMessageLabel.fontSize : messageLabel.fontSize; - messageLabel.position = uMessageLabel.position ? uMessageLabel.position : messageLabel.position; - messageLabel.dimensions = uMessageLabel.dimensions ? uMessageLabel.dimensions : messageLabel.dimensions; - } - if (uConfig.target) { - config.target = uConfig.target; - } - if (typeof uConfig.onEnter == "function") { - config.onEnter = uConfig.onEnter; - } - if (typeof uConfig.onExit == "function") { - config.onExit = uConfig.onExit; - } - } - - if (!config.cancelBtn.textColor) { - config.cancelBtn.textColor = cc.color(255, 255, 255); - } - if (!config.confirmBtn.textColor) { - config.confirmBtn.textColor = cc.color(255, 255, 255); - } - - }, - initView: function () { - var useDefaultSource = cc.Dialog._useDefaultSource; - var winSize = cc.director.getWinSize(); - this._scaleFactor = !useDefaultSource ? 1 : winSize.width > winSize.height ? winSize.width / 720 : winSize.width / 480; - var config = this._finalConfig; - - //bg - this.backgroundSprite = new cc.Scale9Sprite(config.background.res); - this._setScale(this.backgroundSprite); - if (this._scaleFactor < 1) { - this.backgroundSprite.setScale(this._scaleFactor); - } - this.backgroundSprite.setPosition(config.position ? config.position : cc.p(winSize.width / 2, winSize.height / 2)); - - //menu - this.menuItemConfirm = this._createMenuItemSprite(config.confirmBtn, this._confirmCallback); - this.menuItemCancel = this._createMenuItemSprite(config.cancelBtn, this._cancelCallback); - this.menuItemCancel.setPosition(config.cancelBtn.position ? config.cancelBtn.position : cc.p(this.backgroundSprite.width / 2 - this.menuItemCancel.width / 2 - 20, this.menuItemCancel.height + 20)); - this.menuItemConfirm.setPosition(config.confirmBtn.position ? config.confirmBtn.position : cc.p(this.backgroundSprite.width / 2 + this.menuItemConfirm.width / 2 + 20, this.menuItemConfirm.height + 20)); - var menu = new cc.Menu(this.menuItemConfirm, this.menuItemCancel); - menu.setPosition(cc.p(0, 0)); - this.backgroundSprite.addChild(menu); - - //message - var fontSize = config.messageLabel.fontSize ? config.messageLabel.fontSize : this._scaleFactor > 1 ? 16 * this._scaleFactor : 16; - this.messageLabel = new cc.LabelTTF(config.messageLabel.text, "Arial", fontSize); - this.messageLabel.setDimensions(config.messageLabel.dimensions ? config.messageLabel.dimensions : cc.size(this.backgroundSprite.width - 30, this.backgroundSprite.height - this.menuItemConfirm.y - 10)); - this.messageLabel.setColor(config.messageLabel.color ? config.messageLabel.color : cc.color(255, 255, 255)); - this.messageLabel.setPosition(config.messageLabel.position ? config.messageLabel.position : cc.p(this.backgroundSprite.width / 2, this.backgroundSprite.height - this.messageLabel.height / 2 - 20)); - this.backgroundSprite.addChild(this.messageLabel); - if (!config.action) { - var action = cc.sequence(cc.EaseIn.create(cc.scaleTo(0.1, this.backgroundSprite.scale + 0.02), 0.4), cc.EaseOut.create(cc.scaleTo(0.1, this.backgroundSprite.scale), 0.3)); - this.backgroundSprite.runAction(action); - } else { - this.backgroundSprite.runAction(config.action); - } - this.addChild(this.backgroundSprite); - - }, - _createMenuItemSprite: function (res, callback) { - var spriteNormal = new cc.Scale9Sprite(res.normalRes); - var spritePress = new cc.Scale9Sprite(res.pressRes); - this._setScale(spriteNormal); - this._setScale(spritePress); - var fontSize = res.fontSize ? res.fontSize : this._scaleFactor > 1 ? 16 * this._scaleFactor : 16; - var menuLabel = new cc.LabelTTF(res.text, "Arial", fontSize); - menuLabel.setColor(res.textColor); - var menuItem = new cc.MenuItemSprite(spriteNormal, spritePress, callback, this); - menuLabel.setPosition(cc.p(menuItem.width / 2, menuItem.height / 2)); - menuItem.addChild(menuLabel); - return menuItem; - }, - _setScale: function (s9Sprite) { - if (this._scaleFactor > 1) { - s9Sprite.setContentSize(cc.size(this._scaleFactor * s9Sprite.width, this._scaleFactor * s9Sprite.height)); - } - }, - _confirmCallback: function () { - var config = this._finalConfig; - if (config.confirmBtn.callback) { - if (config.target) { - config.confirmBtn.callback.call(config.target, this); - } else { - config.confirmBtn.callback(this); - } - } - this.removeFromParent(); - }, - _cancelCallback: function () { - var config = this._finalConfig; - if (config.cancelBtn.callback) { - if (config.target) { - config.cancelBtn.callback.call(config.target, this); - } else { - config.cancelBtn.callback(this); - } - } - this.removeFromParent(); - }, - onEnter: function () { - this._super(); - var config = this._finalConfig; - this.initView(); - config.onEnter(this); - var self = this; - self._eventListener = cc.EventListener.create({ - event: cc.EventListener.TOUCH_ONE_BY_ONE, - swallowTouches: true, - onTouchBegan: function (touch, event) { - return true; - } - }); - cc.eventManager.addListener(self._eventListener, self); - }, - onExit: function () { - this._super(); - var config = this._finalConfig; - config.onExit(this); - this.removeAllChildren(); - cc.Dialog._dialog = null; - cc.eventManager.removeListener(this._eventListener); - } -}); - -cc.Dialog._dialog = null; -cc.Dialog._clearDialog = function () { - if (cc.Dialog._dialog != null) { - cc.Dialog._dialog.removeFromParent(); - cc.Dialog._dialog = null; - } -}; - -cc.Dialog.show = function (tips, confirmCb, cancelCb) { - if(cc.Dialog._dialog != null){ - cc.log("other dialog is on the screen,this dialog can't show now"); - return; - } - var conf; - if(typeof tips == "string"){ - conf = { - messageLabel: { - text: tips - }, - confirmBtn: { - callback: confirmCb - }, - cancelBtn: { - callback: cancelCb - } - }; - }else if(typeof tips == "object"){ - conf = tips; - }else{ - cc.log("tips is invalid"); - return; - } - - cc.Dialog._dialog = new cc.Dialog(conf); - if (cc.director.getRunningScene()) { - cc.director.getRunningScene().addChild(cc.Dialog._dialog, cc.INT_MAX); - } else { - cc.log("Current scene is null we can't show dialog"); - } -}; - -cc.Dialog._useDefaultSource = true; -cc.Dialog.setUseDefaultSource = function (status) { - cc.Dialog._useDefaultSource = status; -}; - -cc.Dialog._defaultConfig = { - position: null, - target: null, - action: null, - background: { - res: "res_engine/dialog_bg.png" - }, - confirmBtn: { - normalRes: "res_engine/dialog_confirm_normal.png", - pressRes: "res_engine/dialog_confirm_press.png", - text: "甮定", - textColor: null, - fontSize: null, - position: null, - callback: function () { - cc.log("this is confirm callback"); - } - }, - cancelBtn: { - normalRes: "res_engine/dialog_cancel_normal.png", - pressRes: "res_engine/dialog_cancel_press.png", - text: "å–ę¶ˆ", - textColor: null, - position: null, - fontSize: null, - callback: function () { - cc.log("this is cancel callback"); - } - }, - messageLabel: { - text: "", - color: null, - dimensions: null, - fontSize: null, - position:null - }, - onEnter: function (dialog) { - cc.log("dialog call onEnter"); - }, - onExit: function (dialog) { - cc.log("dialog call onExit"); - } -}; - -cc._NetworkErrorDialog = function () { - cc.Dialog._clearDialog(); - cc.Dialog._dialog = new cc.Dialog(cc._NetworkErrorDialog._config); - return cc.Dialog._dialog; -}; - -cc._NetworkErrorDialog._config = { - networkError:{ - - }, - spaceError:{ - - }, - verifyError:{ - - } -}; - -cc._NetworkErrorDialog._show = function (type, tips, confirmCb, cancelCb) { - var networkDialog = cc._NetworkErrorDialog(); - var config; - switch (type) { - case "err_network": - { - config = cc._NetworkErrorDialog._config.networkError; - break; - } - case "err_no_space": - { - config = cc._NetworkErrorDialog._config.spaceError; - break; - } - case "err_verify": - { - config = cc._NetworkErrorDialog._config.verifyError; - break; - } - default: - { - cc.log("type is not found"); - return; - } - } - if (!networkDialog.getParent()) { - - config.confirmBtn = config.confirmBtn || {}; - config.confirmBtn.callback = function () { - if (confirmCb) - confirmCb(); - }; - - config.cancelBtn = config.cancelBtn || {}; - config.cancelBtn.callback = function () { - if (cancelCb) - cancelCb(); - }; - - config.messageLabel = config.messageLabel || {}; - if (typeof config.messageLabel.text == "undefined") { - config.messageLabel.text = tips; - } - - networkDialog.setConfig(config); - if (cc.director.getRunningScene()) { - cc.director.getRunningScene().addChild(networkDialog, cc.INT_MAX); - } else { - cc.log("Current scene is null we can't show dialog"); - } - } -}; - -cc._NetworkErrorDialog._setConfig = function (key, config) { - if (key && config) { - switch (key) { - case "err_network": - { - cc._NetworkErrorDialog._config.networkError = config; - break; - } - case "err_no_space": - { - cc._NetworkErrorDialog._config.spaceError = config; - break; - } - case "err_verify": - { - cc._NetworkErrorDialog._config.verifyError = config; - break; - } - } - } -}; - -cc.cloneObject = function (obj) { - var o; - if (obj.constructor == Object) { - o = new obj.constructor(); - } else { - o = new obj.constructor(obj.valueOf()); - } - for (var key in obj) { - if (o[key] != obj[key]) { - if (typeof(obj[key]) == 'object') { - o[key] = cc.cloneObject(obj[key]); - } else { - o[key] = obj[key]; - } - } - } - o.toString = obj.toString; - o.valueOf = obj.valueOf; - return o; -}; - -//+++++++++++++++++++++++++something about cc.runtime begin+++++++++++++++++++++++++++++ -//todo init runtime config -cc.runtime = { - RUNTIME_CONFIG_KEY:{ - description: "description", - design_resolution: "design_resolution", - entry_file: "entry_file", - game_name: "game_name", - manifest_file:"manifest_file", - orientation: "orientation", - package_name: "package_name", - project_json_file: "project_json_file", - runtime_version: "runtime_version", - version_code: "version_code", - version_name: "version_name" - }, - config:null, - _getConfigName: function () { - return "config.json"; - }, - _initConfig: function () { - cc.log("begin init runtime config"); - var CONFIG_KEY = this.RUNTIME_CONFIG_KEY; - var _init = function(cfg){ - cfg[CONFIG_KEY.design_resolution] = cfg[CONFIG_KEY.design_resolution] || {height:800,width:480,policy:"SHOW_ALL"}; - cfg[CONFIG_KEY.entry_file] = cfg[CONFIG_KEY.entry_file] || {"md5": "", "name": "main.js"}; - cfg[CONFIG_KEY.manifest_file] = cfg[CONFIG_KEY.manifest_file] ||{"md5": "", "name": "manifest.json"}; - cfg[CONFIG_KEY.project_json_file] = cfg[CONFIG_KEY.project_json_file] ||{"md5": "", "name": "project.json"}; - cfg[CONFIG_KEY.description] = cfg[CONFIG_KEY.description] || ""; - cfg[CONFIG_KEY.game_name] = cfg[CONFIG_KEY.game_name] || ""; - cfg[CONFIG_KEY.orientation] = cfg[CONFIG_KEY.orientation] ||""; - cfg[CONFIG_KEY.package_name] = cfg[CONFIG_KEY.package_name] ||""; - cfg[CONFIG_KEY.runtime_version] = cfg[CONFIG_KEY.runtime_version] ||""; - cfg[CONFIG_KEY.version_code] = cfg[CONFIG_KEY.version_code] ||""; - cfg[CONFIG_KEY.version_name] = cfg[CONFIG_KEY.version_name] ||""; - return cfg; - }; - try { - this.config = runtime.config; - //cc.log("read runtime config is " + JSON.stringify(this.config)); - var design = this.config[CONFIG_KEY.design_resolution]; - cc.log("design.width is " + design.width + " design.height is " + design.height + " policy is " + design.policy); - this._setDesignResolutionSize(design.width, design.height, cc.ResolutionPolicy[design.policy]); - } catch (e) { - cc.log("Failed to read or parse" + this._getConfigName()); - this.config = _init({}); - } - }, - _setDesignResolutionSize : function(width,height,policy){ - cc.log("cc.runtime begin setting designResolutionSize"); - cc.view.setDesignResolutionSize(width,height,policy); - } -}; - -cc.runtime._initConfig(); - -cc.runtime.network = cc.network; - -cc.runtime.setOption = function (promptype, config) { - if (config) { - switch (promptype) { - case "network_error_dialog": - { - cc._NetworkErrorDialog._setConfig("err_network", config); - break; - } - case "no_space_error_dialog": - { - cc._NetworkErrorDialog._setConfig("err_no_space", config); - break; - } - case "verify_error_dialog": - { - cc._NetworkErrorDialog._setConfig("err_verify", config); - break; - } - default : - { - cc.log("promptype not found please check your promptype"); - } - } - } else { - cc.log("config is null please check your config"); - } -}; - -runtime.sendMessageToChannel = function(obj) { - var msg = JSON.stringify(obj); - var ret = runtime._sendToChannel(msg, 0); - cc.log("runtime.sendMessageToChannel msg: " + msg + ", ret: " + ret); - return ret; -}; - -var _receiveChannelMessageCallback = null; - -runtime.registerReceiveChannelMessageCallback = function(cb) { - if (_receiveChannelMessageCallback) { - cc.log("WARNING: receiveChannelMessageCallback has been invoked, will replace callback!"); - } - _receiveChannelMessageCallback = cb; -}; - -runtime.unregisterReceiveChannelMessageCallback = function() { - _receiveChannelMessageCallback = null; -}; - -runtime._onReceiveChannelMessage = function(objJson) { - if (_receiveChannelMessageCallback) { - cc.log("runtime._onReceiveChannelMessage: " + objJson); - var obj = JSON.parse(objJson); - return _receiveChannelMessageCallback(obj); - } -}; diff --git a/native/cocos/scripting/js-bindings/script/runtime/jsb_runtime_md5.js b/native/cocos/scripting/js-bindings/script/runtime/jsb_runtime_md5.js deleted file mode 100644 index e98c1f4516..0000000000 --- a/native/cocos/scripting/js-bindings/script/runtime/jsb_runtime_md5.js +++ /dev/null @@ -1,275 +0,0 @@ -cc.md5Encode = function(data){ - // for test/debug - function fflog(msg) { - try { - console.log(msg); - } catch(e) {} - } - - // convert number to (unsigned) 32 bit hex, zero filled string - function to_zerofilled_hex(n) { - var t1 = (n >>> 24).toString(16); - var t2 = (n & 0x00FFFFFF).toString(16); - return "00".substr(0, 2 - t1.length) + t1 + - "000000".substr(0, 6 - t2.length) + t2; - } - - // convert array of chars to array of bytes (note: Unicode not supported) - function chars_to_bytes(ac) { - var retval = []; - for (var i = 0; i < ac.length; i++) { - retval = retval.concat(str_to_bytes(ac[i])); - } - return retval; - } - - - // convert a 64 bit unsigned number to array of bytes. Little endian - function int64_to_bytes(num) { - var retval = []; - for (var i = 0; i < 8; i++) { - retval.push(num & 0xFF); - num = num >>> 8; - } - return retval; - } - - // 32 bit left-rotation - function rol(num, places) { - return ((num << places) & 0xFFFFFFFF) | (num >>> (32 - places)); - } - - // The 4 MD5 functions - function fF(b, c, d) { - return (b & c) | (~b & d); - } - - function fG(b, c, d) { - return (d & b) | (~d & c); - } - - function fH(b, c, d) { - return b ^ c ^ d; - } - - function fI(b, c, d) { - return c ^ (b | ~d); - } - - // pick 4 bytes at specified offset. Little-endian is assumed - function bytes_to_int32(arr, off) { - return (arr[off + 3] << 24) | (arr[off + 2] << 16) | (arr[off + 1] << 8) | (arr[off]); - } - - /* - Conver string to array of bytes in UTF-8 encoding - See: - http://www.dangrossman.info/2007/05/25/handling-utf-8-in-javascript-php-and-non-utf8-databases/ - http://stackoverflow.com/questions/1240408/reading-bytes-from-a-javascript-string - How about a String.getBytes() for Javascript!? Isn't it time to add it? - */ - function str_to_bytes(str) { - // alert("got " + str.length + " chars") - var retval = [ ]; - for (var i = 0; i < str.length; i++) - if (str.charCodeAt(i) <= 0x7F) { - retval.push(str.charCodeAt(i)); - } else { - var tmp = encodeURIComponent(str.charAt(i)).substr(1).split('%'); - for (var j = 0; j < tmp.length; j++) { - retval.push(parseInt(tmp[j], 0x10)); - } - } - return retval; - }; - - - - - // convert the 4 32-bit buffers to a 128 bit hex string. (Little-endian is assumed) - function int128le_to_hex(a, b, c, d) { - var ra = ""; - var t = 0; - var ta = 0; - for (var i = 3; i >= 0; i--) { - ta = arguments[i]; - t = (ta & 0xFF); - ta = ta >>> 8; - t = t << 8; - t = t | (ta & 0xFF); - ta = ta >>> 8; - t = t << 8; - t = t | (ta & 0xFF); - ta = ta >>> 8; - t = t << 8; - t = t | ta; - ra = ra + to_zerofilled_hex(t); - } - return ra; - } - - // check input data type and perform conversions if needed - var databytes = null; - // String - if (typeof data == 'string') { - // convert string to array bytes - databytes = str_to_bytes(data); - } else if (data.constructor == Array) { - if (data.length === 0) { - // if it's empty, just assume array of bytes - databytes = data; - } else if (typeof data[0] == 'string') { - databytes = chars_to_bytes(data); - } else if (typeof data[0] == 'number') { - databytes = data; - } else { - fflog("input data type mismatch"); - return null; - } - } else { - fflog("input data type mismatch"); - return null; - } - - // save original length - var org_len = databytes.length; - - // first append the "1" + 7x "0" - databytes.push(0x80); - - // determine required amount of padding - var tail = databytes.length % 64; - // no room for msg length? - if (tail > 56) { - // pad to next 512 bit block - for (var i = 0; i < (64 - tail); i++) { - databytes.push(0x0); - } - tail = databytes.length % 64; - } - for (i = 0; i < (56 - tail); i++) { - databytes.push(0x0); - } - // message length in bits mod 512 should now be 448 - // append 64 bit, little-endian original msg length (in *bits*!) - databytes = databytes.concat(int64_to_bytes(org_len * 8)); - - // initialize 4x32 bit state - var h0 = 0x67452301; - var h1 = 0xEFCDAB89; - var h2 = 0x98BADCFE; - var h3 = 0x10325476; - - // temp buffers - var a = 0, - b = 0, - c = 0, - d = 0; - - - function _add(n1, n2) { - return 0x0FFFFFFFF & (n1 + n2) - } - - // function update partial state for each run - var updateRun = function(nf, sin32, dw32, b32) { - var temp = d; - d = c; - c = b; - //b = b + rol(a + (nf + (sin32 + dw32)), b32); - b = _add(b, - rol( - _add(a, - _add(nf, _add(sin32, dw32)) - ), b32 - ) - ); - a = temp; - }; - - - // Digest message - for (i = 0; i < databytes.length / 64; i++) { - // initialize run - a = h0; - b = h1; - c = h2; - d = h3; - - var ptr = i * 64; - - // do 64 runs - updateRun(fF(b, c, d), 0xd76aa478, bytes_to_int32(databytes, ptr), 7); - updateRun(fF(b, c, d), 0xe8c7b756, bytes_to_int32(databytes, ptr + 4), 12); - updateRun(fF(b, c, d), 0x242070db, bytes_to_int32(databytes, ptr + 8), 17); - updateRun(fF(b, c, d), 0xc1bdceee, bytes_to_int32(databytes, ptr + 12), 22); - updateRun(fF(b, c, d), 0xf57c0faf, bytes_to_int32(databytes, ptr + 16), 7); - updateRun(fF(b, c, d), 0x4787c62a, bytes_to_int32(databytes, ptr + 20), 12); - updateRun(fF(b, c, d), 0xa8304613, bytes_to_int32(databytes, ptr + 24), 17); - updateRun(fF(b, c, d), 0xfd469501, bytes_to_int32(databytes, ptr + 28), 22); - updateRun(fF(b, c, d), 0x698098d8, bytes_to_int32(databytes, ptr + 32), 7); - updateRun(fF(b, c, d), 0x8b44f7af, bytes_to_int32(databytes, ptr + 36), 12); - updateRun(fF(b, c, d), 0xffff5bb1, bytes_to_int32(databytes, ptr + 40), 17); - updateRun(fF(b, c, d), 0x895cd7be, bytes_to_int32(databytes, ptr + 44), 22); - updateRun(fF(b, c, d), 0x6b901122, bytes_to_int32(databytes, ptr + 48), 7); - updateRun(fF(b, c, d), 0xfd987193, bytes_to_int32(databytes, ptr + 52), 12); - updateRun(fF(b, c, d), 0xa679438e, bytes_to_int32(databytes, ptr + 56), 17); - updateRun(fF(b, c, d), 0x49b40821, bytes_to_int32(databytes, ptr + 60), 22); - updateRun(fG(b, c, d), 0xf61e2562, bytes_to_int32(databytes, ptr + 4), 5); - updateRun(fG(b, c, d), 0xc040b340, bytes_to_int32(databytes, ptr + 24), 9); - updateRun(fG(b, c, d), 0x265e5a51, bytes_to_int32(databytes, ptr + 44), 14); - updateRun(fG(b, c, d), 0xe9b6c7aa, bytes_to_int32(databytes, ptr), 20); - updateRun(fG(b, c, d), 0xd62f105d, bytes_to_int32(databytes, ptr + 20), 5); - updateRun(fG(b, c, d), 0x2441453, bytes_to_int32(databytes, ptr + 40), 9); - updateRun(fG(b, c, d), 0xd8a1e681, bytes_to_int32(databytes, ptr + 60), 14); - updateRun(fG(b, c, d), 0xe7d3fbc8, bytes_to_int32(databytes, ptr + 16), 20); - updateRun(fG(b, c, d), 0x21e1cde6, bytes_to_int32(databytes, ptr + 36), 5); - updateRun(fG(b, c, d), 0xc33707d6, bytes_to_int32(databytes, ptr + 56), 9); - updateRun(fG(b, c, d), 0xf4d50d87, bytes_to_int32(databytes, ptr + 12), 14); - updateRun(fG(b, c, d), 0x455a14ed, bytes_to_int32(databytes, ptr + 32), 20); - updateRun(fG(b, c, d), 0xa9e3e905, bytes_to_int32(databytes, ptr + 52), 5); - updateRun(fG(b, c, d), 0xfcefa3f8, bytes_to_int32(databytes, ptr + 8), 9); - updateRun(fG(b, c, d), 0x676f02d9, bytes_to_int32(databytes, ptr + 28), 14); - updateRun(fG(b, c, d), 0x8d2a4c8a, bytes_to_int32(databytes, ptr + 48), 20); - updateRun(fH(b, c, d), 0xfffa3942, bytes_to_int32(databytes, ptr + 20), 4); - updateRun(fH(b, c, d), 0x8771f681, bytes_to_int32(databytes, ptr + 32), 11); - updateRun(fH(b, c, d), 0x6d9d6122, bytes_to_int32(databytes, ptr + 44), 16); - updateRun(fH(b, c, d), 0xfde5380c, bytes_to_int32(databytes, ptr + 56), 23); - updateRun(fH(b, c, d), 0xa4beea44, bytes_to_int32(databytes, ptr + 4), 4); - updateRun(fH(b, c, d), 0x4bdecfa9, bytes_to_int32(databytes, ptr + 16), 11); - updateRun(fH(b, c, d), 0xf6bb4b60, bytes_to_int32(databytes, ptr + 28), 16); - updateRun(fH(b, c, d), 0xbebfbc70, bytes_to_int32(databytes, ptr + 40), 23); - updateRun(fH(b, c, d), 0x289b7ec6, bytes_to_int32(databytes, ptr + 52), 4); - updateRun(fH(b, c, d), 0xeaa127fa, bytes_to_int32(databytes, ptr), 11); - updateRun(fH(b, c, d), 0xd4ef3085, bytes_to_int32(databytes, ptr + 12), 16); - updateRun(fH(b, c, d), 0x4881d05, bytes_to_int32(databytes, ptr + 24), 23); - updateRun(fH(b, c, d), 0xd9d4d039, bytes_to_int32(databytes, ptr + 36), 4); - updateRun(fH(b, c, d), 0xe6db99e5, bytes_to_int32(databytes, ptr + 48), 11); - updateRun(fH(b, c, d), 0x1fa27cf8, bytes_to_int32(databytes, ptr + 60), 16); - updateRun(fH(b, c, d), 0xc4ac5665, bytes_to_int32(databytes, ptr + 8), 23); - updateRun(fI(b, c, d), 0xf4292244, bytes_to_int32(databytes, ptr), 6); - updateRun(fI(b, c, d), 0x432aff97, bytes_to_int32(databytes, ptr + 28), 10); - updateRun(fI(b, c, d), 0xab9423a7, bytes_to_int32(databytes, ptr + 56), 15); - updateRun(fI(b, c, d), 0xfc93a039, bytes_to_int32(databytes, ptr + 20), 21); - updateRun(fI(b, c, d), 0x655b59c3, bytes_to_int32(databytes, ptr + 48), 6); - updateRun(fI(b, c, d), 0x8f0ccc92, bytes_to_int32(databytes, ptr + 12), 10); - updateRun(fI(b, c, d), 0xffeff47d, bytes_to_int32(databytes, ptr + 40), 15); - updateRun(fI(b, c, d), 0x85845dd1, bytes_to_int32(databytes, ptr + 4), 21); - updateRun(fI(b, c, d), 0x6fa87e4f, bytes_to_int32(databytes, ptr + 32), 6); - updateRun(fI(b, c, d), 0xfe2ce6e0, bytes_to_int32(databytes, ptr + 60), 10); - updateRun(fI(b, c, d), 0xa3014314, bytes_to_int32(databytes, ptr + 24), 15); - updateRun(fI(b, c, d), 0x4e0811a1, bytes_to_int32(databytes, ptr + 52), 21); - updateRun(fI(b, c, d), 0xf7537e82, bytes_to_int32(databytes, ptr + 16), 6); - updateRun(fI(b, c, d), 0xbd3af235, bytes_to_int32(databytes, ptr + 44), 10); - updateRun(fI(b, c, d), 0x2ad7d2bb, bytes_to_int32(databytes, ptr + 8), 15); - updateRun(fI(b, c, d), 0xeb86d391, bytes_to_int32(databytes, ptr + 36), 21); - - // update buffers - h0 = _add(h0, a); - h1 = _add(h1, b); - h2 = _add(h2, c); - h3 = _add(h3, d); - } - // Done! Convert buffers to 128 bit (LE) - return int128le_to_hex(h3, h2, h1, h0).toUpperCase(); -}; diff --git a/native/cocos/scripting/js-bindings/script/studio/jsb_cocos2d_studio.js b/native/cocos/scripting/js-bindings/script/studio/jsb_cocos2d_studio.js deleted file mode 100644 index 0c38cf3313..0000000000 --- a/native/cocos/scripting/js-bindings/script/studio/jsb_cocos2d_studio.js +++ /dev/null @@ -1,564 +0,0 @@ -/* - * Copyright (c) 2013-2016 Chukong Technologies Inc. - * - * 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. - */ - -// -// cocos2d studio constants -// -// This helper file should be required after jsb_cocos2d.js -// - -var ccs = ccs || {}; - -ccs.Class = ccs.Class || cc.Class || {}; - -// Movement event type -ccs.MovementEventType = { - start: 0, - complete: 1, - loopComplete: 2 -}; - -// Inner action type -ccs.InnerActionType = { - LoopAction: 0, - NoLoopAction: 1, - SingleFrame: 2 -}; - -ccs.AnimationInfo = function (name, startIndex, endIndex) { - this.name = name || ""; - this.startIndex = startIndex != undefined ? startIndex : 0; - this.endIndex = endIndex != undefined ? endIndex : 0; -}; - -// Armature -if(ccs.Armature){ - ccs.Armature.prototype.setBody = function( body ) { - var b = body; - if( body.handle !== undefined ) - b = body.handle; - return this._setCPBody( b ); - }; - - ccs.ComController.extend = cc.Class.extend; - ccs.Armature.extend = cc.Class.extend; -} - -ccs.Armature.prototype._setBlendFunc = ccs.Armature.prototype.setBlendFunc; -ccs.Armature.prototype.setBlendFunc = templateSetBlendFunc; - - -ccs.sendEvent = function (event) { - var triggerObjArr = ccs.triggerManager.get(event); - if (triggerObjArr == null) { - return; - } - for (var i = 0; i < triggerObjArr.length; i++) { - var triObj = triggerObjArr[i]; - if (triObj != null && triObj.detect()) { - triObj.done(); - } - } -}; - - -ccs.objectFactory = { - _typeMap: {}, - - destroyInstance: function () { - this._sharedFactory = null; - }, - - createObject: function (className) { - var o = null; - var t = this._typeMap[className]; - if (t) { - o = new t._fun(); - } - return o; - }, - - registerType: function (t) { - this._typeMap[t._className] = t; - } -}; - -ccs.TInfo = ccs.Class.extend({ - _className: "", - _fun: null, - /** - * - * @param {String|ccs.TInfo}c - * @param {Function}f - */ - ctor: function (c, f) { - if (f) { - this._className = c; - this._fun = f; - }else{ - this._className = c._className; - this._fun = c._fun; - } - ccs.objectFactory.registerType(this); - } -}); - -ccs.registerTriggerClass = function(className, createFunc) { - new ccs.TInfo(className, createFunc); -} - -ccs.BaseTriggerCondition = ccs.Class.extend({ - init: function () { - return true; - }, - - detect: function () { - return true; - }, - - serialize: function (jsonVal) { - }, - - removeAll: function () { - } -}); -ccs.BaseTriggerAction = ccs.Class.extend({ - - init: function () { - return true; - }, - - done: function () { - - }, - - serialize: function (jsonVal) { - }, - - removeAll: function () { - } -}); - -ccs.TriggerObj = ccs.Class.extend({ - _cons: null, - _acts: null, - _id: 0, - _enable: true, - _vInt: null, - - ctor: function () { - this._id = 0; - this._enable = true; - }, - - init: function () { - this._cons = []; - this._acts = []; - this._vInt = []; - return true; - }, - - detect: function () { - if (!this._enable || this._cons.length == 0) { - return true; - } - var ret = true; - var obj = null; - for (var i = 0; i < this._cons.length; i++) { - obj = this._cons[i]; - if (obj && obj.detect) { - ret = ret && obj.detect(); - } - } - return ret; - }, - - done: function () { - if (!this._enable || this._acts.length == 0) { - return; - } - var obj; - for (var i = 0; i < this._acts.length; i++) { - obj = this._acts[i]; - if (obj && obj.done) { - obj.done(); - } - } - }, - - removeAll: function () { - var obj = null; - for (var i = 0; i < this._cons.length; i++) { - obj = this._cons[i]; - if (obj) - obj.removeAll(); - } - this._cons = []; - for (var i = 0; i < this._acts.length; i++) { - obj = this._acts[i]; - if (obj) - obj.removeAll(); - } - this._acts = []; - }, - - serialize: function (jsonVal) { - this._id = jsonVal["id"] || 0; - var conditions = jsonVal["conditions"] || []; - for (var i = 0; i < conditions.length; i++) { - var subDict = conditions[i]; - var classname = subDict["classname"]; - if (!classname) { - continue; - } - var con = ccs.objectFactory.createObject(classname); - if (!con) { - cc.log("class named classname(" + classname + ") can not implement!"); - } - - con.serialize(subDict); - con.init(); - this._cons.push(con); - } - - var actions = jsonVal["actions"] || []; - for (var i = 0; i < actions.length; i++) { - var subDict = actions[i]; - var classname = subDict["classname"]; - if (!classname) { - continue; - } - var act = ccs.objectFactory.createObject(classname); - if (!act) { - cc.log("class named classname(" + classname + ") can not implement!"); - } - - act.serialize(subDict); - act.init(); - this._acts.push(act); - } - - var events = jsonVal["events"] || []; - for (var i = 0; i < events.length; i++) { - var subDict = events[i]; - var event = subDict["id"]; - if (event < 0) { - continue; - } - this._vInt.push(event); - } - }, - - getId: function () { - return this._id; - }, - - setEnable: function (enable) { - this._enable = enable; - }, - - getEvents: function () { - return this._vInt; - } -}); - -ccs.TriggerObj.create = function() { - var ret = new ccs.TriggerObj(); - if (ret.init()) - return ret; - return null; -} - -ccs.triggerManager = { - _eventTriggers: {}, - _triggerObjs: {}, - _movementDispatches: [], - - destroyInstance: function () { - this.removeAll(); - this._instance = null; - }, - - parse: function (root) { - var triggers = root;//["Triggers"]; - for (var i = 0; i < triggers.length; ++i) { - var subDict = triggers[i]; - var triggerObj = ccs.TriggerObj.create(); - triggerObj.serialize(subDict); - var events = triggerObj.getEvents(); - for (var j = 0; j < events.length; j++) { - var event = events[j]; - this.add(event, triggerObj); - } - this._triggerObjs[triggerObj.getId()] = triggerObj; - } - }, - - get: function (event) { - return this._eventTriggers[event]; - }, - - getTriggerObj: function (id) { - return this._triggerObjs[id]; - }, - - add: function (event, triggerObj) { - var eventTriggers = this._eventTriggers[event]; - if (!eventTriggers) { - eventTriggers = []; - } - if (eventTriggers.indexOf(triggerObj) == -1) { - eventTriggers.push(triggerObj); - this._eventTriggers[event] = eventTriggers; - } - }, - - removeAll: function () { - for (var key in this._eventTriggers) { - var triObjArr = this._eventTriggers[key]; - for (var j = 0; j < triObjArr.length; j++) { - var obj = triObjArr[j]; - obj.removeAll(); - } - } - this._eventTriggers = {}; - }, - - remove: function (event, Obj) { - if (Obj) { - return this._removeObj(event, Obj); - } - var bRet = false; - do - { - var triObjects = this._eventTriggers[event]; - if (!triObjects) break; - for (var i = 0; i < triObjects.length; i++) { - var triObject = triObjects[i]; - if (triObject) { - triObject.removeAll(); - } - } - delete this._eventTriggers[event]; - bRet = true; - } while (0); - return bRet; - }, - - _removeObj: function (event, Obj) { - var bRet = false; - do - { - var triObjects = this._eventTriggers[event]; - if (!triObjects) break; - for (var i = 0; i < triObjects.length; i++) { - var triObject = triObjects[i]; - if (triObject && triObject == Obj) { - triObject.removeAll(); - triObjects.splice(i, 1); - break; - } - } - bRet = true; - } while (0); - return bRet; - }, - - removeTriggerObj: function (id) { - var obj = this.getTriggerObj(id); - if (!obj) { - return false; - } - var events = obj.getEvents(); - for (var i = 0; i < events.length; i++) { - var event = events[i]; - this.remove(event, obj); - } - return true; - }, - isEmpty: function () { - return !this._eventTriggers || this._eventTriggers.length <= 0; - }, - - addArmatureMovementCallBack: function (armature, callFunc, target) { - if (armature == null || target == null || callFunc == null) { - return; - } - var locAmd, hasADD = false; - for (var i = 0; i < this._movementDispatches.length; i++) { - locAmd = this._movementDispatches[i]; - if (locAmd && locAmd[0] == armature) { - locAmd.addAnimationEventCallBack(callFunc, target); - hasADD = true; - } - } - if (!hasADD) { - var newAmd = new ccs.ArmatureMovementDispatcher(); - armature.getAnimation().setMovementEventCallFunc(newAmd.animationEvent, newAmd); - newAmd.addAnimationEventCallBack(callFunc, target); - this._movementDispatches.push([armature, newAmd]); - } - }, - - removeArmatureMovementCallBack: function (armature, target, callFunc) { - if (armature == null || target == null || callFunc == null) { - return; - } - var locAmd; - for (var i = 0; i < this._movementDispatches.length; i++) { - locAmd = this._movementDispatches[i]; - if (locAmd && locAmd[0] == armature) { - locAmd.removeAnimationEventCallBack(callFunc, target); - } - } - }, - - removeArmatureAllMovementCallBack: function (armature) { - if (armature == null) { - return; - } - var locAmd; - for (var i = 0; i < this._movementDispatches.length; i++) { - locAmd = this._movementDispatches[i]; - if (locAmd && locAmd[0] == armature) { - this._movementDispatches.splice(i, 1); - break; - } - } - }, - - removeAllArmatureMovementCallBack: function () { - this._movementDispatches = []; - }, - - version: function () { - return "1.2.0.0"; - } -}; - - -// Functions don't support binding -ccs.Bone.prototype.getColliderBodyList = function() { - var decoDisplay = this.getDisplayManager().getCurrentDecorativeDisplay(); - if (decoDisplay) { - var detector = decoDisplay.getColliderDetector(); - if (detector) { - return detector.getColliderBodyList(); - } - } - return []; -}; - -ccs.TweenType = { - CUSTOM_EASING: -1, - LINEAR: 0, - - SINE_EASEIN: 1, - SINE_EASEOUT: 2, - SINE_EASEINOUT: 3, - - QUAD_EASEIN: 4, - QUAD_EASEOUT: 5, - QUAD_EASEINOUT: 6, - - CUBIC_EASEIN: 7, - CUBIC_EASEOUT: 8, - CUBIC_EASEINOUT: 9, - - QUART_EASEIN: 10, - QUART_EASEOUT: 11, - QUART_EASEINOUT: 12, - - QUINT_EASEIN: 13, - QUINT_EASEOUT: 14, - QUINT_EASEINOUT: 15, - - EXPO_EASEIN: 16, - EXPO_EASEOUT: 17, - EXPO_EASEINOUT: 18, - - CIRC_EASEIN: 19, - CIRC_EASEOUT: 20, - CIRC_EASEINOUT: 21, - - ELASTIC_EASEIN: 22, - ELASTIC_EASEOUT: 23, - ELASTIC_EASEINOUT: 24, - - BACK_EASEIN: 25, - BACK_EASEOUT: 26, - BACK_EASEINOUT: 27, - - BOUNCE_EASEIN: 28, - BOUNCE_EASEOUT: 29, - BOUNCE_EASEINOUT: 30, - - TWEEN_EASING_MAX: 10000 -}; - -ccs.FrameEaseType = { - CUSTOM : -1, - - LINEAR : 0, - - SINE_EASEIN : 1, - SINE_EASEOUT : 2, - SINE_EASEINOUT : 3, - - QUAD_EASEIN : 4, - QUAD_EASEOUT : 5, - QUAD_EASEINOUT : 6, - - CUBIC_EASEIN : 7, - CUBIC_EASEOUT : 8, - CUBIC_EASEINOUT : 9, - - QUART_EASEIN : 10, - QUART_EASEOUT : 11, - QUART_EASEINOUT : 12, - - QUINT_EASEIN : 13, - QUINT_EASEOUT : 14, - QUINT_EASEINOUT : 15, - - EXPO_EASEIN : 16, - EXPO_EASEOUT : 17, - EXPO_EASEINOUT : 18, - - CIRC_EASEIN : 19, - CIRC_EASEOUT : 20, - CIRC_EASEINOUT : 21, - - ELASTIC_EASEIN : 22, - ELASTIC_EASEOUT : 23, - ELASTIC_EASEINOUT : 24, - - BACK_EASEIN : 25, - BACK_EASEOUT : 26, - BACK_EASEINOUT : 27, - - BOUNCE_EASEIN : 28, - BOUNCE_EASEOUT : 29, - BOUNCE_EASEINOUT : 30, - - TWEEN_EASING_MAX: 1000 -}; diff --git a/native/cocos/scripting/js-bindings/script/studio/jsb_studio_boot.js b/native/cocos/scripting/js-bindings/script/studio/jsb_studio_boot.js deleted file mode 100644 index 40a578e336..0000000000 --- a/native/cocos/scripting/js-bindings/script/studio/jsb_studio_boot.js +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2014-2016 Chukong Technologies Inc. - * - * 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. - */ -ccs.armatureDataManager = null; -cc.defineGetterSetter(ccs, "armatureDataManager", function() { - return ccs.ArmatureDataManager.getInstance(); -}); -ccs.ArmatureDataManager.prototype.clear = function() { - ccs.ArmatureDataManager.destroyInstance(); -}; - -/** - * @type {Object} Base singleton object for ccs.ActionManager - * @name ccs.actionManager - */ -ccs.actionManager = ccs.ActionManager.getInstance(); -ccs.ActionManager.prototype.clear = function() { - this.releaseActions(); -}; -ccs.ActionManager.prototype.initWithDictionary = function(file, dic, node, version) { - ccs.actionManager.initWithDictionaryEx(file, JSON.stringify(dic), node, version); -} - -/** - * The same as cc.Node - * @class - * @extends ccs.Class - */ -ccs.Node = ccs.Node || cc.Node; -ccs.Node.extend = ccs.Node.extend || cc.Node.extend; - -/** - * The same as cc.Sprite - * @class - * @extends ccs.Class - */ -ccs.Sprite = ccs.Sprite || cc.Sprite; -ccs.Sprite.extend = ccs.Sprite.extend || cc.Sprite.extend; - -/** - * The same as cc.Component - * @class - * @extends ccs.Class - */ -ccs.Component = ccs.Component || cc.Component; -ccs.Component.extend = ccs.Component.extend || cc.Component.extend; - -ccs.SkinNode = cc.Node; -ccs.BoneNode.extend = cc.Class.extend; -ccs.SkeletonNode.extend = cc.Class.extend; diff --git a/native/cocos/scripting/js-bindings/script/studio/jsb_studio_create_apis.js b/native/cocos/scripting/js-bindings/script/studio/jsb_studio_create_apis.js deleted file mode 100644 index e23980408a..0000000000 --- a/native/cocos/scripting/js-bindings/script/studio/jsb_studio_create_apis.js +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (c) 2014-2016 Chukong Technologies Inc. - * - * 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. - */ - -/************************ Cocostudio *************************/ - -ccs.Armature.prototype._ctor = function(name, parentBone) { - // parentBone !== undefined && ccs.Armature.prototype.init.call(this, name, parentBone); - if(parentBone !== undefined) - ccs.Armature.prototype.init.call(this, name, parentBone); - else if(name !== undefined) - ccs.Armature.prototype.init.call(this, name); -}; - -ccs.Bone.prototype._ctor = function(name) { - name !== undefined && ccs.Bone.prototype.init.call(this, name); -}; - -ccs.ArmatureAnimation.prototype._ctor = function(armature) { - armature !== undefined && ccs.ArmatureAnimation.prototype.init.call(this, armature); -}; - -ccs.Tween.prototype._ctor = function(bone) { - bone !== undefined && ccs.Tween.prototype.init.call(this, bone); -}; - -ccs.BatchNode.prototype._ctor = function() { - ccs.BatchNode.prototype.init.call(this); -}; - -ccs.DecorativeDisplay.prototype._ctor = function() { - ccs.DecorativeDisplay.prototype.init.call(this); -}; - -ccs.DisplayManager.prototype._ctor = function(bone) { - bone !== undefined && ccs.DisplayManager.prototype.init.call(this, bone); -}; - -ccs.Skin.prototype._ctor = function(fileName, rect) { - if (fileName == null || fileName == "") { - ccs.Skin.prototype.init.call(this); - } else { - if(fileName[0] == "#"){ - ccs.Skin.prototype.initWithSpriteFrameName.call(this, fileName.substr(1)); - } else { - rect ? ccs.Skin.prototype.initWithFile.call(this, fileName, rect) - : ccs.Skin.prototype.initWithFile.call(this, fileName); - } - } -}; - -ccs.ColliderDetector.prototype._ctor = function(bone) { - bone !== undefined && ccs.ColliderDetector.prototype.init.call(this, bone); -}; - -ccs.TriggerObj.prototype._ctor = function() { - ccs.TriggerObj.prototype.init.call(this); -}; - -ccs.ComAttribute.prototype._ctor = function() { - ccs.ComAttribute.prototype.init.call(this); -}; - -ccs.ComAudio.prototype._ctor = function() { - ccs.ComAudio.prototype.init.call(this); -}; - -ccs.ComController.prototype._ctor = function() { - ccs.ComController.prototype.init.call(this); -}; - -ccs.ComRender.prototype._ctor = function() { - ccs.ComRender.prototype.init.call(this); -}; - -ccs.ActionTimelineData.prototype._ctor = function(actionTag) { - if (actionTag !== undefined) - { - ccs.ActionTimelineData.prototype.init.call(this,actionTag); - } -}; - -ccs.ComExtensionData.prototype._ctor = function() { - ccs.ComExtensionData.prototype.init.call(this); -}; - -ccs.BoneNode.prototype._ctor = function (length) { - ccs.BoneNode.prototype.init.call(this); - length !== undefined && this.setDebugDrawLength(length); -}; - -ccs.SkeletonNode.prototype._ctor = function () { - ccs.SkeletonNode.prototype.init.call(this); -}; \ No newline at end of file diff --git a/native/cocos/scripting/js-bindings/script/studio/jsb_studio_load.js b/native/cocos/scripting/js-bindings/script/studio/jsb_studio_load.js deleted file mode 100644 index 74461e748e..0000000000 --- a/native/cocos/scripting/js-bindings/script/studio/jsb_studio_load.js +++ /dev/null @@ -1,245 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 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. - ****************************************************************************/ - -ccs._load = (function(){ - - /** - * load file - * @param {String} file - * @param {String} [type=] - ccui|node|action - * @param {String} [path=] - Resource search path - * @returns {*} - */ - var load = function(file, type, path){ - - var json = cc.loader.getRes(file); - - if(!json) - return cc.log("%s does not exist", file); - var ext = extname(file).toLocaleLowerCase(); - if(ext !== "json" && ext !== "exportjson") - return cc.log("%s load error, must be json file", file); - - var parse; - if(!type){ - if(json["widgetTree"]) - parse = parser["ccui"]; - else if(json["nodeTree"]) - parse = parser["timeline"]; - else if(json["Content"] && json["Content"]["Content"]) - parse = parser["timeline"]; - else if(json["gameobjects"]) - parse = parser["scene"]; - }else{ - parse = parser[type]; - } - - if(!parse){ - cc.log("Can't find the parser : %s", file); - return new cc.Node(); - } - var version = json["version"] || json["Version"]; - if(!version && json["armature_data"]){ - cc.warn("%s is armature. please use:", file); - cc.warn(" ccs.armatureDataManager.addArmatureFileInfoAsync(%s);", file); - cc.warn(" var armature = new ccs.Armature('name');"); - return new cc.Node(); - } - var currentParser = getParser(parse, version); - if(!currentParser){ - cc.log("Can't find the parser : %s", file); - return new cc.Node(); - } - - return currentParser.parse(file, json, path) || null; - }; - - var parser = { - "ccui": {}, - "timeline": {}, - "action": {}, - "scene": {} - }; - - load.registerParser = function(name, version, target){ - if(!name || !version || !target) - return cc.log("register parser error"); - if(!parser[name]) - parser[name] = {}; - parser[name][version] = target; - }; - - load.getParser = function(name, version){ - if(name && version) - return parser[name] ? parser[name][version] : undefined; - if(name) - return parser[name]; - return parser; - }; - - //Gets the file extension - var extname = function(fileName){ - var arr = fileName.match(extnameReg); - return ( arr && arr[1] ) ? arr[1] : null; - }; - var extnameReg = /\.([^\.]+)$/; - - - var parserReg = /([^\.](\.\*)?)*$/; - var getParser = function(parser, version){ - if(parser[version]) - return parser[version]; - else if(version === "*") - return null; - else - return getParser(parser, version.replace(parserReg, "*")); - }; - - return load; - -})(); - -ccs._parser = cc.Class.extend({ - - ctor: function(){ - this.parsers = {}; - }, - - _dirnameReg: /\S*\//, - _dirname: function(path){ - var arr = path.match(this._dirnameReg); - return (arr && arr[0]) ? arr[0] : ""; - }, - - getClass: function(json){ - return json["classname"]; - }, - - getNodeJson: function(json){ - return json["widgetTree"]; - }, - - parse: function(file, json, resourcePath){ - resourcePath = resourcePath || this._dirname(file); - this.pretreatment(json, resourcePath); - var node = this.parseNode(this.getNodeJson(json), resourcePath, file); - node && this.deferred(json, resourcePath, node, file); - return node; - }, - - pretreatment: function(json, resourcePath, file){}, - - deferred: function(json, resourcePath, node, file){}, - - parseNode: function(json, resourcePath){ - var parser = this.parsers[this.getClass(json)]; - var widget = null; - if(parser) - widget = parser.call(this, json, resourcePath); - else - cc.log("Can't find the parser : %s", this.getClass(json)); - - return widget; - }, - - registerParser: function(widget, parse){ - this.parsers[widget] = parse; - } -}); - -/** - * Analysis of studio JSON file - * The incoming file name, parse out the corresponding object - * Temporary support file list: - * ui 1.* - * node 1.* - 2.* - * action 1.* - 2.* - * scene 0.* - 1.* - * @param {String} file - * @param {String} [path=] Resource path - * @returns {{node: cc.Node, action: cc.Action}} - */ -ccs.load = function(file, path){ - var object = { - node: null, - action: null - }; - - object.node = ccs._load(file, null, path); - object.action = ccs._load(file, "action", path); - if(object.action && object.action.tag === -1 && object.node) - object.action.tag = object.node.tag; - return object; -}; - -/** - * Analysis of studio JSON file and layout ui widgets by visible size. - * The incoming file name, parse out the corresponding object - * Temporary support file list: - * ui 1.* - * node 1.* - 2.* - * action 1.* - 2.* - * scene 0.* - 1.* - * @param {String} file - * @param {String} [path=] Resource path - * @returns {{node: cc.Node, action: cc.Action}} - */ -ccs.loadWithVisibleSize = function(file, path){ - var object = ccs.load(file, path); - var size = cc.director.getVisibleSize(); - if(object.node && size){ - object.node.setContentSize(size.width, size.height); - ccui.helper.doLayout(object.node); - } - return object; -}; - -//Forward compatible interface - -ccs.actionTimelineCache = { - - - //@deprecated This function will be deprecated sooner or later please use ccs.load - /** - * Create Timeline Action - * @param file - * @returns {*} - */ - createAction: function(file){ - return ccs._load(file, "action"); - } -}; - -ccs.csLoader = { - - //@deprecated This function will be deprecated sooner or later please use ccs.load - /** - * Create Timeline Node - * @param file - * @returns {*} - */ - createNode: function(file){ - return ccs._load(file); - } -}; \ No newline at end of file diff --git a/native/cocos/scripting/js-bindings/script/studio/jsb_studio_property_apis.js b/native/cocos/scripting/js-bindings/script/studio/jsb_studio_property_apis.js deleted file mode 100644 index a7b6795b15..0000000000 --- a/native/cocos/scripting/js-bindings/script/studio/jsb_studio_property_apis.js +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2016 Chukong Technologies Inc. - * - * 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. - */ - -var _proto = ccs.Bone.prototype; -cc.defineGetterSetter(_proto, "color", _proto.getColor, _proto.setColor); -cc.defineGetterSetter(_proto, "opacity", _proto.getOpacity, _proto.setOpacity); -cc.defineGetterSetter(_proto, "zIndex", _proto.getLocalZOrder, _proto.setLocalZOrder); -cc.defineGetterSetter(_proto, "boneData", _proto.getBoneData, _proto.setBoneData); -cc.defineGetterSetter(_proto, "armature", _proto.getArmature, _proto.setArmature); -cc.defineGetterSetter(_proto, "parentBone", _proto.getParentBone, _proto.setParentBone); -cc.defineGetterSetter(_proto, "childArmature", _proto.getChildArmature, _proto.setChildArmature); -cc.defineGetterSetter(_proto, "childrenBone", _proto.getChildrenBone); -cc.defineGetterSetter(_proto, "tween", _proto.getTween); -cc.defineGetterSetter(_proto, "tweenData", _proto.getTweenData); -cc.defineGetterSetter(_proto, "transformDirty", _proto.getTransformDirty, _proto.setTransformDirty); -cc.defineGetterSetter(_proto, "colliderFilter", _proto.getColliderFilter, _proto.setColliderFilter); -cc.defineGetterSetter(_proto, "displayManager", _proto.getDisplayManager, _proto.setDisplayManager); -cc.defineGetterSetter(_proto, "ignoreMovementBoneData", _proto.getIgnoreMovementBoneData, _proto.setIgnoreMovementBoneData); -cc.defineGetterSetter(_proto, "name", _proto.getName, _proto.setName); -cc.defineGetterSetter(_proto, "blendDirty", _proto.getBlendDirty, _proto.setBlendDirty); - -_proto = ccs.Armature.prototype; -cc.defineGetterSetter(_proto, "parentBone", _proto.getParentBone, _proto.setParentBone); -cc.defineGetterSetter(_proto, "animation", _proto.getAnimation, _proto.setAnimation); -cc.defineGetterSetter(_proto, "armatureData", _proto.getArmatureData, _proto.setArmatureData); -cc.defineGetterSetter(_proto, "name", _proto.getName, _proto.setName); -cc.defineGetterSetter(_proto, "batchNode", _proto.getBatchNode, _proto.setBatchNode); -cc.defineGetterSetter(_proto, "version", _proto.getVersion, _proto.setVersion); -cc.defineGetterSetter(_proto, "body", _proto.getBody, _proto.setBody); -cc.defineGetterSetter(_proto, "colliderFilter", _proto.setColliderFilter); - -_proto = ccs.Skin.prototype; -cc.defineGetterSetter(_proto, "skinData", _proto.getSkinData, _proto.setSkinData); -cc.defineGetterSetter(_proto, "bone", _proto.getBone, _proto.setBone); -cc.defineGetterSetter(_proto, "displayName", _proto.getDisplayName); - -_proto = ccs.ColliderDetector.prototype; -cc.defineGetterSetter(_proto, "colliderFilter", _proto.getColliderFilter, _proto.setColliderFilter); -cc.defineGetterSetter(_proto, "active", _proto.getActive, _proto.setActive); -cc.defineGetterSetter(_proto, "body", _proto.getBody, _proto.setBody); diff --git a/native/cocos/scripting/js-bindings/script/studio/parsers/action-1.x.js b/native/cocos/scripting/js-bindings/script/studio/parsers/action-1.x.js deleted file mode 100644 index fcd779a1a8..0000000000 --- a/native/cocos/scripting/js-bindings/script/studio/parsers/action-1.x.js +++ /dev/null @@ -1,239 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 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. - ****************************************************************************/ - -(function(load, baseParser){ - - var cache = {}; - - var Parser = baseParser.extend({ - - getNodeJson: function(json){ - return json["action"]; - }, - - parseNode: function(json, resourcePath, file){ - if(!json) - return null; - if(cache[file]) - return cache[file].clone(); - - var self = this, - action = new ccs.ActionTimeline(); - - action.setDuration(json["duration"]); - action.setTimeSpeed(json["speed"] || 1); - //The process of analysis - var timelines = json["timelines"]; - timelines.forEach(function(timeline){ - var parser = self.parsers[timeline["frameType"]]; - var frame; - if(parser) - frame = parser.call(self, timeline, resourcePath); - else - cc.log("parser does not exist : %s", timeline["frameType"]); - if(frame) - action.addTimeline(frame); - - if(timeline["frameType"] === "ColorFrame"){ - action.addTimeline( - self.parsers["AlphaFrame"].call(self, timeline, resourcePath) - ); - } - }); - - cache[file] = action; - cache[file].retain(); - return action.clone(); - } - - }); - - var parser = new Parser(); - - var frameList = [ - { - name: "PositionFrame", - handle: function(options){ - var frame = new ccs.PositionFrame(); - var x = options["x"]; - var y = options["y"]; - frame.setPosition(cc.p(x,y)); - return frame; - } - }, - { - name: "VisibleFrame", - handle: function(options){ - var frame = new ccs.VisibleFrame(); - var visible = options["value"]; - frame.setVisible(visible); - return frame; - } - }, - { - name: "ScaleFrame", - handle: function(options){ - var frame = new ccs.ScaleFrame(); - var scalex = options["x"]; - var scaley = options["y"]; - frame.setScaleX(scalex); - frame.setScaleY(scaley); - return frame; - } - }, - { - name: "RotationFrame", - handle: function(options){ - var frame = new ccs.RotationFrame(); - var rotation = options["rotation"]; - frame.setRotation(rotation); - return frame; - } - }, - { - name: "SkewFrame", - handle: function(options){ - var frame = new ccs.SkewFrame(); - var skewx = options["x"]; - var skewy = options["y"]; - frame.setSkewX(skewx); - frame.setSkewY(skewy); - return frame; - } - }, - { - name: "RotationSkewFrame", - handle: function(options){ - var frame = new ccs.RotationSkewFrame(); - var skewx = options["x"]; - var skewy = options["y"]; - frame.setSkewX(skewx); - frame.setSkewY(skewy); - return frame; - } - }, - { - name: "AnchorFrame", - handle: function(options){ - var frame = new ccs.AnchorPointFrame(); - var anchorx = options["x"]; - var anchory = options["y"]; - frame.setAnchorPoint(cc.p(anchorx, anchory)); - return frame; - } - }, - { - name: "InnerActionFrame", - handle: function(options){ - var frame = new ccs.InnerActionFrame(); - var type = options["innerActionType"]; - var startFrame = options["startFrame"]; - frame.setInnerActionType(type); - frame.setStartFrameIndex(startFrame); - return frame; - } - }, - { - name: "ColorFrame", - handle: function(options){ - var frame = new ccs.ColorFrame(); - var red = options["red"]; - var green = options["green"]; - var blue = options["blue"]; - frame.setColor(cc.color(red, green, blue)); - var alphaFrame = new ccs.AlphaFrame(); - var alpha = options["alpha"]; - alphaFrame.setAlpha(alpha); - return frame; - } - }, - { - name: "AlphaFrame", - handle: function(options){ - var frame = new ccs.AlphaFrame(); - var alpha = options["alpha"]; - frame.setAlpha(alpha); - return frame; - } - }, - { - name: "TextureFrame", - handle: function(options){ - var frame = new ccs.TextureFrame(); - var texture = options["value"]; - if(texture != null) { - var path = texture; - var spriteFrame = cc.spriteFrameCache.getSpriteFrame(path); - if(spriteFrame == null){ - var jsonPath = ccs.csLoader.getJsonPath(); - path = jsonPath + texture; - } - frame.setTextureName(path); - } - return frame; - } - }, - { - name: "EventFrame", - handle: function(options){ - var frame = new ccs.EventFrame(); - var evnt = options["value"]; - if(evnt != null) - frame.setEvent(evnt); - return frame; - } - }, - { - name: "ZOrderFrame", - handle: function(options){ - var frame = new ccs.ZOrderFrame(); - var zorder = options["value"]; - frame.setZOrder(zorder); - return frame; - } - } - ]; - - frameList.forEach(function(item){ - parser.registerParser(item.name, function(options, resourcePath){ - var timeline = new ccs.Timeline(); - timeline.setActionTag(options["actionTag"]); - - var frames = options["frames"]; - if(frames && frames.length){ - frames.forEach(function(frameData){ - var frame = item.handle(frameData); - frame.setFrameIndex(frameData["frameIndex"]); - frame.setTween(frameData["tween"]); - timeline.addFrame(frame); - }); - } - return timeline; - }); - }); - - load.registerParser("action", "0.*", parser); - load.registerParser("action", "1.*", parser); - -})(ccs._load, ccs._parser); diff --git a/native/cocos/scripting/js-bindings/script/studio/parsers/action-2.x.js b/native/cocos/scripting/js-bindings/script/studio/parsers/action-2.x.js deleted file mode 100644 index 8204848202..0000000000 --- a/native/cocos/scripting/js-bindings/script/studio/parsers/action-2.x.js +++ /dev/null @@ -1,315 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 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. - ****************************************************************************/ - -(function(load, baseParser){ - - var cache = {}; - - var Parser = baseParser.extend({ - - getNodeJson: function(json){ - return json["Content"]["Content"]["Animation"]; - }, - - parseNode: function(json, resourcePath, file){ - if(!json) - return null; - if(cache[file]) - return cache[file].clone(); - - var self = this, - action = new ccs.ActionTimeline(); - - action.setDuration(json["Duration"]); - action.setTimeSpeed(json["Speed"] || 1); - - //The process of analysis - var timelines = json["Timelines"]; - timelines.forEach(function(timeline){ - var parser = self.parsers[timeline["Property"]]; - var frame; - if(parser) - frame = parser.call(self, timeline, resourcePath); - else - cc.log("parser does not exist : %s", timeline["Property"]); - if(frame) - action.addTimeline(frame); - }); - - cache[file] = action; - cache[file].retain(); - return action.clone(); - }, - - deferred: function(json, resourcePath, action, file){ - var animationlist = json["Content"]["Content"]["AnimationList"]; - var length = animationlist ? animationlist.length : 0; - for (var i = 0; i < length; i++){ - var animationdata = animationlist[i]; - var info = { name: null, startIndex: null, endIndex: null }; - info.name = animationdata["Name"]; - info.startIndex = animationdata["StartIndex"]; - info.endIndex = animationdata["EndIndex"]; - action.addAnimationInfo(info); - } - } - - }); - var parser = new Parser(); - - var frameList = [ - { - name: "Position", - handle: function(options){ - var frame = new ccs.PositionFrame(); - var x = options["X"]; - var y = options["Y"]; - frame.setPosition(cc.p(x,y)); - return frame; - } - }, - { - name: "VisibleForFrame", - handle: function(options){ - var frame = new ccs.VisibleFrame(); - var visible = options["Value"]; - frame.setVisible(visible); - return frame; - } - }, - { - name: "Scale", - handle: function(options){ - var frame = new ccs.ScaleFrame(); - var scalex = options["X"]; - var scaley = options["Y"]; - frame.setScaleX(scalex); - frame.setScaleY(scaley); - return frame; - } - }, - { - name: "Rotation", - handle: function(options){ - var frame = new ccs.RotationFrame(); - var rotation = options["Rotation"] || options["Value"] || 0; - frame.setRotation(rotation); - return frame; - } - }, - { - name: "Skew", - handle: function(options){ - var frame = new ccs.SkewFrame(); - var skewx = options["X"]; - var skewy = options["Y"]; - frame.setSkewX(skewx); - frame.setSkewY(skewy); - return frame; - } - }, - { - name: "RotationSkew", - handle: function(options){ - var frame = new ccs.RotationSkewFrame(); - var skewx = options["X"]; - var skewy = options["Y"]; - frame.setSkewX(skewx); - frame.setSkewY(skewy); - return frame; - } - }, - { - name: "Anchor", - handle: function(options){ - var frame = new ccs.AnchorPointFrame(); - var anchorx = options["X"]; - var anchory = options["Y"]; - frame.setAnchorPoint(cc.p(anchorx, anchory)); - return frame; - } - },{ - name: "AnchorPoint", - handle: function(options){ - var frame = new ccs.AnchorPointFrame(); - var anchorx = options["X"]; - var anchory = options["Y"]; - frame.setAnchorPoint(cc.p(anchorx, anchory)); - return frame; - } - },{ - name: "InnerAction", - handle: function(options){ - var frame = new ccs.InnerActionFrame(); - var type = options["InnerActionType"]; - var startFrame = options["StartFrame"]; - frame.setInnerActionType(type); - frame.setStartFrameIndex(startFrame); - return frame; - } - }, - { - name: "CColor", - handle: function(options){ - var frame = new ccs.ColorFrame(); - var color = options["Color"]; - if(!color) color = {}; - color["R"] = color["R"] === undefined ? 255 : color["R"]; - color["G"] = color["G"] === undefined ? 255 : color["G"]; - color["B"] = color["B"] === undefined ? 255 : color["B"]; - frame.setColor(cc.color(color["R"], color["G"], color["B"])); - return frame; - } - }, - { - name: "Alpha", - handle: function(options){ - var frame = new ccs.AlphaFrame(); - var alpha = options["Value"]; - frame.setAlpha(alpha); - return frame; - } - }, - { - name: "FileData", - handle: function(options, resourcePath){ - var frame, texture, plist, path, spriteFrame; - frame = new ccs.TextureFrame(); - texture = options["TextureFile"]; - if(texture != null) { - plist = texture["Plist"]; - path = texture["Path"]; - spriteFrame = cc.spriteFrameCache.getSpriteFrame(path); - if(!spriteFrame && plist){ - if(cc.loader.getRes(resourcePath + plist)){ - cc.spriteFrameCache.addSpriteFrames(resourcePath + plist); - spriteFrame = cc.spriteFrameCache.getSpriteFrame(path); - }else{ - cc.log("%s need to be preloaded", resourcePath + plist); - } - } - if(spriteFrame == null){ - path = resourcePath + path; - } - frame.setTextureName(path); - } - return frame; - } - }, - { - name: "FrameEvent", - handle: function(options){ - var frame = new ccs.EventFrame(); - var evnt = options["Value"]; - if(evnt != null) - frame.setEvent(evnt); - return frame; - } - }, - { - name: "ZOrder", - handle: function(options){ - var frame = new ccs.ZOrderFrame(); - var zorder = options["Value"]; - frame.setZOrder(zorder); - return frame; - } - }, - { - name: "ActionValue", - handle: function (options) { - - var frame = new ccs.InnerActionFrame(); - var innerActionType = options["InnerActionType"]; - - var currentAnimationFrame = options["CurrentAniamtionName"]; - - var singleFrameIndex = options["SingleFrameIndex"]; - - var frameIndex = options["FrameIndex"]; - if(frameIndex !== undefined) - frame.setFrameIndex(frameIndex); - - frame.setInnerActionType(ccs.InnerActionType[innerActionType]); - frame.setSingleFrameIndex(singleFrameIndex); - - frame.setEnterWithName(true); - if (currentAnimationFrame) - frame.setAnimationName(currentAnimationFrame); - - return frame; - } - }, - { - name: "BlendFunc", - handle: function(options){ - var frame = new ccs.BlendFuncFrame(); - var blendFunc = options["BlendFunc"]; - if(blendFunc && blendFunc["Src"] !== undefined && blendFunc["Dst"] !== undefined) - frame.setBlendFunc(new cc.BlendFunc(blendFunc["Src"], blendFunc["Dst"])); - return frame; - } - } - ]; - - var loadEasingDataWithFlatBuffers = function(frame, options){ - var type = options["Type"]; - frame.setTweenType(type); - var points = options["Points"]; - var result = []; - if(points){ - points.forEach(function(p){ - result.push(p["X"]); - result.push(p["Y"]); - }); - frame.setEasingParams(result); - } - }; - - frameList.forEach(function(item){ - parser.registerParser(item.name, function(options, resourcePath){ - var timeline = new ccs.Timeline(); - timeline.setActionTag(options["ActionTag"]); - - var frames = options["Frames"]; - if(frames && frames.length){ - frames.forEach(function(frameData){ - var frame = item.handle(frameData, resourcePath); - frame.setFrameIndex(frameData["FrameIndex"]); - var tween = frameData["Tween"] != null ? frameData["Tween"] : true; - frame.setTween(tween); - //https://github.com/cocos2d/cocos2d-x/pull/11388/files - var easingData = frameData["EasingData"]; - if(easingData) - loadEasingDataWithFlatBuffers(frame, easingData); - timeline.addFrame(frame); - }); - } - return timeline; - }); - }); - - load.registerParser("action", "*", parser); - -})(ccs._load, ccs._parser); diff --git a/native/cocos/scripting/js-bindings/script/studio/parsers/compatible.js b/native/cocos/scripting/js-bindings/script/studio/parsers/compatible.js deleted file mode 100644 index 6cac678cfc..0000000000 --- a/native/cocos/scripting/js-bindings/script/studio/parsers/compatible.js +++ /dev/null @@ -1,255 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 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. - ****************************************************************************/ - - -/* - This file is for compatibility compatibility with older versions of GUIReader and SceneReader - todo: deprecated all - */ - -(function(){ - - ccs.uiReader = { - - _fileDesignSizes: {}, - - //@deprecated This function will be deprecated sooner or later please use ccs.load - /** - * Create CCUI Node - * @param file - * @returns {*} - */ - widgetFromJsonFile: function(file){ - var json = cc.loader.getRes(cc.path.join(cc.loader.resPath, file)); - if(json) { - this._fileDesignSizes[file] = cc.size(json["designWidth"]||0, json["designHeight"]||0); - } - else { - return null; - } - - var version = json["Version"] || json["version"]; - var versionNum = ccs.uiReader.getVersionInteger(version); - if(!version || versionNum >= 1700){ - cc.warn("Not supported file types, Please try use the ccs.load"); - return null; - } - return ccs._load(file, "ccui"); - }, - - //@deprecated This function will be deprecated sooner or later please use parser.registerParser - /** - * Register a custom Widget reader - * @param classType - * @param ins - * @param object - * @param callback - * @deprecated This function will be deprecated sooner or later please use parser.registerParser - */ - registerTypeAndCallBack: function(classType, ins, object, callback){ - var parser = ccs._load.getParser("ccui")["*"]; - var func = callback.bind(object); - parser.registerParser(classType, function(options, resourcePath){ - var widget = new ins(); - var uiOptions = options["options"]; - object.setPropsFromJsonDictionary && object.setPropsFromJsonDictionary(widget, uiOptions); - this.generalAttributes(widget, uiOptions); - var customProperty = uiOptions["customProperty"]; - if(customProperty) - customProperty = JSON.parse(customProperty); - else - customProperty = {}; - func(classType, widget, customProperty); - this.colorAttributes(widget, uiOptions); - this.anchorPointAttributes(widget, uiOptions); - this.parseChild.call(this, widget, options, resourcePath); - return widget; - }); - }, - - //@deprecated This function will be deprecated sooner or later - /** - * Gets the version number by version string. - * @param {String} version version string. - * @returns {Number} - */ - getVersionInteger: function(version){ - if(!version || typeof version !== "string") return 0; - var arr = version.split("."); - if (arr.length !== 4) - return 0; - var num = 0; - arr.forEach(function(n, i){ - num += n * Math.pow(10, 3 - i); - }); - return num; - }, - - //@deprecated This function will be deprecated sooner or later - /** - * stores the designSize of UI file. - * @param {String} fileName - * @param {cc.Size} size - */ - storeFileDesignSize: function (fileName, size) { - this._fileDesignSizes[fileName] = size; - }, - - //@deprecated This function will be deprecated sooner or later - /** - * Gets the design size by filename. - * @param {String} fileName - * @returns {cc.Size} - */ - getFileDesignSize: function (fileName) { - return this._fileDesignSizes[fileName]; - }, - - //@deprecated This function will be deprecated sooner or later - /** - * Returns the file path - * @returns {string} - */ - getFilePath: function(){ - return this._filePath; - }, - - //@deprecated This function will be deprecated sooner or later - setFilePath: function(path){ - this._filePath = path; - }, - - //@deprecated This function will be deprecated sooner or later - /** - * Returns the parsed object map. (analytic function) - * @returns {Object} - */ - getParseObjectMap: function(){ - return ccs._load.getParser("ccui")["*"]["parsers"]; - }, - - //@deprecated This function will be deprecated sooner or later - /** - * Returns the parsed callback map. (analytic function) - * @returns {*} - */ - getParseCallBackMap: function(){ - return ccs._load.getParser("ccui")["*"]["parsers"]; - }, - - //@deprecated This function will be deprecated sooner or later - clear: function(){} - }; - - var parser = ccs._load.getParser("ccui")["*"]; - ccs.imageViewReader = {setPropsFromJsonDictionary: parser.ImageViewAttributes}; - ccs.buttonReader = {setPropsFromJsonDictionary: parser.ButtonAttributes}; - ccs.checkBoxReader = {setPropsFromJsonDictionary: parser.CheckBoxAttributes}; - ccs.labelAtlasReader = {setPropsFromJsonDictionary: parser.TextAtlasAttributes}; - ccs.labelBMFontReader= {setPropsFromJsonDictionary: parser.TextBMFontAttributes}; - ccs.labelReader = {setPropsFromJsonDictionary: parser.TextAttributes}; - ccs.layoutReader = {setPropsFromJsonDictionary: parser.LayoutAttributes}; - ccs.listViewReader = {setPropsFromJsonDictionary: parser.ListViewAttributes}; - ccs.loadingBarReader = {setPropsFromJsonDictionary: parser.LoadingBarAttributes}; - ccs.pageViewReader = {setPropsFromJsonDictionary: parser.PageViewAttributes}; - ccs.scrollViewReader = {setPropsFromJsonDictionary: parser.ScrollViewAttributes}; - ccs.sliderReader = {setPropsFromJsonDictionary: parser.SliderAttributes}; - ccs.textFieldReader = {setPropsFromJsonDictionary: parser.TextFieldAttributes}; -})(); - -(function(){ - ccs.sceneReader = { - - _node: null, - - //@deprecated This function will be deprecated sooner or later please use ccs.load - /** - * Create Scene Node - * @param file - * @returns {*} - */ - createNodeWithSceneFile: function(file){ - var node = ccs._load(file, "scene"); - this._node = node; - return node; - }, - - /** - * Get a node by tag. - * @param {Number} tag - * @returns {cc.Node|null} - */ - getNodeByTag: function(tag){ - if (this._node == null) - return null; - if (this._node.getTag() === tag) - return this._node; - return this._nodeByTag(this._node, tag); - }, - - _nodeByTag: function (parent, tag) { - if (parent == null) - return null; - var retNode = null; - var children = parent.getChildren(); - for (var i = 0; i < children.length; i++) { - var child = children[i]; - if (child && child.getTag() === tag) { - retNode = child; - break; - } else { - retNode = this._nodeByTag(child, tag); - if (retNode) - break; - } - } - return retNode; - }, - - //@deprecated This function will be deprecated sooner or later - /** - * Returns the version of ccs.SceneReader. - * @returns {string} - */ - version: function(){ - return "*"; - }, - - //@deprecated This function will be deprecated sooner or later - /** - * Sets the listener to reader. - * Cannot use - */ - setTarget: function(){}, - - //@deprecated This function will be deprecated sooner or later - /** - * Clear all triggers and stops all sounds. - */ - clear: function(){ - ccs.triggerManager.removeAll(); - cc.audioEngine.end(); - } - }; -})(); \ No newline at end of file diff --git a/native/cocos/scripting/js-bindings/script/studio/parsers/scene-1.x.js b/native/cocos/scripting/js-bindings/script/studio/parsers/scene-1.x.js deleted file mode 100644 index cb5b6d256a..0000000000 --- a/native/cocos/scripting/js-bindings/script/studio/parsers/scene-1.x.js +++ /dev/null @@ -1,262 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 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. - ****************************************************************************/ - -(function(load, baseParser){ - - var Parser = baseParser.extend({ - - getNodeJson: function(json){ - return json; - }, - - parseNode: function(json, resourcePath){ - var parser = this.parsers[this.getClass(json)]; - var node = null; - if(parser) - node = parser.call(this, json, resourcePath); - else - cc.log("Can't find the parser : %s", this.getClass(json)); - - return node; - }, - - deferred: function(json, resourcePath, node, file){ - ccs.triggerManager.parse(json["Triggers"]||[]); - if(ccs.sceneReader) - ccs.sceneReader._node = node; - }, - - setPropertyFromJsonDict: function(node, json){ - var x = json["x"] || 0; - var y = json["y"] || 0; - node.setPosition(x, y); - - var bVisible = Boolean(cc.isValidValue(json["visible"]) ? json["visible"] : 1); - node.setVisible(bVisible); - - var nTag = cc.isValidValue(json["objecttag"]) ? json["objecttag"] : -1; - node.setTag(nTag); - - var nZorder = json["zorder"] || 0; - node.setLocalZOrder(nZorder); - - var fScaleX = cc.isValidValue(json["scalex"]) ? json["scalex"] : 1; - var fScaleY = cc.isValidValue(json["scaley"]) ? json["scaley"] : 1; - node.setScaleX(fScaleX); - node.setScaleY(fScaleY); - - var fRotationZ = json["rotation"] || 0; - node.setRotation(fRotationZ); - - var sName = json["name"] || ""; - node.setName(sName); - } - - }); - - var parser = new Parser(); - - parser.parseChild = function(node, objects, resourcePath){ - for (var i = 0; i < objects.length; i++) { - var child, - options = objects[i]; - if(options) - child = this.parseNode(options, resourcePath); - if(child) - node.addChild(child); - } - }; - - var componentsParser = { - "CCSprite": function(node, component, resourcePath){ - var child = new cc.Sprite(); - loadTexture(component["fileData"], resourcePath, function(path, type){ - if(type === 0) - child.setTexture(path); - else if(type === 1){ - var spriteFrame = cc.spriteFrameCache.getSpriteFrame(path); - child.setSpriteFrame(spriteFrame); - } - }); - var render = new ccs.ComRender(child, "CCSprite"); - node.addComponent(render); - return render; - }, - "CCTMXTiledMap": function(node, component, resourcePath){ - var child = null; - loadTexture(component["fileData"], resourcePath, function(path, type){ - if(type === 0) - child = new cc.TMXTiledMap(path); - }); - var render = new ccs.ComRender(child, "CCTMXTiledMap"); - node.addComponent(render); - return render; - }, - "CCParticleSystemQuad": function(node, component, resourcePath){ - var child = null; - loadTexture(component["fileData"], resourcePath, function(path, type){ - if(type === 0) - child = new cc.ParticleSystem(path); - else - cc.log("unknown resourcetype on CCParticleSystemQuad!"); - child.setPosition(0, 0); - }); - var render = new ccs.ComRender(child, "CCParticleSystemQuad"); - node.addComponent(render); - return render; - }, - "CCArmature": function(node, component, resourcePath){ - var child = null; - loadTexture(component["fileData"], resourcePath, function(path, type){ - if(type === 0){ - var jsonDict = cc.loader.getRes(path); - if (!jsonDict) cc.log("Please load the resource [%s] first!", path); - var armature_data = jsonDict["armature_data"]; - var subData = armature_data[0]; - var name = subData["name"]; - ccs.armatureDataManager.addArmatureFileInfo(path); - child = new ccs.Armature(name); - } - }); - if(child){ - var render = new ccs.ComRender(child, "CCArmature"); - node.addComponent(render); - var actionName = component["selectedactionname"]; - if (actionName && child.getAnimation()) - child.getAnimation().play(actionName); - - return render; - } - - }, - "CCComAudio": function(node, component, resourcePath){ - var audio = null; - loadTexture(component["fileData"], resourcePath, function(path, type){ - if(type === 0){ - audio = new ccs.ComAudio(); - audio.preloadEffect(path); - var name = component["name"]; - if(name) - audio.setName(name); - node.addComponent(audio); - } - }); - }, - "CCComAttribute": function(node, component, resourcePath){ - var attribute = null; - loadTexture(component["fileData"], resourcePath, function(path, type){ - if(type === 0){ - attribute = new ccs.ComAttribute(); - if (path !== "") - attribute.parse(path); - node.addComponent(attribute); - }else - cc.log("unknown resourcetype on CCComAttribute!"); - }); - return attribute; - }, - "CCBackgroundAudio": function(node, component, resourcePath){ - var audio = null; - loadTexture(component["fileData"], resourcePath, function(path, type){ - if(type === 0){ - audio = new ccs.ComAudio(); - audio.preloadBackgroundMusic(path); - audio.setFile(path);var bLoop = Boolean(component["loop"] || 0); - audio.setLoop(bLoop); - var name = component["name"]; - if(name) - audio.setName(name); - node.addComponent(audio); - audio.playBackgroundMusic(path, bLoop); - } - }); - }, - "GUIComponent": function(node, component, resourcePath){ - var widget = null; - loadTexture(component["fileData"], resourcePath, function(path, type){ - widget = ccs._load(path, "ccui"); - }); - var render = new ccs.ComRender(widget, "GUIComponent"); - node.addComponent(render); - return render; - }, - "CCScene": function(){} - }; - var loadedPlist = {}; - var loadTexture = function(json, resourcePath, cb){ - if(json != null){ - var path = json["path"]; - var type = json["resourceType"]; - var plist = json["plist"]; - if(!path) - return; - if(plist){ - if(cc.loader.getRes(resourcePath + plist)){ - loadedPlist[resourcePath + plist] = true; - cc.spriteFrameCache.addSpriteFrames(resourcePath + plist); - }else{ - if(!loadedPlist[resourcePath + plist]) - cc.log("%s need to be preloaded", resourcePath + plist); - } - } - if(type !== 0) - cb(path, type); - else - cb(resourcePath + path, type); - } - }; - - parser.parseComponents = function(node, json, resourcePath){ - if(!node || !json) - return; - json.forEach(function(component){ - var parser = componentsParser[component["classname"]]; - var render = null; - if(parser) - render = parser(node, component, resourcePath); - else - cc.log("Can't find the component parser : %s", component["classname"]); - var name = component["name"]; - if(render && name){ - render.setName(name); - } - }); - }; - - parser.registerParser("CCNode", function(options, resourcePath){ - var node = new cc.Node(); - this.setPropertyFromJsonDict(node, options); - this.parseChild.call(this, node, options["gameobjects"], resourcePath); - this.parseComponents(node, options["components"], resourcePath); - var size = options["CanvasSize"]; - if (size) - node.setContentSize(cc.size(size["_width"], size["_height"])); - - return node; - }); - - load.registerParser("scene", "*", parser); - - -})(ccs._load, ccs._parser); diff --git a/native/cocos/scripting/js-bindings/script/studio/parsers/timelineParser-1.x.js b/native/cocos/scripting/js-bindings/script/studio/parsers/timelineParser-1.x.js deleted file mode 100644 index 6cf606bdc6..0000000000 --- a/native/cocos/scripting/js-bindings/script/studio/parsers/timelineParser-1.x.js +++ /dev/null @@ -1,293 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 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. - ****************************************************************************/ - -(function(load, baseParser){ - - var loadedPlist = {}; - - var Parser = baseParser.extend({ - - getNodeJson: function(json){ - return json["nodeTree"]; - }, - - addSpriteFrame: function(plists, pngs, resourcePath){ - if(!plists || !pngs || plists.length !== pngs.length) - return; - for (var i = 0; i < plists.length; i++) { - var plist = resourcePath + plists[i]; - if(!cc.loader.getRes(plist) && !loadedPlist[plist]) - cc.log("%s need to be preloaded", plist); - else - loadedPlist[plist] = true; - cc.spriteFrameCache.addSpriteFrames( - plist, - resourcePath + pngs[i] - ); - } - }, - - pretreatment: function(json, resourcePath, file){ - this.addSpriteFrame(json["textures"], json["texturesPng"], resourcePath); - } - - }); - var parser = new Parser(); - - parser.generalAttributes = function(node, options){ - var width = options["width"] !=null ? options["width"] : 0; - var height = options["height"] !=null ? options["height"] : 0; - var x = options["x"] !=null ? options["x"] : 0; - var y = options["y"] !=null ? options["y"] : 0; - var scalex = options["scaleX"] !=null ? options["scaleX"] : 1; - var scaley = options["scaleY"] !=null ? options["scaleY"] : 1; - var rotation = options["rotation"] !=null ? options["rotation"] : 0; - var rotationSkewX = options["rotationSkewX"]!=null ? options["rotationSkewX"] : 0; - var rotationSkewY = options["rotationSkewY"]!=null ? options["rotationSkewY"] : 0; - var skewx = options["skewX"] !=null ? options["skewX"] : 0; - var skewy = options["skewY"] !=null ? options["skewY"] : 0; - var anchorx = options["anchorPointX"] !=null ? options["anchorPointX"] : 0.5; - var anchory = options["anchorPointY"] !=null ? options["anchorPointY"] : 0.5; - var alpha = options["opacity"] !=null ? options["opacity"] : 255; - var red = options["colorR"] !=null ? options["colorR"] : 255; - var green = options["colorG"] !=null ? options["colorG"] : 255; - var blue = options["colorB"] !=null ? options["colorB"] : 255; - var zorder = options["colorR"] !=null ? options["colorR"] : 0; - var tag = options["tag"] !=null ? options["tag"] : 0; - var actionTag = options["actionTag"] !=null ? options["actionTag"] : 0; - var visible = options["visible"] !=null ? options["visible"] : true; - - if(x != 0 || y != 0) - node.setPosition(cc.p(x, y)); - if(scalex != 1) - node.setScaleX(scalex); - if(scaley != 1) - node.setScaleY(scaley); - if (rotation != 0) - node.setRotation(rotation); - if(rotationSkewX != 0) - node.setRotationX(rotationSkewX); - if(rotationSkewY != 0) - node.setRotationY(rotationSkewY); - if(skewx != 0) - node.setSkewX(skewx); - if(skewy != 0) - node.setSkewY(skewy); - if(anchorx != 0.5 || anchory != 0.5) - node.setAnchorPoint(cc.p(anchorx, anchory)); - if(width != 0 || height != 0) - node.setContentSize(cc.size(width, height)); - if(zorder != 0) - node.setLocalZOrder(zorder); - if(visible != true) - node.setVisible(visible); - - if(alpha != 255) - { - node.setOpacity(alpha); - } - if(red != 255 || green != 255 || blue != 255) - { - node.setColor(cc.color(red, green, blue)); - } - - - node.setTag(tag); - node.setUserObject(new ccs.ActionTimelineData(actionTag)); - }; - - parser.parseComponent = function(node, options){ - if(!options) return; - for (var i = 0; i < options.length; ++i){ - var dic = options[i]; - var component = this.loadComponent(dic); - if (component){ - node.addComponent(component); - } - } - }; - - parser.parseChild = function(parse, widget, options, resourcePath){ - var children = options["children"]; - for (var i = 0; i < children.length; i++) { - var child = this.parseNode(children[i], resourcePath); - if(child){ - if(widget instanceof ccui.PageView){ - if(child instanceof ccui.Layout) - widget.addPage(child); - } else { - if(widget instanceof ccui.ListView){ - if(child instanceof ccui.Widget) - widget.pushBackCustomItem(child); - } else { - if(!(widget instanceof ccui.Layout) && child instanceof ccui.Widget) { - if(child.getPositionType() === ccui.Widget.POSITION_PERCENT) { - var position = child.getPositionPercent(); - var anchor = widget.getAnchorPoint(); - child.setPositionPercent(cc.p(position.x + anchor.x, position.y + anchor.y)); - } - //To make up for the studio positioning error problem - var AnchorPointIn = widget.getAnchorPointInPoints(); - child.setPosition(cc.p(child.getPositionX() + AnchorPointIn.x, child.getPositionY() + AnchorPointIn.y)); - } - widget.addChild(child); - } - } - } - } - }; - - parser.initNode = function(options){ - var node = new cc.Node(); - this.generalAttributes(node, options); - return node; - }; - parser.initSubGraph = function(options){ - var filePath = options["fileName"]; - - var node; - if (filePath && "" !== filePath){ - node = this.createNode(filePath); - }else{ - node = new ccs.Node(); - } - this.generalAttributes(node, options); - return node; - }; - parser.initSprite = function(options, resourcePath){ - var path = options["fileName"]; - var sprite; - if(path != null){ - var spriteFrame = cc.spriteFrameCache.getSpriteFrame(path); - if(!spriteFrame){ - path = resourcePath + path; - sprite = new ccs.Sprite(path); - }else{ - sprite = ccs.Sprite.createWithSpriteFrame(spriteFrame); - } - - if(!sprite){ - sprite = new cc.Sprite(); - cc.log("filePath is empty. Create a sprite with no texture"); - } - }else{ - sprite = new ccs.Sprite(); - } - this.generalAttributes(sprite, options); - var flipX = options["flipX"]; - var flipY = options["flipY"]; - - if(flipX != false) - sprite.setFlippedX(flipX); - if(flipY != false) - sprite.setFlippedY(flipY); - return sprite; - }; - parser.initParticle = function(options, resourcePath){ - var filePath = options["plistFile"]; - var num = options["tmxFile"]; - var particle = new cc.ParticleSystemQuad(filePath); - particle.setTotalParticles(num); - this.generalAttributes(particle, options); - return particle; - }; - parser.initTMXTiledMap = function(options, resourcePath){ - var tmxFile = options["tmxFile"]; - var tmxString = options["tmxString"]; - //todo check path and resourcePath - var path = options["resourcePath"]; - - var tmx = null; - if (tmxFile && "" !== tmxFile){ - tmx = new cc.TMXTiledMap(tmxFile); - }else if (tmxString && "" !== tmxString && path && "" !== path){ - tmx = new cc.TMXTiledMap(tmxString, path); - } - return tmx; - }; - var uiParser = load.getParser("ccui")["*"]; - parser.initWidget = function(options, resourcePath){ - var type = options["classname"]; - - var parser = uiParser.parsers[type]; - if(!parser) - return cc.log("%s parser is not found", type); - - var node = parser.call(uiParser, options, resourcePath); - if(node){ - var rotationSkewX = options["rotationSkewX"]; - var rotationSkewY = options["rotationSkewY"]; - var skewx = options["skewX"]; - var skewy = options["skewY"]; - if(rotationSkewX != 0) - node.setRotationX(rotationSkewX); - if(rotationSkewY != 0) - node.setRotationY(rotationSkewY); - if(skewx != 0) - node.setSkewX(skewx); - if(skewy != 0) - node.setSkewY(skewy); - - var actionTag = options["actionTag"]; - node.setUserObject(new ccs.ActionTimelineData(actionTag)); - } - return node; - }; - - var register = [ - {name: "Node", handle: parser.initNode}, - {name: "SubGraph", handle: parser.initSubGraph}, - {name: "Sprite", handle: parser.initSprite}, - {name: "Particle", handle: parser.initParticle}, - {name: "TMXTiledMap", handle: parser.initTMXTiledMap}, - - {name: "Widget", handle: parser.initWidget}, - {name: "Panel", handle: parser.initWidget}, - {name: "Button", handle: parser.initWidget}, - {name: "CheckBox", handle: parser.initWidget}, - {name: "ImageView", handle: parser.initWidget}, - {name: "LabelAtlas", handle: parser.initWidget}, - {name: "LabelBMFont", handle: parser.initWidget}, - {name: "Label", handle: parser.initWidget}, - {name: "ListView", handle: parser.initWidget}, - {name: "LoadingBar", handle: parser.initWidget}, - {name: "PageView", handle: parser.initWidget}, - {name: "ScrollView", handle: parser.initWidget}, - {name: "Slider", handle: parser.initWidget}, - {name: "TextField", handle: parser.initWidget} - ]; - - register.forEach(function(item){ - parser.registerParser(item.name, function(options, parse, resourcePath){ - var node = item.handle.call(this, options["options"]); - this.parseComponent(node, options["components"]); - this.parseChild(parse, node, options, resourcePath); - return node; - }); - }); - - load.registerParser("timeline", "0.*", parser); - load.registerParser("timeline", "1.*", parser); - -})(ccs._load, ccs._parser); diff --git a/native/cocos/scripting/js-bindings/script/studio/parsers/timelineParser-2.x.js b/native/cocos/scripting/js-bindings/script/studio/parsers/timelineParser-2.x.js deleted file mode 100644 index 12d956436f..0000000000 --- a/native/cocos/scripting/js-bindings/script/studio/parsers/timelineParser-2.x.js +++ /dev/null @@ -1,1359 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 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. - ****************************************************************************/ - -(function(load, baseParser){ - - var DEBUG = false; - - var Parser = baseParser.extend({ - - parse: function(file, json, path){ - var resourcePath; - if(path !== undefined) - resourcePath = path; - else - resourcePath = this._dirname(file); - this.pretreatment(json, resourcePath, file); - var node = this.parseNode(this.getNodeJson(json), resourcePath); - this.deferred(json, resourcePath, node, file); - return node; - }, - - getNodeJson: function(json){ - var content = json["Content"]; - if(content["ObjectData"]) - return content["ObjectData"]; - - return content["Content"]["ObjectData"]; - }, - - getClass: function(json){ - return json["ctype"]; - } - - }); - var parser = new Parser(); - - - var getParam = function(value, dValue){ - if(value === undefined) - return dValue; - else - return value; - }; - - ////////// - // NODE // - ////////// - - parser.generalAttributes = function(node, json){ - if(json["Name"] != null) - node.setName(json["Name"]); - - var position = json["Position"]; - if(position != null && (position["X"] != null || position["Y"] != null)) - node.setPosition(cc.p(position["X"]||0, position["Y"]||0)); - - var scale = json["Scale"]; - if(scale != null){ - if(scale["ScaleX"] != null) - node.setScaleX(scale["ScaleX"]); - if(scale["ScaleY"] != null) - node.setScaleY(scale["ScaleY"]); - } - - var rotationSkewX = json["RotationSkewX"]; - if (rotationSkewX != null) - node.setRotationX(rotationSkewX); - - var rotationSkewY = json["RotationSkewY"]; - if (json["RotationSkewY"] != null) - node.setRotationY(rotationSkewY); - - var anchor = json["AnchorPoint"]; - if(anchor != null){ - if(anchor["ScaleX"] == null) - anchor["ScaleX"] = 0; - if(anchor["ScaleY"] == null) - anchor["ScaleY"] = 0; - if(anchor["ScaleX"] != 0.5 || anchor["ScaleY"] != 0.5) - node.setAnchorPoint(cc.p(anchor["ScaleX"], anchor["ScaleY"])); - } - - if (json["ZOrder"] != null) - node.setLocalZOrder(json["ZOrder"]); - - var visible = getParam(json["VisibleForFrame"], true); - node.setVisible(visible); - - var size = json["Size"]; - if(size) - setContentSize(node, size); - - if (json["Alpha"] != null) - node.setOpacity(json["Alpha"]); - - node.setTag(json["Tag"] || 0); - - var actionTag = json["ActionTag"] || 0; - var extensionData = new ccs.ComExtensionData(); - var customProperty = json["UserData"]; - if(customProperty !== undefined) - extensionData.setCustomProperty(customProperty); - extensionData.setActionTag(actionTag); - if (node.getComponent("ComExtensionData")) - node.removeComponent("ComExtensionData"); - node.addComponent(extensionData); - - node.setCascadeColorEnabled(true); - node.setCascadeOpacityEnabled(true); - - setLayoutComponent(node, json); - }; - - parser.parseChild = function(node, children, resourcePath){ - if(!node || !children) return; - for (var i = 0; i < children.length; i++) { - var child = this.parseNode(children[i], resourcePath); - if(child){ - if(node instanceof ccui.PageView){ - if(child instanceof ccui.Layout) - node.addPage(child); - } else { - if(node instanceof ccui.ListView){ - if(child instanceof ccui.Widget) - node.pushBackCustomItem(child); - } else { - if(!(node instanceof ccui.Layout) && child instanceof ccui.Widget) { - if(child.getPositionType() === ccui.Widget.POSITION_PERCENT) { - var position = child.getPositionPercent(); - var anchor = node.getAnchorPoint(); - child.setPositionPercent(cc.p(position.x + anchor.x, position.y + anchor.y)); - } - } - node.addChild(child); - } - } - } - } - }; - - /** - * SingleNode - * @param json - * @returns {cc.Node} - */ - parser.initSingleNode = function(json, resourcePath){ - var node = new cc.Node(); - - this.generalAttributes(node, json); - var color = json["CColor"]; - if(color != null) - node.setColor(getColor(color)); - - return node; - }; - - /** - * Sprite - * @param json - * @param resourcePath - * @returns {cc.Sprite} - */ - parser.initSprite = function(json, resourcePath){ - var node = new cc.Sprite(); - - loadTexture(json["FileData"], resourcePath, function(path, type){ - if(type === 0) - node.setTexture(path); - else if(type === 1){ - var spriteFrame = cc.spriteFrameCache.getSpriteFrame(path); - if(spriteFrame) - node.setSpriteFrame(spriteFrame); - } - }); - - var blendData = json["BlendFunc"]; - if(json["BlendFunc"]) { - var blendFunc = cc.BlendFunc.ALPHA_PREMULTIPLIED; - if (blendData["Src"] !== undefined) - blendFunc.src = blendData["Src"]; - if (blendData["Dst"] !== undefined) - blendFunc.dst = blendData["Dst"]; - node.setBlendFunc(blendFunc); - } - - if(json["FlipX"]) - node.setFlippedX(true); - if(json["FlipY"]) - node.setFlippedY(true); - - this.generalAttributes(node, json); - var color = json["CColor"]; - if(color != null) - node.setColor(getColor(color)); - - return node; - }; - - /** - * Particle - * @param json - * @param resourcePath - * @returns {*} - */ - parser.initParticle = function(json, resourcePath){ - var node, - self = this; - loadTexture(json["FileData"], resourcePath, function(path, type){ - node = new cc.ParticleSystem(path); - self.generalAttributes(node, json); - node.setPositionType(cc.ParticleSystem.TYPE_GROUPED); - !cc.sys.isNative && node.setDrawMode(cc.ParticleSystem.TEXTURE_MODE); - - var blendData = json["BlendFunc"]; - if(json["BlendFunc"]){ - var blendFunc = cc.BlendFunc.ALPHA_PREMULTIPLIED; - if(blendData["Src"] !== undefined) - blendFunc.src = blendData["Src"]; - if(blendData["Dst"] !== undefined) - blendFunc.dst = blendData["Dst"]; - node.setBlendFunc(blendFunc); - } - }); - return node; - }; - - - //////////// - // WIDGET // - //////////// - - parser.widgetAttributes = function (widget, json, enableContent) { - widget.setCascadeColorEnabled(true); - widget.setCascadeOpacityEnabled(true); - - widget.setUnifySizeEnabled(false); - //widget.setLayoutComponentEnabled(true); - widget.ignoreContentAdaptWithSize(false); - !enableContent && setContentSize(widget, json["Size"]); - - var name = json["Name"]; - if (name) - widget.setName(name); - - var actionTag = json["ActionTag"] || 0; - widget.setActionTag(actionTag); - var extensionData = new ccs.ComExtensionData(); - var customProperty = json["UserData"]; - if(customProperty !== undefined) - extensionData.setCustomProperty(customProperty); - extensionData.setActionTag(actionTag); - if (widget.getComponent("ComExtensionData")) - widget.removeComponent("ComExtensionData"); - widget.addComponent(extensionData); - - var rotationSkewX = json["RotationSkewX"]; - if (rotationSkewX) - widget.setRotationX(rotationSkewX); - - var rotationSkewY = json["RotationSkewY"]; - if (rotationSkewY) - widget.setRotationY(rotationSkewY); - - - var flipX = json["FlipX"]; - if (flipX) - widget.setFlippedX(true); - - var flipY = json["FlipY"]; - if (flipY) - widget.setFlippedY(true); - - var zOrder = json["zOrder"]; - if (zOrder != null) - widget.setLocalZOrder(zOrder); - - var visible = getParam(json["VisibleForFrame"], true); - widget.setVisible(visible); - - var alpha = json["Alpha"]; - if (alpha != null) - widget.setOpacity(alpha); - - widget.setTag(json["Tag"] || 0); - - var touchEnabled = json["TouchEnable"] || false; - widget.setTouchEnabled(touchEnabled); - - var callBackType = json["CallBackType"]; - if (callBackType != null) - widget.setCallbackType(callBackType); - - var callBackName = json["CallBackName"]; - if (callBackName) - widget.setCallbackName(callBackName); - - var position = json["Position"]; - if (position != null) - widget.setPosition(position["X"] || 0, position["Y"] || 0); - - var scale = json["Scale"]; - if (scale != null) { - var scaleX = getParam(scale["ScaleX"], 1); - var scaleY = getParam(scale["ScaleY"], 1); - widget.setScaleX(scaleX); - widget.setScaleY(scaleY); - } - - var anchorPoint = json["AnchorPoint"]; - if (anchorPoint != null) - widget.setAnchorPoint(anchorPoint["ScaleX"] || 0, anchorPoint["ScaleY"] || 0); - - var color = json["CColor"]; - if (color != null) - widget.setColor(getColor(color)); - - setLayoutComponent(widget, json); - bindCallback(widget, json); - }; - - var bindCallback = function(widget, json){ - var callBackType = json["CallBackType"]; - var callBackName = json["CallBackName"]; - var callBack = function(e){ - if(typeof widget[callBackName] === "function") - widget[callBackName](e); - }; - if(callBackType === "Click"){ - widget.addClickEventListener(callBack); - }else if(callBackType === "Touch"){ - widget.addTouchEventListener(callBack); - }else if(callBackType === "Event"){ - widget.addCCSEventListener(callBack); - } - }; - - var setLayoutComponent = function(widget, json){ - var layoutComponent = ccui.LayoutComponent.bindLayoutComponent(widget); - if(!layoutComponent) - return; - - var positionXPercentEnabled = json["PositionPercentXEnable"] || json["PositionPercentXEnabled"] || false; - var positionYPercentEnabled = json["PositionPercentYEnable"] || json["PositionPercentYEnabled"] || false; - var positionXPercent = 0, - positionYPercent = 0, - PrePosition = json["PrePosition"]; - if (PrePosition != null) { - positionXPercent = PrePosition["X"] || 0; - positionYPercent = PrePosition["Y"] || 0; - } - var sizeXPercentEnable = json["PercentWidthEnable"] || json["PercentWidthEnabled"] || false; - var sizeYPercentEnable = json["PercentHeightEnable"]|| json["PercentHeightEnabled"] || false; - var sizeXPercent = 0, - sizeYPercent = 0, - PreSize = json["PreSize"]; - if (PrePosition != null) { - sizeXPercent = PreSize["X"] || 0; - sizeYPercent = PreSize["Y"] || 0; - } - var stretchHorizontalEnabled = json["StretchWidthEnable"] || false; - var stretchVerticalEnabled = json["StretchHeightEnable"] || false; - var horizontalEdge = json["HorizontalEdge"]; - var verticalEdge = json["VerticalEdge"]; - var leftMargin = json["LeftMargin"] || 0; - var rightMargin = json["RightMargin"] || 0; - var topMargin = json["TopMargin"] || 0; - var bottomMargin = json["BottomMargin"] || 0; - - layoutComponent.setPositionPercentXEnabled(positionXPercentEnabled); - layoutComponent.setPositionPercentYEnabled(positionYPercentEnabled); - layoutComponent.setPositionPercentX(positionXPercent); - layoutComponent.setPositionPercentY(positionYPercent); - layoutComponent.setPercentWidthEnabled(sizeXPercentEnable); - layoutComponent.setPercentHeightEnabled(sizeYPercentEnable); - layoutComponent.setPercentWidth(sizeXPercent); - layoutComponent.setPercentHeight(sizeYPercent); - layoutComponent.setPercentWidthEnabled(sizeXPercentEnable || sizeYPercentEnable); - layoutComponent.setStretchWidthEnabled(stretchHorizontalEnabled); - layoutComponent.setStretchHeightEnabled(stretchVerticalEnabled); - - var horizontalEdgeType = ccui.LayoutComponent.horizontalEdge.NONE; - if (horizontalEdge === "LeftEdge") { - horizontalEdgeType = ccui.LayoutComponent.horizontalEdge.LEFT; - } else if (horizontalEdge === "RightEdge") { - horizontalEdgeType = ccui.LayoutComponent.horizontalEdge.RIGHT; - } else if (horizontalEdge === "BothEdge") { - horizontalEdgeType = ccui.LayoutComponent.horizontalEdge.CENTER; - } - layoutComponent.setHorizontalEdge(horizontalEdgeType); - - var verticalEdgeType = ccui.LayoutComponent.verticalEdge.NONE; - if (verticalEdge === "TopEdge") { - verticalEdgeType = ccui.LayoutComponent.verticalEdge.TOP; - } else if (verticalEdge === "BottomEdge") { - verticalEdgeType = ccui.LayoutComponent.verticalEdge.BOTTOM; - } else if (verticalEdge === "BothEdge") { - verticalEdgeType = ccui.LayoutComponent.verticalEdge.CENTER; - } - layoutComponent.setVerticalEdge(verticalEdgeType); - - layoutComponent.setTopMargin(topMargin); - layoutComponent.setBottomMargin(bottomMargin); - layoutComponent.setLeftMargin(leftMargin); - layoutComponent.setRightMargin(rightMargin); - - layoutComponent.setVerticalEdge(verticalEdgeType); - - layoutComponent.setTopMargin(topMargin); - layoutComponent.setBottomMargin(bottomMargin); - layoutComponent.setLeftMargin(leftMargin); - layoutComponent.setRightMargin(rightMargin); - }; - - var setLayoutBackground = function(layout, single, first, end){ - if( layout.getBackGroundColorType() === 2 ){ - first = first || {}; - end = end || {}; - layout.setBackGroundColor(getColor(first), getColor(end)); - }else{ - single = single || {}; - layout.setBackGroundColor(getColor(single)); - } - }; - - var setLayoutBackgroundVector = function(widget, vector){ - var x = vector["ScaleX"] || 0; - var y = vector["ScaleY"] || 0; - widget.setBackGroundColorVector(cc.p(x, y)); - }; - - /** - * Layout - * @param json - * @param resourcePath - * @returns {ccui.Layout} - */ - parser.initPanel = function(json, resourcePath){ - var widget = new ccui.Layout(); - this.widgetAttributes(widget, json); - - var clipEnabled = json["ClipAble"] || false; - if(clipEnabled != null) - widget.setClippingEnabled(clipEnabled); - - var colorType = getParam(json["ComboBoxIndex"], 0); - widget.setBackGroundColorType(colorType); - - var bgColorOpacity = getParam(json["BackColorAlpha"], 255); - if(bgColorOpacity != null) - widget.setBackGroundColorOpacity(bgColorOpacity); - - var backGroundScale9Enabled = json["Scale9Enable"]; - if(backGroundScale9Enabled != null) - widget.setBackGroundImageScale9Enabled(backGroundScale9Enabled); - - var opacity = getParam(json["Alpha"], 255); - widget.setOpacity(opacity); - - loadTexture(json["FileData"], resourcePath, function(path, type){ - widget.setBackGroundImage(path, type); - }); - - if(backGroundScale9Enabled){ - var scale9OriginX = json["Scale9OriginX"] || 0; - var scale9OriginY = json["Scale9OriginY"] || 0; - - var scale9Width = json["Scale9Width"] || 0; - var scale9Height = json["Scale9Height"] || 0; - - widget.setBackGroundImageCapInsets(cc.rect( - scale9OriginX, scale9OriginY, scale9Width, scale9Height - )); - - setContentSize(widget, json["Size"]); - }else{ - if (!widget.isIgnoreContentAdaptWithSize()){ - setContentSize(widget, json["Size"]); - } - - } - - setLayoutBackground(widget, json["SingleColor"], json["FirstColor"], json["EndColor"]); - setLayoutBackgroundVector(widget, json["ColorVector"]); - - return widget; - }; - - /** - * Text - * @param json - * @param resourcePath - */ - parser.initText = function(json, resourcePath){ - var widget = new ccui.Text(); - - var touchScaleEnabled = json["TouchScaleChangeAble"]; - if(touchScaleEnabled != null) - widget.setTouchScaleChangeEnabled(touchScaleEnabled); - - var text = json["LabelText"]; - if(text != null) - widget.setString(text); - - var fontSize = json["FontSize"]; - if(fontSize != null) - widget.setFontSize(fontSize); - - var fontName = json["FontName"]; - if(fontName && "" !== fontName) - widget.setFontName(fontName); - - var areaWidth = json["AreaWidth"]; - var areaHeight = json["areaHeight"]; - if(areaWidth && areaHeight) - widget.setTextAreaSize(cc.size(areaWidth, areaHeight)); - - var h_alignment = json["HorizontalAlignmentType"] || "HT_Left"; - switch(h_alignment){ - case "HT_Right": - h_alignment = 2; break; - case "HT_Center": - h_alignment = 1; break; - case "HT_Left": - default: - h_alignment = 0; - } - widget.setTextHorizontalAlignment(h_alignment); - - var v_alignment = json["VerticalAlignmentType"] || "VT_Top"; - switch(v_alignment){ - case "VT_Bottom": - v_alignment = 2; break; - case "VT_Center": - v_alignment = 1; break; - case "VT_Top": - default: - v_alignment = 0; - } - widget.setTextVerticalAlignment(v_alignment); - - var fontResource = json["FontResource"]; - if(fontResource != null){ - var path = fontResource["Path"]; - if(path){ - if (cc.sys.isNative) { - fontName = cc.path.join(cc.loader.resPath, resourcePath, path); - } else { - fontName = path.match(/([^\/]+)\.(\S+)/); - fontName = fontName ? fontName[1] : ""; - } - widget.setFontName(fontName); - } - } - - if(json["OutlineEnabled"] && json["OutlineColor"] && widget.enableOutline) - widget.enableOutline(getColor(json["OutlineColor"]), getParam(json["OutlineSize"], 1)); - - if(json["ShadowEnabled"] && json["ShadowColor"] && widget.enableShadow) - widget.enableShadow( - getColor(json["ShadowColor"]), - cc.size(getParam(json["ShadowOffsetX"], 2), getParam(json["ShadowOffsetY"], -2)), - json["ShadowBlurRadius"] || 0 - ); - - var isCustomSize = json["IsCustomSize"]; - if(isCustomSize != null) - widget.ignoreContentAdaptWithSize(!isCustomSize); - - widget.setUnifySizeEnabled(false); - - var color = json["CColor"]; - json["CColor"] = null; - widget.setTextColor(getColor(color)); - this.widgetAttributes(widget, json, widget.isIgnoreContentAdaptWithSize()); - json["CColor"] = color; - return widget; - }; - - /** - * Button - * @param json - * @param resourcePath - */ - parser.initButton = function(json, resourcePath){ - var widget = new ccui.Button(); - - loadTexture(json["NormalFileData"], resourcePath, function(path, type){ - widget.loadTextureNormal(path, type); - }); - loadTexture(json["PressedFileData"], resourcePath, function(path, type){ - widget.loadTexturePressed(path, type); - }); - loadTexture(json["DisabledFileData"], resourcePath, function(path, type){ - widget.loadTextureDisabled(path, type); - }); - - var scale9Enabled = getParam(json["Scale9Enable"], false); - if(scale9Enabled) { - widget.setScale9Enabled(scale9Enabled); - } - - var text = json["ButtonText"]; - if(text != null) - widget.setTitleText(text); - - var fontSize = json["FontSize"]; - if(fontSize != null) - widget.setTitleFontSize(fontSize); - - var fontName = json["FontName"]; - if(fontName && "" !== fontName) - widget.setTitleFontName(fontName); - - var textColor = json["TextColor"]; - if(textColor != null) - widget.setTitleColor(getColor(textColor)); - - var displaystate = getParam(json["DisplayState"], true); - widget.setBright(displaystate); - widget.setEnabled(displaystate); - - var fontResource = json["FontResource"]; - if(fontResource != null){ - var path = fontResource["Path"]; - if(path){ - if (cc.sys.isNative) { - fontName = cc.path.join(cc.loader.resPath, resourcePath, path); - } else { - fontName = path.match(/([^\/]+)\.(\S+)/); - fontName = fontName ? fontName[1] : ""; - } - widget.setTitleFontName(fontName); - } - } - - var label = widget.getTitleRenderer(); - if(label && json["ShadowEnabled"] && json["ShadowColor"] && label.enableShadow){ - label.enableShadow( - getColor(json["ShadowColor"]), - cc.size(getParam(json["ShadowOffsetX"], 2), getParam(json["ShadowOffsetY"], -2)), - json["ShadowBlurRadius"] || 0 - ); - } - if(label && json["OutlineEnabled"] && json["OutlineColor"] && label.enableStroke) - label.enableStroke(getColor(json["OutlineColor"]), getParam(json["OutlineSize"], 1)); - - this.widgetAttributes(widget, json); - - if(scale9Enabled) { - widget.setUnifySizeEnabled(false); - widget.ignoreContentAdaptWithSize(false); - var capInsets = cc.rect( - json["Scale9OriginX"] || 0, - json["Scale9OriginY"] || 0, - json["Scale9Width"] || 0, - json["Scale9Height"] || 0 - ); - widget.setCapInsets(capInsets); - } - - setContentSize(widget, json["Size"]); - - return widget; - }; - - /** - * CheckBox - * @param json - * @param resourcePath - */ - parser.initCheckBox = function(json, resourcePath){ - var widget = new ccui.CheckBox(); - - this.widgetAttributes(widget, json); - - var dataList = [ - {name: "NormalBackFileData", handle: widget.loadTextureBackGround}, - {name: "PressedBackFileData", handle: widget.loadTextureBackGroundSelected}, - {name: "NodeNormalFileData", handle: widget.loadTextureFrontCross}, - {name: "DisableBackFileData", handle: widget.loadTextureBackGroundDisabled}, - {name: "NodeDisableFileData", handle: widget.loadTextureFrontCrossDisabled} - ]; - - dataList.forEach(function(item){ - loadTexture(json[item.name], resourcePath, function(path, type){ - item.handle.call(widget, path, type); - }); - }); - - var selectedState = getParam(json["CheckedState"], false); - widget.setSelected(selectedState); - - var displaystate = getParam(json["DisplayState"], true); - widget.setBright(displaystate); - widget.setEnabled(displaystate); - - return widget; - }; - - /** - * ScrollView - * @param json - * @param resourcePath - */ - parser.initScrollView = function(json, resourcePath){ - var widget = new ccui.ScrollView(); - - this.widgetAttributes(widget, json); - - loadTexture(json["FileData"], resourcePath, function(path, type){ - widget.setBackGroundImage(path, type); - }); - - var clipEnabled = json["ClipAble"] || false; - widget.setClippingEnabled(clipEnabled); - - var colorType = getParam(json["ComboBoxIndex"], 0); - widget.setBackGroundColorType(colorType); - - var bgColorOpacity = json["BackColorAlpha"]; - if(bgColorOpacity != null) - widget.setBackGroundColorOpacity(bgColorOpacity); - - var backGroundScale9Enabled = json["Scale9Enable"]; - if(backGroundScale9Enabled){ - widget.setBackGroundImageScale9Enabled(true); - - var scale9OriginX = json["Scale9OriginX"] || 0; - var scale9OriginY = json["Scale9OriginY"] || 0; - var scale9Width = json["Scale9Width"] || 0; - var scale9Height = json["Scale9Height"] || 0; - widget.setBackGroundImageCapInsets(cc.rect( - scale9OriginX, scale9OriginY, scale9Width, scale9Height - )); - setContentSize(widget, json["Size"]); - }else if(!widget.isIgnoreContentAdaptWithSize()){ - setContentSize(widget, json["Size"]); - } - - setLayoutBackground(widget, json["SingleColor"], json["FirstColor"], json["EndColor"]); - setLayoutBackgroundVector(widget, json["ColorVector"]); - - var innerNodeSize = json["InnerNodeSize"]; - var innerSize = cc.size( - innerNodeSize["Width"] || 0, - innerNodeSize["Height"] || 0 - ); - widget.setInnerContainerSize(innerSize); - - var direction = 0; - if(json["ScrollDirectionType"] === "Vertical") direction = 1; - if(json["ScrollDirectionType"] === "Horizontal") direction = 2; - if(json["ScrollDirectionType"] === "Vertical_Horizontal") direction = 3; - widget.setDirection(direction); - - var bounceEnabled = getParam(json["IsBounceEnabled"], false); - widget.setBounceEnabled(bounceEnabled); - - return widget; - }; - - /** - * ImageView - * @param json - * @param resourcePath - */ - parser.initImageView = function(json, resourcePath){ - var widget = new ccui.ImageView(); - - loadTexture(json["FileData"], resourcePath, function(path, type){ - widget.loadTexture(path, type); - }); - loadTexture(json["ImageFileData"], resourcePath, function(path, type){ - widget.loadTexture(path, type); - }); - - var scale9Enabled = json["Scale9Enable"]; - if(scale9Enabled){ - widget.setScale9Enabled(true); - widget.setUnifySizeEnabled(false); - widget.ignoreContentAdaptWithSize(false); - - var scale9OriginX = json["Scale9OriginX"] || 0; - var scale9OriginY = json["Scale9OriginY"] || 0; - var scale9Width = json["Scale9Width"] || 0; - var scale9Height = json["Scale9Height"] || 0; - widget.setCapInsets(cc.rect( - scale9OriginX , - scale9OriginY, - scale9Width, - scale9Height - )); - } else - setContentSize(widget, json["Size"]); - - this.widgetAttributes(widget, json); - - return widget; - }; - - /** - * LoadingBar - * @param json - * @param resourcePath - * @returns {ccui.LoadingBar} - */ - parser.initLoadingBar = function(json, resourcePath){ - var widget = new ccui.LoadingBar(); - - this.widgetAttributes(widget, json); - - loadTexture(json["ImageFileData"], resourcePath, function(path, type){ - widget.loadTexture(path, type); - }); - - var direction = json["ProgressType"] === "Right_To_Left" ? 1 : 0; - widget.setDirection(direction); - - var percent = getParam(json["ProgressInfo"], 80); - if(percent != null) - widget.setPercent(percent); - - return widget; - }; - - /** - * Slider - * @param json - * @param resourcePath - */ - parser.initSlider = function(json, resourcePath){ - var widget = new ccui.Slider(); - var loader = cc.loader; - - this.widgetAttributes(widget, json); - - var textureList = [ - {name: "BackGroundData", handle: widget.loadBarTexture}, - {name: "BallNormalData", handle: widget.loadSlidBallTextureNormal}, - {name: "BallPressedData", handle: widget.loadSlidBallTexturePressed}, - {name: "BallDisabledData", handle: widget.loadSlidBallTextureDisabled}, - {name: "ProgressBarData", handle: widget.loadProgressBarTexture} - ]; - textureList.forEach(function(item){ - loadTexture(json[item.name], resourcePath, function(path, type){ - item.handle.call(widget, path, type); - }); - }); - - var percent = json["PercentInfo"] || 0; - widget.setPercent(percent); - - var displaystate = getParam(json["DisplayState"], true); - widget.setBright(displaystate); - widget.setEnabled(displaystate); - - return widget; - }; - - /** - * PageView - * @param json - * @param resourcePath - */ - parser.initPageView = function(json, resourcePath){ - var widget = new ccui.PageView(); - - this.widgetAttributes(widget, json); - - loadTexture(json["FileData"], resourcePath, function(path, type){ - widget.setBackGroundImage(path, type); - }); - - var clipEnabled = json["ClipAble"] || false; - widget.setClippingEnabled(clipEnabled); - - var backGroundScale9Enabled = json["Scale9Enable"]; - if(backGroundScale9Enabled){ - widget.setBackGroundImageScale9Enabled(true); - - var scale9OriginX = json["Scale9OriginX"] || 0; - var scale9OriginY = json["Scale9OriginY"] || 0; - var scale9Width = json["Scale9Width"] || 0; - var scale9Height = json["Scale9Height"] || 0; - widget.setBackGroundImageCapInsets(cc.rect( - scale9OriginX, - scale9OriginY, - scale9Width, - scale9Height - )); - } - - var colorType = getParam(json["ComboBoxIndex"], 0); - widget.setBackGroundColorType(colorType); - - setLayoutBackground(widget, json["SingleColor"], json["FirstColor"], json["EndColor"]); - setLayoutBackgroundVector(widget, json["ColorVector"]); - - var bgColorOpacity = json["BackColorAlpha"]; - if(bgColorOpacity != null) - widget.setBackGroundColorOpacity(bgColorOpacity); - - setContentSize(widget, json["Size"]); - - return widget; - }; - - /** - * ListView - * @param json - * @param resourcePath - * @returns {ccui.ListView} - */ - parser.initListView = function(json, resourcePath){ - var widget = new ccui.ListView(); - - this.widgetAttributes(widget, json); - - loadTexture(json["FileData"], resourcePath, function(path, type){ - widget.setBackGroundImage(path, type); - }); - - var clipEnabled = json["ClipAble"] || false; - widget.setClippingEnabled(clipEnabled); - - var colorType = getParam(json["ComboBoxIndex"], 0); - widget.setBackGroundColorType(colorType); - - var bgColorOpacity = getParam(json["BackColorAlpha"], 255); - var backGroundScale9Enabled = json["Scale9Enable"]; - if(backGroundScale9Enabled){ - widget.setBackGroundImageScale9Enabled(true); - - var scale9OriginX = json["Scale9OriginX"] || 0; - var scale9OriginY = json["Scale9OriginY"] || 0; - var scale9Width = json["Scale9Width"] || 0; - var scale9Height = json["Scale9Height"] || 0; - widget.setBackGroundImageCapInsets(cc.rect( - scale9OriginX, - scale9OriginY, - scale9Width, - scale9Height - )); - } - - var directionType = getParam(json["DirectionType"], ccui.ListView.DIR_HORIZONTAL); - var verticalType = getParam(json["VerticalType"], "Align_Left"); - var horizontalType = getParam(json["HorizontalType"], "Align_Top"); - if(!directionType){ - widget.setDirection(ccui.ScrollView.DIR_HORIZONTAL); - if(verticalType === "Align_Bottom") - widget.setGravity(ccui.ListView.GRAVITY_BOTTOM); - else if(verticalType === "Align_VerticalCenter") - widget.setGravity(ccui.ListView.GRAVITY_CENTER_VERTICAL); - else - widget.setGravity(ccui.ListView.GRAVITY_TOP); - }else if(directionType === "Vertical"){ - widget.setDirection(ccui.ScrollView.DIR_VERTICAL); - if (horizontalType === "") - widget.setGravity(ccui.ListView.GRAVITY_LEFT); - else if (horizontalType === "Align_Right") - widget.setGravity(ccui.ListView.GRAVITY_RIGHT); - else if (horizontalType === "Align_HorizontalCenter") - widget.setGravity(ccui.ListView.GRAVITY_CENTER_HORIZONTAL); - } - - var bounceEnabled = getParam(json["IsBounceEnabled"], false); - widget.setBounceEnabled(bounceEnabled); - - var itemMargin = json["ItemMargin"] || 0; - widget.setItemsMargin(itemMargin); - - var innerSize = json["InnerNodeSize"]; - //Width - if(innerSize != null) - widget.setInnerContainerSize(cc.size(innerSize["Widget"]||0, innerSize["Height"]||0)); - - setLayoutBackground(widget, json["SingleColor"], json["FirstColor"], json["EndColor"]); - setLayoutBackgroundVector(widget, json["ColorVector"]); - - if(bgColorOpacity != null) - widget.setBackGroundColorOpacity(bgColorOpacity); - - setContentSize(widget, json["Size"]); - - return widget; - }; - - /** - * TextAtlas - * @param json - * @param resourcePath - * @returns {ccui.TextAtlas} - */ - parser.initTextAtlas = function(json, resourcePath){ - var widget = new ccui.TextAtlas(); - - var stringValue = json["LabelText"]; - var itemWidth = json["CharWidth"]; - var itemHeight = json["CharHeight"]; - - var startCharMap = json["StartChar"]; - - loadTexture(json["LabelAtlasFileImage_CNB"], resourcePath, function(path, type){ - if(type === 0){ - widget.setProperty(stringValue, path, itemWidth, itemHeight, startCharMap); - } - }); - this.widgetAttributes(widget, json); - - return widget; - }; - - /** - * TextBMFont - * @param json - * @param resourcePath - * @returns {ccui.TextBMFont} - */ - parser.initTextBMFont = function(json, resourcePath){ - var widget = new ccui.TextBMFont(); - this.widgetAttributes(widget, json); - - var text = json["LabelText"]; - if(text) - widget.setString(text); - - loadTexture(json["LabelBMFontFile_CNB"], resourcePath, function(path, type){ - widget.setFntFile(path); - }); - widget.ignoreContentAdaptWithSize(true); - return widget; - }; - - /** - * TextField - * @param json - * @param resourcePath - * @returns {ccui.TextField} - */ - parser.initTextField = function(json, resourcePath){ - var widget = new ccui.TextField(); - - var passwordEnabled = json["PasswordEnable"]; - if(passwordEnabled){ - widget.setPasswordEnabled(true); - var passwordStyleText = json["PasswordStyleText"] || "*"; - widget.setPasswordStyleText(passwordStyleText); - } - - var placeHolder = json["PlaceHolderText"]; - if(placeHolder != null) - widget.setPlaceHolder(placeHolder); - - var fontSize = json["FontSize"]; - if(fontSize != null) - widget.setFontSize(fontSize); - - var fontName = json["FontName"]; - if(fontName && "" !== fontName) - widget.setFontName(fontName); - - var maxLengthEnabled = json["MaxLengthEnable"]; - if(maxLengthEnabled){ - widget.setMaxLengthEnabled(true); - var maxLength = json["MaxLengthText"] || 0; - widget.setMaxLength(maxLength); - } - - //var isCustomSize = json["IsCustomSize"]; - this.widgetAttributes(widget, json); - - var text = json["LabelText"]; - if(text != null) - widget.setString(text); - - var fontResource = json["FontResource"]; - if(fontResource != null){ - var path = fontResource["Path"]; - if(path){ - if (cc.sys.isNative) { - fontName = cc.path.join(cc.loader.resPath, resourcePath, path); - } else { - fontName = path.match(/([^\/]+)\.(\S+)/); - fontName = fontName ? fontName[1] : ""; - } - widget.setFontName(fontName); - } - } - - widget.setUnifySizeEnabled(false); - widget.ignoreContentAdaptWithSize(false); - - var color = json["CColor"]; - if(color != null) - widget.setTextColor(getColor(color)); - - if (!widget.isIgnoreContentAdaptWithSize()){ - setContentSize(widget, json["Size"]); - if (cc.sys.isNative) - widget.getVirtualRenderer().setLineBreakWithoutSpace(true); - } - - return widget; - }; - - /** - * SimpleAudio - * @param json - * @param resourcePath - */ - parser.initSimpleAudio = function(json, resourcePath){ - var node = new ccs.ComAudio(); - var loop = json["Loop"] || false; - //var volume = json["Volume"] || 0; - //cc.audioEngine.setMusicVolume(volume); - node.setLoop(loop); - loadTexture(json["FileData"], resourcePath, function(path, type){ - node.setFile(path); - }); - }; - - /** - * GameMap - * @param json - * @param resourcePath - * @returns {*} - */ - parser.initGameMap = function(json, resourcePath){ - var node = null; - - loadTexture(json["FileData"], resourcePath, function(path, type){ - if(type === 0) - node = new cc.TMXTiledMap(path); - - parser.generalAttributes(node, json); - }); - - return node; - }; - - /** - * ProjectNode - * @param json - * @param resourcePath - * @returns {*} - */ - parser.initProjectNode = function(json, resourcePath){ - var projectFile = json["FileData"]; - if(projectFile != null && projectFile["Path"]){ - var file = resourcePath + projectFile["Path"]; - if(cc.loader.getRes(file)){ - var obj = ccs.load(file, resourcePath); - parser.generalAttributes(obj.node, json); - if(obj.action && obj.node){ - obj.action.tag = obj.node.tag; - var InnerActionSpeed = json["InnerActionSpeed"]; - if(InnerActionSpeed !== undefined) - obj.action.setTimeSpeed(InnerActionSpeed); - obj.node.runAction(obj.action); - obj.action.gotoFrameAndPause(0); - } - return obj.node; - } else - cc.log("%s need to be preloaded", file); - } - }; - - var getFileName = function(name){ - if(!name) return ""; - var arr = name.match(/([^\/]+)\.[^\/]+$/); - if(arr && arr[1]) - return arr[1]; - else - return ""; - }; - - /** - * Armature - * @param json - * @param resourcePath - */ - parser.initArmature = function(json, resourcePath){ - var node = new ccs.Armature(); - var isLoop = json["IsLoop"]; - var isAutoPlay = json["IsAutoPlay"]; - var currentAnimationName = json["CurrentAnimationName"]; - - loadTexture(json["FileData"], resourcePath, function(path, type){ - var plists, pngs; - var armJson = cc.loader.getRes(path); - if(!armJson) - cc.log("%s need to be preloaded", path); - else{ - plists = armJson["config_file_path"]; - pngs = armJson["config_png_path"]; - plists.forEach(function(plist, index){ - if(pngs[index]) - cc.spriteFrameCache.addSpriteFrames(plist, pngs[index]); - }); - } - ccs.armatureDataManager.addArmatureFileInfo(path); - node.init(getFileName(path)); - if(isAutoPlay) - node.getAnimation().play(currentAnimationName, -1, isLoop); - else{ - node.getAnimation().play(currentAnimationName); - node.getAnimation().gotoAndPause(0); - } - }); - - parser.generalAttributes(node, json); - - node.setColor(getColor(json["CColor"])); - return node; - }; - - parser.initBoneNode = function(json, resourcePath){ - var node = new ccs.BoneNode(); - var length = json["Length"]; - if(length !== undefined) - node.setDebugDrawLength(length); - - var blendFunc = json["BlendFunc"]; - if(blendFunc && blendFunc["Src"] !== undefined && blendFunc["Dst"] !== undefined) - node.setBlendFunc(new cc.BlendFunc(blendFunc["Src"] || 0, blendFunc["Dst"] || 0)); - - parser.generalAttributes(node, json); - var color = json["CColor"]; - if(color && (color["R"] !== undefined || color["G"] !== undefined || color["B"] !== undefined)) - node.setColor(getColor(color)); - return node; - }; - - parser.initSkeletonNode = function(json){ - var node = new ccs.SkeletonNode(); - parser.generalAttributes(node, json); - var color = json["CColor"]; - if(color && (color["R"] !== undefined || color["G"] !== undefined || color["B"] !== undefined)) - node.setColor(getColor(color)); - return node; - }; - - var loadedPlist = {}; - var loadTexture = function(json, resourcePath, cb){ - if(json !== undefined && json !== null){ - var path = json["Path"]; - var type; - if(json["Type"] === "Default" || json["Type"] === "Normal") - type = 0; - else - type = 1; - var plist = json["Plist"]; - if(plist){ - if(cc.loader.getRes(resourcePath + plist)){ - loadedPlist[resourcePath + plist] = true; - cc.spriteFrameCache.addSpriteFrames(resourcePath + plist); - }else{ - if(!loadedPlist[resourcePath + plist] && !cc.spriteFrameCache.getSpriteFrame(path)) - cc.log("%s need to be preloaded", resourcePath + plist); - } - } - if(type !== 0){ - if(cc.spriteFrameCache.getSpriteFrame(path)) - cb(path, type); - else - cc.log("failed to get spriteFrame: %s", path); - } - else { - var filePath = resourcePath + path; - if(path && jsb.fileUtils.isFileExist(filePath)) - cb(filePath, type); - else - cb("", type); - } - } - }; - - var getColor = function(json){ - if(json === undefined || json === null) - return cc.color(255,255,255,255); - var r = json["R"] != null ? json["R"] : 255; - var g = json["G"] != null ? json["G"] : 255; - var b = json["B"] != null ? json["B"] : 255; - var a = json["A"] != null ? json["A"] : 255; - - return cc.color(r, g, b, a); - }; - - var setContentSize = function(node, size){ - var x = size["X"] || 0; - var y = size["Y"] || 0; - if(size) - node.setContentSize(cc.size(x, y)); - }; - - var register = [ - {name: "SingleNodeObjectData", handle: parser.initSingleNode}, - {name: "NodeObjectData", handle: parser.initSingleNode}, - {name: "LayerObjectData", handle: parser.initSingleNode}, - {name: "GameNodeObjectData", handle: parser.initSingleNode}, - {name: "GameLayerObjectData", handle: parser.initSingleNode}, - {name: "SpriteObjectData", handle: parser.initSprite}, - {name: "ParticleObjectData", handle: parser.initParticle}, - {name: "PanelObjectData", handle: parser.initPanel}, - {name: "TextObjectData", handle: parser.initText}, - {name: "ButtonObjectData", handle: parser.initButton}, - {name: "CheckBoxObjectData", handle: parser.initCheckBox}, - {name: "ScrollViewObjectData", handle: parser.initScrollView}, - {name: "ImageViewObjectData", handle: parser.initImageView}, - {name: "LoadingBarObjectData", handle: parser.initLoadingBar}, - {name: "SliderObjectData", handle: parser.initSlider}, - {name: "PageViewObjectData", handle: parser.initPageView}, - {name: "ListViewObjectData", handle: parser.initListView}, - {name: "TextAtlasObjectData", handle: parser.initTextAtlas}, - {name: "TextBMFontObjectData", handle: parser.initTextBMFont}, - {name: "TextFieldObjectData", handle: parser.initTextField}, - {name: "SimpleAudioObjectData", handle: parser.initSimpleAudio}, - {name: "GameMapObjectData", handle: parser.initGameMap}, - {name: "ProjectNodeObjectData", handle: parser.initProjectNode}, - {name: "ArmatureNodeObjectData", handle: parser.initArmature}, - {name: "BoneNodeObjectData", handle: parser.initBoneNode}, - {name: "SkeletonNodeObjectData", handle: parser.initSkeletonNode} - ]; - - register.forEach(function(item){ - parser.registerParser(item.name, function(options, resourcePath){ - var node = item.handle.call(this, options, resourcePath); - this.parseChild(node, options["Children"], resourcePath); - DEBUG && node && (node.__parserName = item.name); - return node; - }); - }); - - load.registerParser("timeline", "2.*", parser); - load.registerParser("timeline", "*", parser); - -})(ccs._load, ccs._parser); diff --git a/native/cocos/scripting/js-bindings/script/studio/parsers/uiParser-1.x.js b/native/cocos/scripting/js-bindings/script/studio/parsers/uiParser-1.x.js deleted file mode 100644 index db06a9d7fd..0000000000 --- a/native/cocos/scripting/js-bindings/script/studio/parsers/uiParser-1.x.js +++ /dev/null @@ -1,708 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 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. - ****************************************************************************/ - -(function(load, baseParser){ - - var Parser = baseParser.extend({ - - addSpriteFrame: function(textures, resourcePath){ - if(!textures) return; - for (var i = 0; i < textures.length; i++) { - cc.spriteFrameCache.addSpriteFrames(resourcePath + textures[i]); - } - }, - - pretreatment: function(json, resourcePath){ - this.addSpriteFrame(json["textures"], resourcePath); - }, - - deferred: function(json, resourcePath, node, file){ - if(node){ - var version = json["Version"] || json["version"]; - var versionNum = ccs.uiReader.getVersionInteger(version); - ccs.actionManager.initWithDictionary(file, json["animation"], node, versionNum); - node.setContentSize(cc.size(json["designWidth"], json["designHeight"])); - } - } - - }); - - var parser = new Parser(); - - parser.generalAttributes = function(widget, options){ - var ignoreSizeExsit = options["ignoreSize"]; - if(ignoreSizeExsit != null) - widget.ignoreContentAdaptWithSize(ignoreSizeExsit); - - if (options["sizeType"]) - { - widget.setSizeType(options["sizeType"]); - } - - if (options["positionType"]) - { - widget.setPositionType(options["positionType"]); - } - - widget.setSizePercent(cc.p(options["sizePercentX"], options["sizePercentY"])); - widget.setPositionPercent(cc.p(options["positionPercentX"], options["positionPercentY"])); - - /* adapt screen */ - var w = 0, h = 0; - var adaptScreen = options["adaptScreen"]; - if (adaptScreen) { - var screenSize = cc.director.getWinSize(); - w = screenSize.width; - h = screenSize.height; - } else { - w = options["width"]; - h = options["height"]; - } - widget.setContentSize(w, h); - - widget.setTag(options["tag"]); - widget.setActionTag(options["actiontag"]); - widget.setTouchEnabled(options["touchAble"]); - var name = options["name"]; - var widgetName = name ? name : "default"; - widget.setName(widgetName); - - var x = options["x"]; - var y = options["y"]; - widget.setPosition(x, y); - - var sx = options["scaleX"]!=null ? options["scaleX"] : 1; - widget.setScaleX(sx); - - var sy = options["scaleY"]!=null ? options["scaleY"] : 1; - widget.setScaleY(sy); - - var rt = options["rotation"] || 0; - widget.setRotation(rt); - - var vb = options["visible"] || false; - if(vb != null) - widget.setVisible(vb); - widget.setLocalZOrder(options["ZOrder"]); - - var layout = options["layoutParameter"]; - if(layout != null){ - var layoutParameterDic = options["layoutParameter"]; - var paramType = layoutParameterDic["type"]; - var parameter = null; - - switch(paramType){ - case 0: - break; - case 1: - parameter = new ccui.LinearLayoutParameter(); - var gravity = layoutParameterDic["gravity"]; - parameter.setGravity(gravity); - break; - case 2: - parameter = new ccui.RelativeLayoutParameter(); - var rParameter = parameter; - var relativeName = layoutParameterDic["relativeName"]; - rParameter.setRelativeName(relativeName); - var relativeToName = layoutParameterDic["relativeToName"]; - rParameter.setRelativeToWidgetName(relativeToName); - var align = layoutParameterDic["align"]; - rParameter.setAlign(align); - break; - default: - break; - } - if(parameter != null){ - var mgl = layoutParameterDic["marginLeft"]||0; - var mgt = layoutParameterDic["marginTop"]||0; - var mgr = layoutParameterDic["marginRight"]||0; - var mgb = layoutParameterDic["marginDown"]||0; - parameter.setMargin(mgl, mgt, mgr, mgb); - widget.setLayoutParameter(parameter); - } - } - }; - - parser.colorAttributes = function(widget, options){ - var op = options["opacity"]; - if(op != null) - widget.setOpacity(op); - var colorR = options["colorR"]; - var colorG = options["colorG"]; - var colorB = options["colorB"]; - widget.setColor(cc.color((colorR == null) ? 255 : colorR, (colorG == null) ? 255 : colorG, (colorB == null) ? 255 : colorB)); - - widget.setFlippedX(options["flipX"]); - widget.setFlippedY(options["flipY"]); - }; - - parser.anchorPointAttributes = function(widget, options){ - var isAnchorPointXExists = options["anchorPointX"]; - var anchorPointXInFile; - if (isAnchorPointXExists != null) - anchorPointXInFile = options["anchorPointX"]; - else - anchorPointXInFile = widget.getAnchorPoint().x; - - var isAnchorPointYExists = options["anchorPointY"]; - var anchorPointYInFile; - if (isAnchorPointYExists != null) - anchorPointYInFile = options["anchorPointY"]; - else - anchorPointYInFile = widget.getAnchorPoint().y; - - if (isAnchorPointXExists != null || isAnchorPointYExists != null) - widget.setAnchorPoint(cc.p(anchorPointXInFile, anchorPointYInFile)); - }; - - parser.parseChild = function(widget, options, resourcePath){ - var children = options["children"]; - for (var i = 0; i < children.length; i++) { - var child = this.parseNode(children[i], resourcePath); - if(child){ - if(widget instanceof ccui.PageView) - widget.addPage(child); - else { - if(widget instanceof ccui.ListView){ - widget.pushBackCustomItem(child); - } else { - if(!(widget instanceof ccui.Layout)) { - if(child.getPositionType() === ccui.Widget.POSITION_PERCENT) { - var position = child.getPositionPercent(); - var anchor = widget.getAnchorPoint(); - child.setPositionPercent(cc.p(position.x + anchor.x, position.y + anchor.y)); - } - var AnchorPointIn = widget.getAnchorPointInPoints(); - child.setPosition(cc.p(child.getPositionX() + AnchorPointIn.x, child.getPositionY() + AnchorPointIn.y)); - } - widget.addChild(child); - } - } - } - } - }; - - var getPath = function(res, type, path, cb){ - if(path){ - if(type === 0) - cb(res + path, type); - else - cb(path, type); - } - }; - - /** - * Panel parser (UILayout) - */ - parser.LayoutAttributes = function(widget, options, resourcePath){ - var w = 0, h = 0; - var adaptScreen = options["adaptScreen"]; - if (adaptScreen){ - var screenSize = cc.director.getWinSize(); - w = screenSize.width; - h = screenSize.height; - }else{ - w = options["width"]; - h = options["height"]; - } - widget.setSize(cc.size(w, h)); - - widget.setClippingEnabled(options["clipAble"]); - - var backGroundScale9Enable = options["backGroundScale9Enable"]; - widget.setBackGroundImageScale9Enabled(backGroundScale9Enable); - var cr = options["bgColorR"]; - var cg = options["bgColorG"]; - var cb = options["bgColorB"]; - - var scr = options["bgStartColorR"]; - var scg = options["bgStartColorG"]; - var scb = options["bgStartColorB"]; - - var ecr = options["bgEndColorR"]; - var ecg = options["bgEndColorG"]; - var ecb = options["bgEndColorB"]; - - var bgcv1 = options["vectorX"]; - var bgcv2 = options["vectorY"]; - widget.setBackGroundColorVector(cc.p(bgcv1, bgcv2)); - - var co = options["bgColorOpacity"]; - - var colorType = options["colorType"]; - widget.setBackGroundColorType(colorType/*ui.LayoutBackGroundColorType(colorType)*/); - widget.setBackGroundColor(cc.color(scr, scg, scb), cc.color(ecr, ecg, ecb)); - widget.setBackGroundColor(cc.color(cr, cg, cb)); - widget.setBackGroundColorOpacity(co); - - var imageFileNameDic = options["backGroundImageData"]; - if(imageFileNameDic){ - getPath(resourcePath, imageFileNameDic["resourceType"], imageFileNameDic["path"], function(path, type){ - widget.setBackGroundImage(path, type); - }); - } - - if (backGroundScale9Enable){ - var cx = options["capInsetsX"]; - var cy = options["capInsetsY"]; - var cw = options["capInsetsWidth"]; - var ch = options["capInsetsHeight"]; - widget.setBackGroundImageCapInsets(cc.rect(cx, cy, cw, ch)); - } - if (options["layoutType"]) - { - widget.setLayoutType(options["layoutType"]); - } - }; - /** - * Button parser (UIButton) - */ - parser.ButtonAttributes = function(widget, options, resourcePath){ - var button = widget; - var scale9Enable = options["scale9Enable"]; - button.setScale9Enabled(scale9Enable); - - var normalDic = options["normalData"]; - getPath(resourcePath, normalDic["resourceType"], normalDic["path"], function(path, type){ - button.loadTextureNormal(path, type); - }); - var pressedDic = options["pressedData"]; - getPath(resourcePath, pressedDic["resourceType"], pressedDic["path"], function(path, type){ - button.loadTexturePressed(path, type); - }); - var disabledDic = options["disabledData"]; - getPath(resourcePath, disabledDic["resourceType"], disabledDic["path"], function(path, type){ - button.loadTextureDisabled(path, type); - }); - if (scale9Enable) { - var cx = options["capInsetsX"]; - var cy = options["capInsetsY"]; - var cw = options["capInsetsWidth"]; - var ch = options["capInsetsHeight"]; - - button.setCapInsets(cc.rect(cx, cy, cw, ch)); - var sw = options["scale9Width"]; - var sh = options["scale9Height"]; - if (sw != null && sh != null) - button.setSize(cc.size(sw, sh)); - } - var text = options["text"]; - if (text != null) - button.setTitleText(text); - - var cr = options["textColorR"]; - var cg = options["textColorG"]; - var cb = options["textColorB"]; - var cri = cr!==null?options["textColorR"]:255; - var cgi = cg!==null?options["textColorG"]:255; - var cbi = cb!==null?options["textColorB"]:255; - - button.setTitleColor(cc.color(cri,cgi,cbi)); - var fs = options["fontSize"]; - if (fs != null) - button.setTitleFontSize(options["fontSize"]); - var fn = options["fontName"]; - if (fn) - button.setTitleFontName(options["fontName"]); - }; - /** - * CheckBox parser (UICheckBox) - */ - parser.CheckBoxAttributes = function(widget, options, resourcePath){ - //load background image - var backGroundDic = options["backGroundBoxData"]; - getPath(resourcePath, backGroundDic["resourceType"], backGroundDic["path"], function(path, type){ - widget.loadTextureBackGround(path, type); - }); - - //load background selected image - var backGroundSelectedDic = options["backGroundBoxSelectedData"]; - getPath( - resourcePath, - backGroundSelectedDic["resourceType"] || backGroundDic["resourceType"], - backGroundSelectedDic["path"] || backGroundDic["path"], - function(path, type){ - widget.loadTextureBackGroundSelected(path, type); - }); - - //load frontCross image - var frontCrossDic = options["frontCrossData"]; - getPath(resourcePath, frontCrossDic["resourceType"], frontCrossDic["path"], function(path, type){ - widget.loadTextureFrontCross(path, type); - }); - - //load backGroundBoxDisabledData - var backGroundDisabledDic = options["backGroundBoxDisabledData"]; - getPath( - resourcePath, - backGroundDisabledDic["resourceType"] || frontCrossDic["resourceType"], - backGroundDisabledDic["path"] || frontCrossDic["path"], - function(path, type){ - widget.loadTextureBackGroundDisabled(path, type); - }); - - ///load frontCrossDisabledData - var frontCrossDisabledDic = options["frontCrossDisabledData"]; - getPath(resourcePath, frontCrossDisabledDic["resourceType"], frontCrossDisabledDic["path"], function(path, type){ - widget.loadTextureFrontCrossDisabled(path, type); - }); - - if (options["selectedState"]) - widget.setSelected(options["selectedState"]); - }; - /** - * ImageView parser (UIImageView) - */ - parser.ImageViewAttributes = function(widget, options, resourcePath){ - var imageFileNameDic = options["fileNameData"] - getPath(resourcePath, imageFileNameDic["resourceType"], imageFileNameDic["path"], function(path, type){ - widget.loadTexture(path, type); - }); - - var scale9EnableExist = options["scale9Enable"]; - var scale9Enable = false; - if (scale9EnableExist){ - scale9Enable = options["scale9Enable"]; - } - widget.setScale9Enabled(scale9Enable); - - if (scale9Enable){ - var sw = options["scale9Width"]; - var sh = options["scale9Height"]; - if (sw && sh) - { - var swf = options["scale9Width"]; - var shf = options["scale9Height"]; - widget.setSize(cc.size(swf, shf)); - } - - var cx = options["capInsetsX"]; - var cy = options["capInsetsY"]; - var cw = options["capInsetsWidth"]; - var ch = options["capInsetsHeight"]; - - widget.setCapInsets(cc.rect(cx, cy, cw, ch)); - } - }; - /** - * TextAtlas parser (UITextAtlas) - */ - parser.TextAtlasAttributes = function(widget, options, resourcePath){ - var sv = options["stringValue"]; - var cmf = options["charMapFileData"]; // || options["charMapFile"]; - var iw = options["itemWidth"]; - var ih = options["itemHeight"]; - var scm = options["startCharMap"]; - if (sv != null && cmf && iw != null && ih != null && scm != null){ - var cmftDic = options["charMapFileData"]; - var cmfType = cmftDic["resourceType"]; - switch (cmfType){ - case 0: - var tp_c = resourcePath; - var cmfPath = cmftDic["path"]; - var cmf_tp = tp_c + cmfPath; - widget.setProperty(sv, cmf_tp, iw, ih, scm); - break; - case 1: - cc.log("Wrong res type of LabelAtlas!"); - break; - default: - break; - } - } - }; - /** - * TextBMFont parser (UITextBMFont) - */ - parser.TextBMFontAttributes = function(widget, options, resourcePath){ - var cmftDic = options["fileNameData"]; - var cmfType = cmftDic["resourceType"]; - switch (cmfType) { - case 0: - var tp_c = resourcePath; - var cmfPath = cmftDic["path"]; - var cmf_tp = tp_c + cmfPath; - widget.setFntFile(cmf_tp); - break; - case 1: - cc.log("Wrong res type of LabelAtlas!"); - break; - default: - break; - } - - var text = options["text"]; - widget.setString(text); - }; - /** - * Text parser (UIText) - */ - var regTTF = /\.ttf$/; - parser.TextAttributes = function(widget, options, resourcePath){ - var touchScaleChangeAble = options["touchScaleEnable"]; - widget.setTouchScaleChangeEnabled(touchScaleChangeAble); - - var text = options["text"]; - widget.setString(text); - var fs = options["fontSize"]; - if (fs != null){ - widget.setFontSize(options["fontSize"]); - } - var fn = options["fontName"]; - if (fn != null){ - if(cc.sys.isNative){ - if(regTTF.test(fn)){ - widget.setFontName(cc.path.join(cc.loader.resPath, resourcePath, fn)); - }else{ - widget.setFontName(fn); - } - }else{ - widget.setFontName(fn.replace(regTTF, '')); - } - } - - var aw = options["areaWidth"]; - var ah = options["areaHeight"]; - if (aw != null && ah != null){ - var size = cc.size(options["areaWidth"], options["areaHeight"]); - widget.setTextAreaSize(size); - } - var ha = options["hAlignment"]; - if (ha != null){ - widget.setTextHorizontalAlignment(options["hAlignment"]); - } - var va = options["vAlignment"]; - if (va != null){ - widget.setTextVerticalAlignment(options["vAlignment"]); - } - }; - /** - * ListView parser (UIListView) - */ - parser.ListViewAttributes = function(widget, options, resoutcePath){ - parser.ScrollViewAttributes(widget, options,resoutcePath); - var direction = options["direction"]; - widget.setDirection(direction); - var gravity = options["gravity"]; - widget.setGravity(gravity); - var itemMargin = options["itemMargin"]; - widget.setItemsMargin(itemMargin); - }; - /** - * LoadingBar parser (UILoadingBar) - */ - parser.LoadingBarAttributes = function(widget, options, resourcePath){ - var imageFileNameDic = options["textureData"]; - getPath(resourcePath, imageFileNameDic["resourceType"], imageFileNameDic["path"], function(path, type){ - widget.loadTexture(path, type); - }); - - var scale9Enable = options["scale9Enable"]; - widget.setScale9Enabled(scale9Enable); - - if (scale9Enable){ - var cx = options["capInsetsX"]; - var cy = options["capInsetsY"]; - var cw = options["capInsetsWidth"]; - var ch = options["capInsetsHeight"]; - - widget.setCapInsets(cc.rect(cx, cy, cw, ch)); - - var width = options["width"]; - var height = options["height"]; - widget.setSize(cc.size(width, height)); - } - - widget.setDirection(options["direction"]); - widget.setPercent(options["percent"]); - }; - /** - * PageView parser (UIPageView) - */ - parser.PageViewAttributes = parser.LayoutAttributes; - /** - * ScrollView parser (UIScrollView) - */ - parser.ScrollViewAttributes = function(widget, options, resoutcePath){ - parser.LayoutAttributes(widget, options,resoutcePath); - var innerWidth = options["innerWidth"]!=null ? options["innerWidth"] : 200; - var innerHeight = options["innerHeight"]!=null ? options["innerHeight"] : 200; - widget.setInnerContainerSize(cc.size(innerWidth, innerHeight)); - - var direction = options["direction"]!=null ? options["direction"] : 1; - widget.setDirection(direction); - widget.setBounceEnabled(options["bounceEnable"]); - }; - /** - * Slider parser (UISlider) - */ - parser.SliderAttributes = function(widget, options, resourcePath){ - var slider = widget; - - var barTextureScale9Enable = options["scale9Enable"]; - slider.setScale9Enabled(barTextureScale9Enable); - var bt = options["barFileName"]; - var barLength = options["length"]; - - var imageFileNameDic = options["barFileNameData"]; - var imageFileType = imageFileNameDic["resourceType"]; - var imageFileName = imageFileNameDic["path"]; - - if(bt != null){ - if(barTextureScale9Enable){ - getPath(resourcePath, imageFileType, imageFileName, function(path, type){ - slider.loadBarTexture(path, type); - }); - slider.setSize(cc.size(barLength, slider.getContentSize().height)); - } - }else{ - getPath(resourcePath, imageFileType, imageFileName, function(path, type){ - slider.loadBarTexture(path, type); - }); - } - - var normalDic = options["ballNormalData"]; - getPath(resourcePath, normalDic["resourceType"], normalDic["path"], function(path, type){ - slider.loadSlidBallTextureNormal(path, type); - }); - - var pressedDic = options["ballPressedData"]; - getPath( - resourcePath, - pressedDic["resourceType"] || normalDic["resourceType"], - pressedDic["path"] || normalDic["path"], - function(path, type){ - slider.loadSlidBallTexturePressed(path, type); - }); - - var disabledDic = options["ballDisabledData"]; - getPath(resourcePath, disabledDic["resourceType"], disabledDic["path"], function(path, type){ - slider.loadSlidBallTextureDisabled(path, type); - }); - - var progressBarDic = options["progressBarData"]; - getPath(resourcePath, progressBarDic["resourceType"], progressBarDic["path"], function(path, type){ - slider.loadProgressBarTexture(path, type); - }); - }; - /** - * TextField parser (UITextField) - */ - parser.TextFieldAttributes = function(widget, options, resourcePath){ - var ph = options["placeHolder"]; - if(ph) - widget.setPlaceHolder(ph); - - widget.setString(options["text"]||""); - var fs = options["fontSize1"]; - if(fs) - widget.setFontSize(fs); - var fn = options["fontName"]; - if (fn != null){ - if(cc.sys.isNative){ - if(regTTF.test(fn)){ - widget.setFontName(cc.path.join(cc.loader.resPath, resourcePath, fn)); - }else{ - widget.setFontName(fn); - } - }else{ - widget.setFontName(fn.replace(regTTF, '')); - } - } - - var tsw = options["touchSizeWidth"]; - var tsh = options["touchSizeHeight"]; - if(tsw!=null && tsh!=null) - widget.setTouchSize(tsw, tsh); - - var dw = options["width"]; - var dh = options["height"]; - if(dw > 0 || dh > 0){ - //textField.setSize(cc.size(dw, dh)); - } - var maxLengthEnable = options["maxLengthEnable"]; - widget.setMaxLengthEnabled(maxLengthEnable); - if(maxLengthEnable){ - var maxLength = options["maxLength"]; - widget.setMaxLength(maxLength); - } - - var passwordEnable = options["passwordEnable"]; - widget.setPasswordEnabled(passwordEnable); - if(passwordEnable) - widget.setPasswordStyleText(options["passwordStyleText"]); - - var aw = options["areaWidth"]; - var ah = options["areaHeight"]; - if(aw && ah){ - var size = cc.size(aw, ah); - widget.setTextAreaSize(size); - } - var ha = options["hAlignment"]; - if(ha) - widget.setTextHorizontalAlignment(ha); - var va = options["vAlignment"]; - if(va) - widget.setTextVerticalAlignment(va); - - var r = options["colorR"]; - var g = options["colorG"]; - var b = options["colorB"]; - if (r !== undefined && g !== undefined && b !== undefined) { - widget.setTextColor(cc.color(r, g, b)); - } - }; - - var register = [ - {name: "Panel", object: ccui.Layout, handle: parser.LayoutAttributes}, - {name: "Button", object: ccui.Button, handle: parser.ButtonAttributes}, - {name: "CheckBox", object: ccui.CheckBox, handle: parser.CheckBoxAttributes}, - {name: "ImageView", object: ccui.ImageView, handle: parser.ImageViewAttributes}, - {name: "LabelAtlas", object: ccui.TextAtlas, handle: parser.TextAtlasAttributes}, - {name: "LabelBMFont", object: ccui.TextBMFont, handle: parser.TextBMFontAttributes}, - {name: "Label", object: ccui.Text, handle: parser.TextAttributes}, - {name: "ListView", object: ccui.ListView, handle: parser.ListViewAttributes}, - {name: "LoadingBar", object: ccui.LoadingBar, handle: parser.LoadingBarAttributes}, - {name: "PageView", object: ccui.PageView, handle: parser.PageViewAttributes}, - {name: "ScrollView", object: ccui.ScrollView, handle: parser.ScrollViewAttributes}, - {name: "Slider", object: ccui.Slider, handle: parser.SliderAttributes}, - {name: "TextField", object: ccui.TextField, handle: parser.TextFieldAttributes} - ]; - - register.forEach(function(item){ - parser.registerParser(item.name, function(options, resourcePath){ - var widget = new item.object; - var uiOptions = options["options"]; - parser.generalAttributes(widget, uiOptions); - item.handle(widget, uiOptions, resourcePath); - parser.colorAttributes(widget, uiOptions); - parser.anchorPointAttributes(widget, uiOptions); - parser.parseChild.call(this, widget, options, resourcePath); - return widget; - }); - }); - - load.registerParser("ccui", "*", parser); - -})(ccs._load, ccs._parser);